text:
Q: Having hard time making sense of Stack Trace I am having hard time re-producing the scenario or reading the below error I got on my logs today.. normally the stack trace would point to the file and line number and such but as you can see below it only says nullreference exception without giving me the specific location.. I would appreciate if you can help me read into this and find out what exaclty is happening..
System.Web.HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'. ---> System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
  at ASP.views_reservation_checkout_aspx.__RenderContent2(HtmlTextWriter __w, Control parameterContainer)
  at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
  at ASP.content_kismetvacation_views_shared_site_master.__RenderBodyContent(HtmlTextWriter __w, Control parameterContainer)
  at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
  at ASP.content_kismetvacation_views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer)
  at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
  at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
  at System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer)
  at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  at System.Web.UI.Page.HandleError(Exception e)
  at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  at System.Web.UI.Page.ProcessRequest()
  at System.Web.UI.Page.ProcessRequest(HttpContext context)
  at System.Web.Mvc.ViewPage.ProcessRequest(HttpContext context)
  at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.<>c__DisplayClass4.<Wrap>b__3()
  at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.Wrap[TResult](Func`1 func)
  at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
  at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
  at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage)
  at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
  at System.Web.Mvc.ViewPage.RenderView(ViewContext viewContext)
  at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
  at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass14.<InvokeActionResultWithFilters>b__11()
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
  at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
  at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
  at System.Web.Mvc.Controller.ExecuteCore()
  at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__4()
  at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
  at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
  at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
  at ASP.views_reservation_checkout_aspx.__RenderContent2(HtmlTextWriter __w, Control parameterContainer)
  at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
  at ASP.content_kismetvacation_views_shared_site_master.__RenderBodyContent(HtmlTextWriter __w, Control parameterContainer)
  at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
  at ASP.content_kismetvacation_views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer)
  at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
  at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
  at System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer)
  at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  at System.Web.UI.Page.HandleError(Exception e)
  at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  at System.Web.UI.Page.ProcessRequest()
  at System.Web.UI.Page.ProcessRequest(HttpContext context)
  at System.Web.Mvc.ViewPage.ProcessRequest(HttpContext context)
  at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.<>c__DisplayClass4.<Wrap>b__3()
  at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.Wrap[TResult](Func`1 func)
  at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)

A: The top line of the stack trace is from the deepest point (where the error occurred) and the following lines as it bubbles back up the stack.
I removed the System.* entries (where it dips into the .NET Framework) and what's left are your pages and classes, for the most part. It makes it a bit more readable, maybe more manageable ...
System.Web.HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'. ---> System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
  at ASP.views_reservation_checkout_aspx.__RenderContent2(HtmlTextWriter __w, Control parameterContainer)
  at ASP.content_kismetvacation_views_shared_site_master.__RenderBodyContent(HtmlTextWriter __w, Control parameterContainer)
  at ASP.content_kismetvacation_views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer)

System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
  at ASP.views_reservation_checkout_aspx.__RenderContent2(HtmlTextWriter __w, Control parameterContainer)
  at ASP.content_kismetvacation_views_shared_site_master.__RenderBodyContent(HtmlTextWriter __w, Control parameterContainer)
  at ASP.content_kismetvacation_views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer)

I see your content page in there: *views_reservation_checkout_aspx*
And a view: *content_kismetvacation_views_shared_site_master*
The deepest point shows the web page named ASP.views_reservation_checkout_aspx (ASP/views/reservation/checkout.aspx ?) so you should focus your debugging efforts on the objects and controls in there.
Things to try in that page:

*

*Set breakpoints in Visual Studio

*

*and step through your code line-by-line,

*along the way inspect instances of things for null.

*look for a member call (e.g. method or property)  on an instance that is null.

*fix and repeat

A: Yeah, null reference exceptions can be a little tricky.  It looks like it's happening inside the "reservation checkout" view itself.


text:
Q: Flutter: How to change the MaterialApp theme at runtime I have a MaterialApp Widget that sets the theme for all Widgets within the app.  I'd like to change the MaterialApps theme value at runtime from a child Widget that doesn't have any direct reference to its parent MaterialApp.
It seems like this should be possible because the ThemeData is provided by an InheritedWidget, but I can't figure out how to change the theme wholesale.  Does anyone know how to do this?
Here is the MaterialApp that owns the rest of the app:
new MaterialApp(
    title: 'App Name',
    theme: initialTheme,
    routes: <String, WidgetBuilder>{
      '/' : ...,
    },
),

A: You can also use StreamController.
Just copy and paste this code. It's a working sample.
You don't need any library and it's super simple
import 'dart:async';

import 'package:flutter/material.dart';

StreamController<bool> isLightTheme = StreamController();

main() {
  runApp(MainApp());
}

class MainApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<bool>(
        initialData: true,
        stream: isLightTheme.stream,
        builder: (context, snapshot) {
          return MaterialApp(
              theme: snapshot.data ? ThemeData.light() : ThemeData.dark(),
              debugShowCheckedModeBanner: false,
              home: Scaffold(
                  appBar: AppBar(title: Text("Dynamic Theme")),
                  body: SettingPage()));
        });
  }
}

class SettingPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.all(16.0),
        child: Center(
            child: Row(mainAxisAlignment: MainAxisAlignment.center, children: <
                Widget>[
          RaisedButton(
              color: Colors.blue,
              child: Text("Light Theme", style: TextStyle(color: Colors.white)),
              onPressed: () {
                isLightTheme.add(true);
              }),
          RaisedButton(
              color: Colors.black,
              child: Text("Dark Theme", style: TextStyle(color: Colors.white)),
              onPressed: () {
                isLightTheme.add(false);
              }),
        ])));
  }
}

A: Based on Dan Field's recommendation I came to the following solution.  If anyone has improvements feel free to chime in:
// How to use: Any Widget in the app can access the ThemeChanger
// because it is an InheritedWidget. Then the Widget can call
// themeChanger.theme = [blah] to change the theme. The ThemeChanger
// then accesses AppThemeState by using the _themeGlobalKey, and
// the ThemeChanger switches out the old ThemeData for the new
// ThemeData in the AppThemeState (which causes a re-render).

final _themeGlobalKey = new GlobalKey(debugLabel: 'app_theme');

class AppTheme extends StatefulWidget {

  final child;

  AppTheme({
    this.child,
  }) : super(key: _themeGlobalKey);

  @override
  AppThemeState createState() => new AppThemeState();
}

class AppThemeState extends State<AppTheme> {

  ThemeData _theme = DEV_THEME;

  set theme(newTheme) {
    if (newTheme != _theme) {
      setState(() => _theme = newTheme);
    }
  }

  @override
  Widget build(BuildContext context) {
    return new ThemeChanger(
      appThemeKey: _themeGlobalKey,
      child: new Theme(
        data: _theme,
        child: widget.child,
      ),
    );
  }
}

class ThemeChanger extends InheritedWidget {

  static ThemeChanger of(BuildContext context) {
    return context.inheritFromWidgetOfExactType(ThemeChanger);
  }

  final ThemeData theme;
  final GlobalKey _appThemeKey;

  ThemeChanger({
    appThemeKey,
    this.theme,
    child
  }) : _appThemeKey = appThemeKey, super(child: child);

  set appTheme(AppThemeOption theme) {
    switch (theme) {
      case AppThemeOption.experimental:
        (_appThemeKey.currentState as AppThemeState)?.theme = EXPERIMENT_THEME;
        break;
      case AppThemeOption.dev:
        (_appThemeKey.currentState as AppThemeState)?.theme = DEV_THEME;
        break;
    }
  }

  @override
  bool updateShouldNotify(ThemeChanger oldWidget) {
    return oldWidget.theme == theme;
  }

}

A: This is a specific case of the question answered here: How to force Flutter to rebuild / redraw all widgets?
Take a look at the Stocks sample mentioned in that question, taking note especially of:
https://github.com/flutter/flutter/blob/e7b7ebc066c1b2a5aa5c19f8961307427e0142a6/dev/benchmarks/test_apps/stocks/lib/main.dart
https://github.com/flutter/flutter/blob/e7b7ebc066c1b2a5aa5c19f8961307427e0142a6/dev/benchmarks/test_apps/stocks/lib/stock_settings.dart
Take note of the following:

*

*Theme is specified from _configuration, which is updated by configurationUpdater

*configurationUpdater is passed on to children of the app that need it

*Children can call that configurationUpdater, which in turn sets state at the root of the app, which in turn redraws the app using the specified theme

A: You can use Provider to change that .
1- You have to add Provider in pubspec.yaml file
dependencies:
  flutter:
    sdk: flutter
  provider: ^4.3.2+2

2- Extend a class from  ChangeNotifier to change theme and hold current theme
import 'package:flutter/material.dart';

var darkTheme = ThemeData.dark();
var lightTheme= ThemeData.light();
enum ThemeType { Light, Dark }

class ThemeModel extends ChangeNotifier {
  ThemeData currentTheme = darkTheme;
  ThemeType _themeType = ThemeType.Dark;

  toggleTheme() {
    if (_themeType == ThemeType.Dark) {
      currentTheme = lightTheme;
      _themeType = ThemeType.Light;
    }
    else if (_themeType == ThemeType.Light) {
      currentTheme = darkTheme;
      _themeType = ThemeType.Dark;
    }
    return notifyListeners();
  }
}

3- Add ChangeNotifierProvider as child of runApp
void main() {
  runApp(
    ChangeNotifierProvider<ThemeModel>(
      create: (context) => ThemeModel(),
      child: MyApp(),
    ),
  );
}

4- get current theme on starting app
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'MyApp',
      initialRoute: '/',
      theme: Provider.of<ThemeModel>(context).currentTheme,
      routes: {
        '/': (context) => FirstPage(),
        '/SecondPage': (context) => SecondPage(),
      },
    );

  }

5- Toggle your Theme in Other class
onTap: () {Provider.of<ThemeModel>(context,listen: false).toggleTheme();},

A: You may use ChangeNotifierProvider/Consumer from provider package with combination of ChangeNotifier successor.
/// Theme manager
class ThemeManager extends ChangeNotifier {
  ThemeManager([ThemeData initialTheme]) : _themeData = initialTheme ?? lightTheme;

  ThemeData _themeData;

  /// Returns the current theme
  ThemeData get themeData => _themeData;

  /// Sets the current theme
  set themeData(ThemeData value) {
    _themeData = value;
    notifyListeners();
  }

  /// Dark mode theme
  static ThemeData lightTheme = ThemeData();

  /// Light mode theme
  static ThemeData darkTheme = ThemeData();
}

/// Application
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (_) => ThemeManager(),
      child: Consumer<ThemeManager>(
        builder: (_, manager, __) {
          return MaterialApp(
            title: 'Flutter Demo',
            theme: manager.themeData,
            home: HomePage(),
          );
        },
      ),
    );
  }
}

// Somewhere in GUI
FlatButton(
  child: Text(isDarkMode ? 'Light Mode' : 'Dark Mode'),
  onPressed() {
    Provider.of<ThemeManager>(context, listen:false)
      .themeData = isDarkMode ? ThemeManager.darkTheme : ThemeManager.lightTheme;
  },
),

A: Here's my approach using the built-in flutter's state management solution ChangeNotifier. Which uses AnimatedBuilder to build the MaterialApp whenever the data members (ThemeMode in this case) in the Settings class changes.
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

Settings appSettings = Settings();

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
        animation: appSettings,
        builder: (context, snapshot) {
          return MaterialApp(
            theme: ThemeData.light(),
            darkTheme: ThemeData.dark(),
            themeMode: appSettings.getTheme,
            home: MyAwesomeApp(title: "Dark Theme Sample"),
          );
        });
  }
}

class MyAwesomeApp extends StatefulWidget {
  const MyAwesomeApp({Key? key, required this.title}) : super(key: key);
  final String title;
  @override
  State<MyAwesomeApp> createState() => _MyAwesomeAppState();
}

class _MyAwesomeAppState extends State<MyAwesomeApp> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'Toggle the switch to change the Theme',
            ),
            Switch(
                value: appSettings.getTheme == ThemeMode.dark,
                onChanged: (isDark) {
                  if (isDark) {
                    appSettings.setTheme(ThemeMode.dark);
                  } else {
                    appSettings.setTheme(ThemeMode.light);
                  }
                }),
            Text(
              appSettings.getTheme == ThemeMode.dark ? 'Dark' : 'Light',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
    );
  }
}

class Settings extends ChangeNotifier {
  ThemeMode theme = ThemeMode.light;

  ThemeMode get getTheme => theme;

  void setTheme(ThemeMode theme) {
    this.theme = theme;
    notifyListeners();
  }

  void notifyListeners() {
    super.notifyListeners();
  }
}

Heres the dartpad demo to try it out https://dartpad.dev/?id=c81eccd13f45568ee10c4d160f1560c9

A: Simple Example
Change Themes at Runtime /w StatefulWidget
This copy/paste example changes the app theme between light/dark themes at runtime using StatefulWidget.
(This is the auto-generated Flutter example app from Android Studio, modified.)
What's changed

*

*MyApp changed from StatelessWidget to StatefulWidget (MyStatefulApp)

*static of(context) method added to MyStatefulApp (to find our State object from descendants)

*changeTheme() method added to our State object

*FAB button call to _incrementCounter delegates setState rebuild to MyStatefulApp.of(context).changeTheme(). No need to call setState here.

import 'package:flutter/material.dart';

void main() {
  runApp(MyStatefulApp());
}

/// Change MyApp from StatelessWidget to StatefulWidget
class MyStatefulApp extends StatefulWidget {
  @override

  _MyStatefulAppState createState() => _MyStatefulAppState();

  /// Add an InheritedWidget-style static accessor so we can
  /// find our State object from any descendant & call changeTheme
  /// from anywhere.
  static _MyStatefulAppState of(BuildContext context) =>
      context.findAncestorStateOfType<_MyStatefulAppState>();
}

class _MyStatefulAppState extends State<MyStatefulApp> {
  // define a state field for theme
  ThemeData _theme = ThemeData();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'App Themes',
      theme: _theme, // use theme field here
      home: MyHomePage(title: 'Change App Theme at Runtime'),
    );
  }

  /// Call changeTheme to rebuild app with a new theme
  void changeTheme({ThemeData theme}) {
    setState(() {
      _theme = theme;
    });
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    _counter++;

    // alternate light / dark themes with each FAB press, for illustration
    ThemeData _theme = _counter.isOdd ? ThemeData.dark() : ThemeData();

    /// Find the State object and change the theme, can be done anywhere with
    /// a context
    MyStatefulApp.of(context).changeTheme(theme: _theme);

    // we're rebuilding with changeTheme, so don't duplicate setState call
    /*setState(() {
      _counter++;
    });*/
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You switched themes this many times, happy yet?:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

Notes

*

*You'll see a console warning about a deprecated setter.  Ignore this.  The Flutter team is aware and they'll fix it when they get time.

*to swap between light / dark modes we should really provide a darkTheme and themeMode args to MaterialApp and just change themeMode between ThemeMode.light and ThemeMode.dark instead of changing the theme arg each time.  Using themeMode would support device-wide dark mode from iOS 13 / Android 10 onwards.  The above example was done as-is to answer the question as simply/directly as possible, but isn't ideal for this particular use case.

A: after various attempts I did it with the BLoC pattern, I don't know if it is a good method but it seems to work with no problems:
App theme models:
     class MyTheme {
      Brightness brightness;
      Color backgroundColor;
      Color scaffoldBackgroundColor;
      Color primaryColor;
      Brightness primaryColorBrightness;
      Color accentColor;

      MyTheme({
        this.brightness,
        this.backgroundColor,
        this.scaffoldBackgroundColor,
        this.primaryColor,
        this.primaryColorBrightness,
        this.accentColor
      });
    }

    class AppTheme {
      String name;
      MyTheme theme;
      AppTheme(this.name, this.theme);
    }

    List<AppTheme> myThemes = [
  AppTheme(
      'Default',
      MyTheme(
        brightness: Brightness.light,
        backgroundColor: Colors.blue[50],
        scaffoldBackgroundColor: Colors.blue[50],
        primaryColor: Colors.blue,
        primaryColorBrightness: Brightness.dark,
        accentColor: Colors.blue[50],
      )),
  AppTheme(
    'Teal',
    MyTheme(
      brightness: Brightness.light,
      backgroundColor: Colors.teal[50],
      scaffoldBackgroundColor: Colors.teal[50],
      primaryColor: Colors.teal[600],
      primaryColorBrightness: Brightness.dark,
      accentColor: Colors.teal[50],
    ),
  ),
];

App BLoC class. Here I used a BehaviorSubject of RxDart.
    class AppBloc {

  final _theme = BehaviorSubject<AppTheme>();
  Function(AppTheme) get inTheme => _theme.sink.add;
  Stream<AppTheme> get outTheme => _theme.stream;

  AppBloc() {
    print('-------APP BLOC INIT--------');

    // Send to stream the initial theme
    inTheme(myThemes[0]);
  }

  dispose() {
    print('---------APP BLOC DISPOSE-----------');
    _theme.close();
  }
}

In the settings page of the app I use the _theme stream to set the current theme of a dropdown menu with the themes list. With the onChanged handler, when a user clicks on the theme it is sent to stream:
StreamBuilder(
                    stream: widget.bloc.outTheme,
                    builder: (context, AsyncSnapshot<AppTheme> snapshot) {
                      return snapshot.hasData
                          ? DropdownButton<AppTheme>(
                              hint: Text("Status"),
                              value: snapshot.data,
                              items: myThemes.map((AppTheme appTheme) {
                                return DropdownMenuItem<AppTheme>(
                                  value: appTheme,
                                  child: Text(appTheme.name),
                                );
                              }).toList(),
                              onChanged: widget.bloc.inTheme,
                            )
                          : Container();
                    }),

And finally in the homepage, with a StreamBuilder I use the _theme stream to set the selected ThemeData:
StreamBuilder(
          stream: _bloc.outTheme,
          builder: (context, AsyncSnapshot<AppTheme> snapshot) {
            return MaterialApp(
                theme: snapshot.hasData ? _buildThemeData(snapshot.data) : ThemeData(),
                home: HomePage());
          }),

_BuildThemeData method to get the ThemeData from the theme model:
_buildThemeData(AppTheme appTheme) {
return ThemeData(
  brightness: appTheme.theme.brightness,
  backgroundColor: appTheme.theme.backgroundColor,
  scaffoldBackgroundColor: appTheme.theme.scaffoldBackgroundColor,
  primaryColor: appTheme.theme.primaryColor,
  primaryColorBrightness: appTheme.theme.primaryColorBrightness,
  accentColor: appTheme.theme.accentColor
);

}

I hope this is useful to you.

A: After following @SuperDeclarative Answer do this
At main.dart while making material app
MaterialApp(
      builder: (context, child) {
        return new AppTheme(
            child: YourAppWidget())
})

In any other class where you want to change theme
setState(() {
    ThemeChanger.of(context).appTheme = appThemeLight;
  });

My Tip:

*

*Save to shared pref. at the time changing theme from other class

*Before launching check this preference and open the app with this theme

*After opening follow the above code from any other class

redpajama_set_name: RedPajamaStackExchange


text:
Q: Read basic object properties from PPTX or ODF I need to read a few "basic" information from PPTX or ODF slides, such as objects' position, size, font, color, media source in the case of pictures and videos.
I have been looking around for libraries (PHP / Javascript) or even just for format documentation so to write something from the ground up, but couldn't find anything suitable.
Any good recommendation?


text:
Q: Is there a way to extract only desired text from an image? I am working on a project where I am trying to extract the medicine name just by scanning the entire medicine packet. For example -
Below is the image consisting of the tablet information named 'Health OK'.

My question is whether, by scanning or by using this image, is it possible to extract only the name of the tablet i.e. 'Health OK' ?
I've tried using Pytesseract but it didn't provide me with desired results. Below is the code -
from PIL import Image
import pytesseract, re
f = "ocr.jpg"
t = pytesseract.image_to_string(Image.open(f))
print(t)
m = re.findall(r"[\d—-]+ TABLETS [\d—-]+", t)
if m:
    print(m[0])

Is there any possible solution using ANN or CNN models?

A: My take on this would be to create a variable for the desired text that you want to extract. Once you run an OCR on an image, store its output in a list as well.
For example:
disired_text = 'Health OK'
OCR_output = ['Multivitamin', 'Multiminerals', 'Amino Acids', 'with Taurine', 'Health OK']

Once you have these lists, you can use any string matching algorithm like fuzzy matching to extract the best match from the OCT_output list
For Example:
score_dict = {} #initializing dictionary to store text and score
for output_text in OCR_output:
    score = fuzzy_match_function(output_text, desired_text)
    score_dict[output_text] = score

You will get a score_dict (a dictionary) containing text and scores. You can extract the one that has the minimum distance with your desired variable.
Hope this works out for you!

A: You can train a model if you have sufficient samples by marking the area of text of interest to extract or recognize the area then feeding that area to OCR for extraction  .
From what i see neural network if you have enough data to train on. Probably you can use some sort of transfer learning on an already trained model.
if you don't have labeled data, you can use commercially available annotation tools to mark the area of interest for training.


text:
Q: Need help on getting into a function in C++ Here is the sample of my code:
//Function Declarations
void askChampSearch(string&, string&);

void displayChampDetail(string);

int main()
{
string searchedChamp;
string aboutUser;

cout << "**********YOU'RE GOING TO WANT TO MAKE YOUR PROMPT FULL SCREEN**********" << endl;
cout << "Welcome to my LEAGUE OF LEGENDS info guide!" << endl;
cout << "You can search any champion in League of Legends, and all" << endl;
cout << "of that champions information will be displayed.The information" << endl;
cout << "that will be displayed is: Abilites, Champion Lore, About The Campion, Best Build, and the Champions Wiki Page!" << endl;
cout << endl;

askChampSearch(aboutUser, searchedChamp);
displayChampDetail(searchedChamp);

return 0;
}

//Function Definitions
void askChampSearch(string& UserName, string& searchedChamp){
cout << "Thank you for trying out my program! I really appreciate it! What is your name? (Don't worry, your name isn't stored) ";
    cin >> UserName;
    cout << "Hi " << UserName << ", nice to meet you!" << endl;
    cout << endl;

    cout << "What League of Legends champion would you like to search? ";
    cin >> searchedChamp;
    cout << "The champion that you have searched for was " << searchedChamp << "!";
}

void displayChampDetail(string searchedChamp) {
if (searchedChamp == Ahri) {
    cout << "Ahri is a nine-tailed fox who is a whore" << endl;
    cout << "If Ahri hits you with a charm, you are fucked" << endl;
}

}

What I am having problems with is after my program leaves the first void:
void askChampSearch(string& UserName, string& searchedChamp){
cout << "Thank you for trying out my program! I really appreciate it! What is your name? (Don't worry, your name isn't stored) ";
    cin >> UserName;
    cout << "Hi " << UserName << ", nice to meet you!" << endl;
    cout << endl;

    cout << "What League of Legends champion would you like to search? ";
    cin >> searchedChamp;
    cout << "The champion that you have searched for was " << searchedChamp << "!";
}

It won't enter into the next one! For example. If the user types the Name Ahri it should display what I have done, but it says I need to define Ahri. How do I define Ahri within the second Void. Here is the code for my second Void:
void displayChampDetail(string searchedChamp) {
if (searchedChamp == Ahri) {
    cout << "Ahri is a nine-tailed fox" << endl;
    cout << "If Ahri hits you with a charm, you are dead" << endl;
}
}

What I am trying to do is, if the user types the name Ahri, it the information that I have provided.
The error code that I am getting is identifier "Ahri" is undefined.

A: searchedChamp == "Ahri"

It is a string. Other wise compiler tries to find a variable with name "Ahri"and it doesn't find it so it asks you to define it.


text:
Q: Represent a Java type as a varargs Is it possible to do something like this using Java features?
class myClass {int i; String s;}

static void myMethod(myClass... args)
{
...
}

main()
{
   myMethod(2,"two",3,"three");
}

A: It is not possible. Perhaps you could create a static helper method which makes creating your objects as easy as possible.
static myClass mc(int i, String s) {
    return new myClass(i, s);
}

myMethod(mc(2, "two"), mc(3, "three"));

A: No, but you can make a constructor of MyClass and invoke:
myMethod(new MyClass(2, "two"), new Myclass(3, "three"));

For the sake of brevity you can make a statically-imported factory method:
public class MyClass {
    public MyClass create(String s, int i) {
        return new MyClass(s, i);
    }
}

and use:
myMethod(create(2, "two"), create(3, "three"));

A: You could do it with a wrapper class:
class MyWrapper {
    private int i;
    private String s;

    public MyWrapper(int _i, String _s) {
        i = _i;
        s = _s;
    }
}

class Test {
    static void myMethod(MyWrapper... args) {
        //do work
    }

    public static void main(String[] args) {
        myMethod(new MyWrapper(2, "two"), new MyWrapper(3, "three"));
    }
}

A: Yes, sortof. You need a constructor of your class...
public class MyClass{
   int i
   String s;

   public MyClass(int i, String s){
      this.i = i;
      this.s = s;
   }
}

public static void myMethod(MyClass... instances){
     .....
}

public static void myMethod(Object... args){

    MyClass[] instances = new MyClass[args.length / 2];
    for (int i=0; i<args.length / 2; i++){
         instances[i] = new MyClass((Integer)args[i * 2], (String)args[(i*2) + 1]);
    }

    myMethod(instances);
}

You would need to add error checking to ensure that args has an even number of elements and there is not a method to enforce that every i * 2 element is an Integer and every i * 2 + 1 is a String. But it is possible.
Given all of the above, I will say... this is very non-standard programming and I would not recommend it. But as you see, it is possible.


text:
Q: I deleted and reinstalled Batman Arkham Knight from epic and when I booted the game, my saves were gone. Is there a way to recover my data? I did save some of my data a while back to another folder but I'd like to get all of my timed records and progress back. I noticed that in the This PC/Documents/WB Games/Batman Arkham Knight/SteamID/SaveData/Backup folder there is a bunch of save data backup files.
Of note is that I own the game on epic and did not own the game on steam, and yet there are still apparently backup saves in a folder labeled SteamID. However, these files have a date at the end of their file extension (i.e. *.sgm_xx_xx_20xx).
When I get rid of the date extension, the game recognizes the file as save data, but says that it's corrupted and shows 0% game progress. Is there any way to make this data work with the epic version of the game? Is there any other way to recover save data after deleting and reinstalling the game? Would I be able to access this data if I bought the steam version of the game?
Update:
I bought the game on steam and unfortunately, it didn't recognize the save data in that folder. I tried editing the file extension to make it a .sgm file (rather than a .sgm_xx_xx_20xx) and it still didn't recognize it.
The steam version didn't recognize it at all, which makes me wonder if there's an online check or something that's preventing me from using my own files from the SaveData folder.
Importantly, I converted the most recent of these save data backups and my own manual backup (which works but is outdated) to .txt files to compare them. It looks like the backup files in the SteamID folder is a valid save file, it is very similar in its contents to the old one, with just some changes to some characters and lines.
Due to this and the filesize, I am convinced that this automatic backup is a valid save file and my chance at getting my data back. However, I can't seem to get it to work with either a steam or epic version of the game, and it still has that pesky file extension (.sgm_xx_xx_20xx).
I think this can actually save my data, but I need help figuring out how. How can I get this file to work with the game? Is there any other way to restore lost data?


text:
Q: OpenCV - background removal and object detection I need to detect where objects (mostly people) are in relation to a wall. I can have a fixed position camera in the ceiling so I thought to get an image of the space with nothing in it. Then use the difference of that and the current camera image to get an image with just the things. Then I can do blob detection I think to get the positions (only need x).
Does this seem sound? I'm not very accomplished in OpenCV so am looking for some advice.

A: That would be one way of going about it, but not very robust as the video feed won't produce consistent precise images so the background will never be nicely subtracted out, and people walking through the scene will occlude light and could also possibly match parts of your background.
This process of removing the background from a video is simply dubbed "background subtraction" and there are built-in OpenCV methods for it.
OpenCV has tutorials on their site showing the basics, for both python and C++.


text:
Q: How to create a generic method that accepts only generic parameters and not raw type parameters? I want to create a generic method that accepts only an arraylist of integers. But the method is also accepting a raw type. How can I restrict it to accept only an arraylist of integers?
package generics;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class GenericBox<T> {
    public static void main(String[] args) {
        ArrayList l1 = new ArrayList();
        l1.add(1);
        l1.add("subbu");
        printListValues(l1);

        ArrayList<Integer> l2 = new ArrayList<>();
        l2.add(1);
        l2.add(2);
        printListValues(l2);
    }
    public static <T extends ArrayList<Integer>> void printListValues(T t){
        System.out.println(t);
    }
}

Thank you,
Subbu.

A:
But the method is also accepting a raw type

Are you saying that you want this call to be forbidden ?
printListValues(new ArrayList());  // raw type

The compiler will issue a warning about using raw types, but it will compile. You might be able to tell your compiler (examine its documentation or configuration GUI for how) to treat this as an error, and so forbid it.
The reason the compiler normally allows this is backwards-compatibility. Generics were added later in life (with Java 5) and are "opt-in". If the code uses generic types, they have to be correct, but you could forgo that altogether. The old "raw" code still continues to work (which is a strong selling point of Java).
Maybe there is a compiler option to turn warnings into errors, so you can prevent yourself from using raw types. But you cannot force others to do that.

A: You simply cannot stop somebody passing in a raw-typed list.
For better or for worse (mostly the latter these days), raw types are a deeply-embedded part of the language. There is no getting away from them.
However, your method signature defines a contract:
public static void printListValues(ArrayList<Integer> t)

says "To work correctly, I need an ArrayList (or null). If that list is not null, I expect all of its elements to be Integer or null; and I expect the list to be able to consume instances of Integer or null without causing problems for the caller".
If you pass in anything else, the behaviour is undefined: caveat emptor. Most of the time, the compiler stops this happening, but if the type checks are disabled (by the use of raw types), you're on your own.
So, don't worry about people passing in a raw-typed list. If they ignore the contract of your method, and ignore the warnings from the compiler, they are getting everything they deserve.

A: And you can use many Types and you can specify what kind of types it should accept
public class GenericBox<T> {
    public static void main(String[] args) {

        GenericProperties genericsPropertiesOnly=new GenericProperties();

        genericsPropertiesOnly.l2.add(1);
        genericsPropertiesOnly.l2.add(1);

        printListValues(genericsPropertiesOnly);
    }
//In here i am specifying to method should accept only Generic  from GenericProperties class

    public static <T extends GenericProperties> void printListValues(T t){
        System.out.println(t.l2);
    }

}

In here you can specify what kind of properties you are going to use
public class GenericProperties {

    private ArrayList<Integer> list;

    private ArrayList<String> listw;

    ArrayList<Integer> l2 = new ArrayList<>();

}


text:
Q: How to configure pom.xml file to use Nexus Repository manager I am using Redhat, java 1.7, maven 3.2.5, jenkins 1.6,git version 2.0.5 and nexus-2.12.0-01
I have created a Local Nexus Repository for my internal development.
Now What I am trying to do is, to build maven project using jenkins with Nexus Repository Manger Oss.
I am able to build my project without Nexus Repository Manger Oss.
Note : I am using parent pom since I have to sub projects.
Below are the steps that I followed.

*

*Installed Nexus Repository Manger Oss. It is up and running
here is screen-shot.

*Installed ojdbc5 jar in nexus repository

*Made necessary changes in setting.xml file of .m2 folder
here the content of setting.xml
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0                                                           http://maven.apache.org/xsd/settings-1.0.0.xsd">

    <mirrors>
        <mirror>
        <!--This sends everything else to /public -->
            <id>nexus</id>
            <mirrorOf>*</mirrorOf>
            <url>http://localhost:8081/nexus/content/groups/public</url>
        </mirror>
    </mirrors>

    <activeProfiles>
        <!--make the profile active all the time -->
        <activeProfile>nexus</activeProfile>
    </activeProfiles>

    <profiles>
        <profile>
            <id>nexus</id>
          <repositories>
          <repository>
          <id>central</id>
          <url>http://maven.apache.org</url>
          <releases><enabled>true</enabled></releases>
          <snapshots><enabled>true</enabled></snapshots>
          </repository>
            </repositories>

            <pluginRepositories>
                <pluginRepository>
                    <id>central</id>
                    <url>http://maven.apache.org</url>
                    <releases><enabled>true</enabled></releases>
                    <snapshots><enabled>true</enabled></snapshots>
                </pluginRepository>
            </pluginRepositories>
        </profile>
    </profiles>

    <servers>
      <server>
       <id>releases</id>
       <username>deployment</username>
       <password>deployment123</password>
      </server>
      <server>
        <id>snapshots</id>
        <username>deployment</username>
        <password>deployment123</password>
      </server>
    </servers>

</settings>

*

*Added the details of nexus repository in my pom.xml
parent pom.xml content
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>parent</groupId>
  <artifactId>A</artifactId>
  <packaging>pom</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>Maven Webapp</name>
  <!--url>http://maven.apache.org</url-->

  <distributionManagement>
    <repository>
      <id>releases</id>
      <url>http://localhost:8081/nexus/content/repositories/thirdparty/</url>
    </repository>
    <snapshotRepository>
      <id>snapshots</id>
      <url>http://localhost:8081/nexus/content/repositories/snapshots/</url>
    </snapshotRepository>
  </distributionManagement>

  <dependencies>
    <dependency>
      <groupId>com.oracle</groupId>
      <artifactId>ojdbc5</artifactId>
      <version>11.2.0.1</version>
    </dependency>
  </dependencies>

  <modules>
    <module>subModule1</module>
    <module>subModule2</module>
  </modules>
</project>

SubModule1's pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.a</groupId>
  <artifactId>a</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Maven Webapp</name>

  <distributionManagement>
    <repository>
      <id>releases</id>
      <!-- CHANGE HERE by your team nexus server -->
      <url>http://localhost:8081/nexus/content/repositories/thirdparty/</url>
    </repository>
    <snapshotRepository>
      <id>snapshots</id>
      <!-- CHANGE HERE by your team nexus server -->
      <url>http://localhost:8081/nexus/content/repositories/snapshots/</url>
    </snapshotRepository>
  </distributionManagement>

  <dependencies>
    // dependecies are defined here
  <dependencies>

In subModule1 and subModule2 I have added the distributionManagement section.
But when I build my project I get the below error.

[ERROR] Failed to execute goal on project submodule1: Could not
  resolve dependencies for project submodule1:war:1.0-SNAPSHOT: Failure
  to find com.oracle:ojdbc5:jar:11.2.0.1 in
  https://repo.maven.apache.org/maven2 was cached in the local
  repository, resolution will not be reattempted until the update
  interval of central has elapsed or updates are forced -> [Help 1]

I understand the error is caused by the com.oracle:ojdbc5:jar:11.2.0.1jar dependency not being resolvable.
But I am surprised why it is not picking it up from my local nexus repository.
Have I missed any configuration, or am I doing it in a wrong way?
How do I use local nexus repository for my projects?

A: In your settings.xml, usually in your ~/.m2/ directory you need to specify your local Nexus.  You only get maven central by default.
 <profile>
        <id>local</id>
        <repositories>
            <repository>
                <id>nexus</id>
                <name>libs-release</name>
                <url>http://url to your local Nexus/artifactory/libs-release</url>
            </repository>
        </repositories>
 </profile>

You can add as many repository elements as you like.
Make sure the correct profile is active, at the bottom of your settings.xml
  <activeProfiles>
    <activeProfile>local</activeProfile>
  </activeProfiles>

Also you will be left with a stub in your ~/.m2/repository/com/oracle ... folder.  I always do a rm -r ~/.m2/repository/com/oracle to force it to download from the remote repo.

A: Your settings.xml does not correctly override the central repository configuration. The correct setup can be found in the documentation.
There are also example projects available that have everything ready to go and the eval guide includes a step by step guide.

A: This is my settings.xml file-
<localRepository>C:/Users/shuarya/.m2/repository</localRepository>
<interactiveMode>true</interactiveMode>
<offline>false</offline>
<pluginGroups>
</pluginGroups>
<proxies>
</proxies>
<servers>
</servers>
<mirrors>
    <mirror>
  <!--This sends everything else to /public -->
  <id>nexus</id>
  <mirrorOf>*</mirrorOf>
  <url>http://localhost:8081/nexus/content/repositories/com.shubham.TestNexus2</url>
 </mirror>
</mirrors>
<profiles>
<profile>
   <id>nexus</id>
  <!--Enable snapshots for the built in central repo to direct -->
  <!--all requests to nexus via the mirror -->
  <repositories>
    <repository>
      <id>central</id>
      <url>http://central</url>
      <releases><enabled>true</enabled></releases>
      <snapshots><enabled>true</enabled></snapshots>
    </repository>
  </repositories>
 <pluginRepositories>
    <pluginRepository>
      <id>central</id>
      <url>http://central</url>
      <releases><enabled>true</enabled></releases>
      <snapshots><enabled>true</enabled></snapshots>
    </pluginRepository>
  </pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<!--make the profile active all the time -->
<activeProfile>nexus</activeProfile>
</activeProfiles>
</settings>

So, in my settings.xml file, I have specified the path of my local repository and also, at the bottom I have chosen my active profile as nexus. Inside the nexus node I have specified my locally hosted nexus repository's path.
And, I have not specified any URL in my pom.xml
    <modelVersion>4.0.0</modelVersion>
<groupId>com.shubham.example</groupId>
<artifactId>TestingNexusrepo</artifactId>
<version>0.0.1-SNAPSHOT</version>

<dependencies>

    <dependency>
        <groupId>com.shubham.TestNexus</groupId>
        <artifactId>TestNexus</artifactId>
        <version>1</version>
    </dependency>

    <dependency>
        <groupId>com.shubham.TestNexus2</groupId>
        <artifactId>TestNexus2</artifactId>
        <version>1</version>
    </dependency>

</dependencies>
</project>

When the project builds, it downloads the jar from the repository and keeps it in the local repository path. This way, in future when you specify this(same) dependency, it fetches the dependency from the local repository rather than downloading it again from the Nexus repository (caching).
This is working for me, please let me know if my understanding is wrong.
Also, Is there any way in which I could specify more than one URL(s) for the nexus repository.
Please help.


text:
Q: Get IP address and port in Flask decorator function How to get in a decorator function in Flask the IP address and port of the client that sent the request ?
from flask import Flask, request, jsonify
from functools import wraps
app = Flask(__name__)

def check_auth(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print(request)
        ###  Here I need the IP address and port of the client
        return f(*args, **kwargs)
    return decorated_function

@app.route('/test', methods=['POST'])
@check_auth
def hello():
    json = request.json
    json['nm'] = 'new name2'
    jsonStr = jsonify(json)
    return jsonStr

A: You can use Flask's request.environ() function to get the Remote port and IP Address for the client:
from flask import request
from functools import wraps

def check_auth(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        print(request)
        ###  Here I need the IP address and port of the client
        print("The client IP is: {}".format(request.environ['REMOTE_ADDR']))
        print("The client port is: {}".format(request.environ['REMOTE_PORT']))
        return f(*args, **kwargs)
    return decorated_function

The decorator prints something like:
The client IP is: 127.0.0.1
The client port is: 12345


text:
Q: Flutter url_launcher Unhandled Exception: Could not launch youtube url (Caused by canLaunch) I'm trying to use the url_launcher plugin to open youtube videos by link but the canLaunch function keeps throwing an error. I'm able to bypass this error only by completely removing the canLaunch function but can't figure out what is wrong.
Code not working:
_goToVideo(YoutubeVideoData video) async {
  if (await canLaunch(video.url)) {
    await launch(video.url);
  } else {
    throw 'Could not launch ${video.url}';
  }
}

Code working:
_goToVideo(YoutubeVideoData video) async {
  await launch(video.url);
}

I'm not quite sure why I can't use the canLaunch method as written in the README Example
Error:
E/flutter (12574): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: Could not launch https://www.youtube.com/watch?v=-3g5WlqJtIo
E/flutter (12574): #0      _goToVideo (package:esfandapp/widgets/newsList/videoCard.dart:71:5)
E/flutter (12574): <asynchronous suspension>
E/flutter (12574): #1      VideoCard.build.<anonymous closure> (package:esfandapp/widgets/newsList/videoCard.dart:13:20)
E/flutter (12574): #2      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:992:19)
E/flutter (12574): #3      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:1098:38)
E/flutter (12574): #4      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
E/flutter (12574): #5      TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
E/flutter (12574): #6      BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:284:5)
E/flutter (12574): #7      BaseTapGestureRecognizer.acceptGesture (package:flutter/src/gestures/tap.dart:256:7)
E/flutter (12574): #8      GestureArenaManager.sweep (package:flutter/src/gestures/arena.dart:158:27)
E/flutter (12574): #9      GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:224:20)
E/flutter (12574): #10     GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:200:22)
E/flutter (12574): #11     GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:158:7)
E/flutter (12574): #12     GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:104:7)
E/flutter (12574): #13     GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:88:7)
E/flutter (12574): #14     _rootRunUnary (dart:async/zone.dart:1206:13)
E/flutter (12574): #15     _CustomZone.runUnary (dart:async/zone.dart:1100:19)
E/flutter (12574): #16     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1005:7)
E/flutter (12574): #17     _invoke1 (dart:ui/hooks.dart:267:10)
E/flutter (12574): #18     _dispatchPointerDataPacket (dart:ui/hooks.dart:176:5)

Widget using the function:
class VideoCard extends StatelessWidget {
  final YoutubeVideoData video;
  VideoCard({this.video});

  @override
  Widget build(BuildContext context) {
    return InkWell(
      onTap: () => _goToVideo(video),
      child: Container(
        child: Card(
          child: Container(
            child: Column(
              children: [
                Align(
                  child: Padding(
                    child: Text(
                      video.title,
                      style: TextStyle(
                        fontFamily: 'Roboto Condensed',
                        fontSize: 16,
                      ),
                    ),
                    padding: EdgeInsets.fromLTRB(15, 0, 15, 10),
                  ),
                  alignment: Alignment.centerLeft,
                ),
                Container(
                    child: Image.network(video.thumbnails[1], fit: BoxFit.cover,),
                  width: MediaQuery.of(context).size.width,
                ),
                Align(
                  child: Container(
                    child: Text(
                      video.date.toString() + "",
                      style: TextStyle(
                        fontFamily: 'Roboto Condensed',
                        fontSize: 14,
                        fontWeight: FontWeight.w300,
                      ),
                    ),
                    padding: EdgeInsets.fromLTRB(15, 5, 15, 0),
                  ),
                  alignment: Alignment.centerLeft,
                ),
              ],
            ),
            width: MediaQuery.of(context).size.width - 32,
            padding: EdgeInsets.symmetric(
              horizontal: 0,
              vertical: 10,
            ),
            alignment: Alignment.center,
          ),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(25))),
        ),
      ),
    );
  }
}

A: Even after trying accepted answer, If its not working for you then Please try followed code.
PRE STEPS: Do as accepted answer suggested.
Add following tags in AndroidManifest.xml before <application/>
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>

<queries>
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <data android:scheme="https" />
    </intent>
    <intent>
        <action android:name="android.intent.action.DIAL" />
        <data android:scheme="tel" />
    </intent>
    <intent>
        <action android:name="android.intent.action.SEND" />
        <data android:mimeType="*/*" />
    </intent>
</queries>

NOW WHAT I HAVE DONE
Create one method:
Future<void> _makeSocialMediaRequest(String url) async {
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }

and Called it by following way:
  //FOR EMAIL
  final Uri _emailLaunchUri = Uri(
      scheme: 'mailto',
      path: 'pratik13butani@gmail.com',
      queryParameters: {'subject': 'Pratik Butani'});
  _makeSocialMediaRequest(_emailLaunchUri.toString());

  //FOR PHONE NUMBER:
  final Uri _phoneLaunchUri =
      Uri(scheme: 'tel', path: postOffice.mobileNo);
  _makeSocialMediaRequest(_phoneLaunchUri.toString());

  //FOR ANY URL.. YOU CAN PASS DIRECT URL..
  _makeSocialMediaRequest("http://pratikbutani.com");

Its working for me. Hopefully it will work for you too. Thank you.

A: Starting from API30 (Android 11), your Android app has to list all apps it interacts with.
You can add:
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>

in your android manifest to bypass it or specifically list them.
For more info:
https://developer.android.com/about/versions/11/privacy/package-visibility

A: Personally, I don't like the uncertainty that seems to come with using the QUERY_ALL_PACKAGES permission (because Google could stop letting people use it in the future). For that reason, I did some investigation and found that adding the following to my AndroidManifest.xml allows my app to open the browser, phone app and email app on API 30:
<manifest>

    <!-- Nest within the manifest element, not the application element-->
    <queries>
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="https" />
        </intent>
        <intent>
            <action android:name="android.intent.action.DIAL" />
            <data android:scheme="tel" />
        </intent>
        <intent>
            <action android:name="android.intent.action.SEND" />
            <data android:mimeType="*/*" />
        </intent>
    </queries>

    <application>
        ....
    </application>
</manifest>

To get the same functionality working on iOS, it may be necessary to add the following to your info.plist file:
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>https</string>
    <string>http</string>
    <string>tel</string>
    <string>mailto</string>
</array>

Just wanted to share in case it helps someone else out.

A: bro only put '!' before "if (!await canLaunch(url))"
Use this -->
 if (!await canLaunch(url)){
  await launch(
    url,
    forceSafariVC: false,
    forceWebView: false,
    headers: <String, String>{'my_header_key': 'my_header_value'},
  );
} else {

  throw 'Could not launch $url';
}

A: For Android Use the below code in Android/main/res/AndroidManifest.xml like the showed in the image

and here is the code
<intent>
    <action android:name="android.intent.action.VIEW" />
    <data android:scheme="https" />
</intent>
<intent>
    <action android:name="android.intent.action.DIAL" />
    <data android:scheme="tel" />
</intent>
<intent>
    <action android:name="android.intent.action.SEND" />
    <data android:mimeType="*/*" />
</intent>

For IPhone ios/Runner/Info.plist like the showed in the image

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>https</string>
    <string>http</string>
    <string>tel</string>
    <string>mailto</string>

A: Make sure to add in the android manifest the below line
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>

Don't forget about the Info.plist as well
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>https</string>
    <string>http</string>
    <string>tel</string>
    <string>mailto</string>
</array>

A: I spent nearly 2 hours to find what is wrong and after I closed the application from the recent tab and re-run the app it worked perfectly fine.
Things you might missed,

*

*adding Url_launcher dependency in pubspec.yaml

*Adding queries in Android manifest file after tag

<queries>
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" />
    </intent>
</queries>

*Adding keys in the info.plist file under ios directory

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>https</string>
    <string>http</string>
</array>

*Just try to uninstall app and run the code

A:  if (await canLaunchUrl(Uri.parse(url))) {
      await launchUrl(Uri.parse(url),
      mode: LaunchMode.externalApplication, );
    }

A: i faced same error using win and linux for android developments
and solve it with these steps
the idea is to add the  to AndroidManifest.xml in app/src/main/AndroidManifest.xml
to do so and to make it work without error you must update the gardle version so here is the steps
1-updated my gradle-wrapper.properties to gradle-6.7.1-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7.1-all.zip

2- updated my classpath  in  android/build.gradle to com.android.tools.build:gradle:4.2.1
buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

3- add the  above  to my AndroidManifest.xml in app/src/main/AndroidManifest.xml
   <queries>
        <!-- If your app opens https URLs -->
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="https" />
        </intent>
        <!-- If your app makes calls -->
        <intent>
            <action android:name="android.intent.action.DIAL" />
            <data android:scheme="tel" />
        </intent>
        <!-- If your app emails -->
        <intent>
            <action android:name="android.intent.action.SEND" />
            <data android:mimeType="*/*" />
        </intent>
    </queries>

and now everything work fine

A: If none of the above works, try adding this in the AndroidManifest.xml (main one if you have that). Add this code snipped just above the <application> tag.
<queries>
    <intent>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="https" />
    </intent>
</queries>

A: For Android Just add in your androidmanifest.xml file
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES"/>

For iOS add these in your info.plist file
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>https</string>
    <string>http</string>
    <string>tel</string>
    <string>mailto</string>
</array>

A: QUERY_ALL_PACKAGES (not recommended)
Because Google could stop letting people use it in the future as mentioned in the official document
if you use launch any url from your app just use
<manifest package="com.example.game">
    <queries>
        <package android:name="com.android.chrome" />

    </queries>
    ...
</manifest>

likewise you can add <queries> depends on your need.

ex.

<queries>
        <!-- If your app opens https URLs -->
        <intent>
            <action android:name="android.intent.action.VIEW" />
            <data android:scheme="https" />
        </intent>
        <!-- If your app makes calls -->
        <intent>
            <action android:name="android.intent.action.DIAL" />
            <data android:scheme="tel" />
        </intent>
        <!-- If your app emails -->
        <intent>
            <action android:name="android.intent.action.SEND" />
            <data android:mimeType="*/*" />
        </intent>
    </queries>

A: This worked for me
if (!url.contains('http')) url = 'https://$url';

Complete Method:
launchURL(String url) async {
  if (!url.contains('http')) url = 'https://$url';
  if (await canLaunch(url)) {
    await launch(url);
  } else {
    throw 'Could not launch $url';
  }
}


text:
Q: Dual basis existance To find the basis of a dual space, one needs to solve equations to satisfy Kronecker's delta conditions. One we solve them we have everything needed to prove their uniqueness, linear independence, etc..
So my question is why those n² linear equations are solvable in the first place?

A: Given a basis for a vector space, we can define linear functions on the vector space simply by picking any image for each basis element.
That's all these equations are: specifying the values of linear functionals  on the elements of the basis.
We could instead give a pointwise definition of these functionals
$$ \phi_i\left( \sum_j c_{ij} v_j \right) = c_{ii} $$
but that's more complicated and has a lot of unnecessary redundancy.

In coordinates, it's just as trivial; the coordinate form of the basis vector $v_j$ is just the standard $n \times 1$ basis column vector $\hat{e}_j$. The coordinate form of covectors in the dual space are $1 \times n$ row vectors, with $\phi_i$ corresponding to the standard basis row vector $\hat{e}_i^T$.
The equations are just computing the products $\hat{e}_i^T \hat{e}_j$, and give a coordinate-free way to express the relationship between the two bases.


text:
Q: My "Hello world" Azure Function is performing very slowly Running the simple hello world code below takes an average of 8 seconds to execute (200 samples, Minimum 64ms, max 14 seconds using jmeter).
I do not see app stops in the logs so why so long and why such a variance?
Note I've tried from multiple network connections, internal and external so doesn't appear network related.
public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string name = req.Query["name"];

            string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic data = JsonConvert.DeserializeObject(requestBody);
            name = name ?? data?.name;

            string responseMessage = string.IsNullOrEmpty(name)
                ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
                : $"Hello Universe, {name}. This HTTP triggered function executed successfully.";

            return new OkObjectResult(responseMessage);
        }
    }

Log file doesn't show anything unusual:
2020-11-19T13:44:40.502 [Information] Executing 'Function1' (Reason='This function was programmatically called via the host APIs.', Id=47ae5039-ac8a-4146-8f06-76b74bafae42)
2020-11-19T13:44:40.540 [Information] Executing 'Function1' (Reason='This function was programmatically called via the host APIs.', Id=5e51999c-c255-44c8-b155-0ea5248d0621)
2020-11-19T13:44:40.541 [Information] Executing 'Function1' (Reason='This function was programmatically called via the host APIs.', Id=bcb087b3-2dae-4514-9821-34971d1e816e)
2020-11-19T13:44:40.541 [Information] Executing 'Function1' (Reason='This function was programmatically called via the host APIs.', Id=90ce4f95-8f34-4359-8bb6-d11b56198edd)
2020-11-19T13:44:40.547 [Information] C# HTTP trigger function processed a request.
2020-11-19T13:44:40.569 [Information] C# HTTP trigger function processed a request.
2020-11-19T13:44:40.570 [Information] Executing 'Function1' (Reason='This function was programmatically called via the host APIs.', Id=edd086c6-b5ad-43f1-855c-5dd729812e3a)
2020-11-19T13:44:40.570 [Information] C# HTTP trigger function processed a request.
2020-11-19T13:44:40.575 [Information] C# HTTP trigger function processed a request.
2020-11-19T13:44:40.622 [Information] Executed 'Function1' (Succeeded, Id=5e51999c-c255-44c8-b155-0ea5248d0621, Duration=76ms)
2020-11-19T13:44:40.699 [Information] C# HTTP trigger function processed a request.
2020-11-19T13:44:40.700 [Information] Executed 'Function1' (Succeeded, Id=edd086c6-b5ad-43f1-855c-5dd729812e3a, Duration=129ms)
2020-11-19T13:44:40.701 [Information] Executed 'Function1' (Succeeded, Id=bcb087b3-2dae-4514-9821-34971d1e816e, Duration=160ms)
2020-11-19T13:44:40.702 [Information] Executed 'Function1' (Succeeded, Id=90ce4f95-8f34-4359-8bb6-d11b56198edd, Duration=160ms)
2020-11-19T13:44:40.712 [Information] Executed 'Function1' (Succeeded, Id=47ae5039-ac8a-4146-8f06-76b74bafae42, Duration=230ms)

A: Turned out the VS2019 wizard additionally publishes a blob storage trigger and was failing repeatedly very often and causing a drain on server resources.


text:
Q: How do all those Javascript OpenID libraries work? There are several OpenID libraries implemented in Javascript (like openid-realselector, openid-selector, jquery.opendid). How do all these work? Do they just provide and call the OpenID provider and then the provider provides some data (how?) and redirects back to my site (to where exactly?)? And now is it my part on the server side to fetch that data somehow and use it to log in my user? I looked at the code of openid-selector, but don't see where to provide a callback url to my site. So I am not sure anymore if the above scenario is really the way how this all works.

A: The libraries you have mentioned are OpenID selectors, that is, glorified forms allowing for easy selection of a provider. They have nothing to do with the protocol, which must be implemented server-side.
As for "how do they work", they simply submit a form with a certain field (openid_identifier). Depending on the button you click, that field has different values, and if you don't click on any, you simply have to input it yourself. Then, a server-side code gets the value, passes it to a library that does handles openid.
You can find a list of OpenID (server-side) libraries on http://openid.net/developers/libraries/.


text:
Q: Howto: mysqldump cron on godaddy I have a MySql database that I want to backup to a file daily. (Which I will later download for off-server backup).
I have set up the following command in my crontab (ran daily):
mysqldump -–opt -Q -h [myhost] -u myusername -–password=***** ebooklibrary > /fullpath.../_db_backups/openelibrary.sql

The database name is ebooklibrary.
I am constantly getting this error:
mysqldump: Got error: 1045: Access denied for user 'myusername'@'97.74.144.139' (using password: NO) when trying to connect

How can I fix this, or do it properly, so that mysqldump will run daily?
Thanks.

Using the shell, the following command worked:
 mysql -h myhost -u myusername -p"*****" ebooklibrary

A: I believe the matter is with how you specify the password. Try
mysqldump –opt -Q -h [myhost] -u myusername –p"*****" ebooklibrary > /fullpath.../_db_backups/openelibrary.sql

A: When specifying a password on the command line, you need to use
--password="xxx"

rather than
-password="xxx"

Note the double dash on the first command.
EDIT: Do you know if the DB server is the same server as the web server? If so, have you tried omitting the host? With that thought, have you also tried --host=127.0.0.1 (Just tried that on my machine - it seems very anal about the correct host name)

A: There are 2 probable reasons for this error.
1) Your password has special characters like !%# etc., if this is the case you can escape the character by placing a back slash '\' before it.
2) This user truely does not have access permission from the IP address mentioned in the error. The solution is to either provide rights to that user from the specified IP or do not attempt to use that host for mysql access.
You can also use the following command if you have access to the server CLI (if you specify no host, mysql will attempt to connect to localhost):
mysqldump -uUSER -pPASS ebooklibrary > /fullpath.../_db_backups/openelibrary.sql

or you can use the following syntax if you are executing the command remotely.
mysqldump -h IP -uUSER -pPASS ebooklibrary > /fullpath.../_db_backups/openelibrary.sql

You should ascertain that you have the necessary rights to perform the dump as specified on the mysqldump page.


text:
Q: Karma not running any unit test cases I am trying to set up Karma for a small demo project. The problem is that Karma is not executing any test cases.
My project has only two .js files: app/js/app.js and test/spec/app.spec.js
My karma config file is as follows:
module.exports = function(config) {
   config.set({
     basePath: '',
     frameworks: ['jasmine'],
     plugins: ['karma-jasmine','karma-phantomjs-launcher'],
     files: [
        'app/js/app.js',
        'test/spec/app.spec.js',
     ],
     exclude: [
     ],
     preprocessors: {},
     reporters: ['dots'],
     port: 9876,
     colors: true,
     logLevel: config.LOG_INFO,
     autoWatch: true,
     browsers: ['PhantomJS'],
     singleRun: true
     });
  };

The temporary contents of my app.spec.js file are:
describe('app js', function(){
   it('test');
});

I am using Gulp in my project and I have written the following gulp task for testing:
gulp.task('test', function() {
   gulp.src('app/js/**/*.js')
   .pipe(karma({
      configFile: 'karma.conf.js',
      action: 'watch'
   }));
});

This is what I am getting in the terminal on running gulp test:
Starting Karma server...
WARN `start` method is deprecated since 0.13. It will be removed in 0.14.
Please use
server = new Server(config, [done])
server.start()
instead.
11 01 2018 22:26:29.672:WARN [karma]: No captured browser, open http://localhost:9876/
11 01 2018 22:26:29.686:INFO [karma]: Karma v2.0.0 server started at http://0.0.0.0:9876/
11 01 2018 22:26:29.687:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
11 01 2018 22:26:29.693:INFO [launcher]: Starting browser PhantomJS
11 01 2018 22:26:30.239:INFO [PhantomJS 2.1.1 (Mac OS X 0.0.0)]: Connected
on socket J2AB2rwIs49mJwRQAAAA with id 34572564
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 0 of 0 ERROR (0 secs / 0 secs)

Can anyone please let me know that what am I doing wrong here?


text:
Q: I have categories and product table. i want to show the categories which has at least 1 product in Laravel I have categories and product table. i want to show the categories which has at least 1 product

A: First you have to make one to many relationship it`s described there: https://laravel.com/docs/8.x/eloquent-relationships#one-to-many
And then you can call and check if it has products

A: Use has.
$categories = Category::has('products')->get();

This will return all categories that have at least one product.


text:
Q: android best layout to display image button that will fills the screen what's the best layout to use to display a series of image button, side by side (as displayed in attached image), and that will fills the screen horizontally when the orientation changes to horizontal (as attached)?
horizontal orientation http://img254.imageshack.us/img254/657/layoutxs.png
vertical orientation http://img208.imageshack.us/img208/2428/layouthy.png

A: It looks like you want to use something like FlowLayout, which doesn't exist in Android. You can make your own, however. More information

*

*How can I do something like a FlowLayout in Android?

*http://nishantvnair.wordpress.com/2010/09/28/flowlayout-in-android/
I have an activity with a layout similar to yours, but I use a different method. What I do is define a different xml layout for landscape and portrait. So I have layout-port/mylayout.xml and layout-land/mylayout.xml and the system determines which one the activity should use.

A: <GridView android:layout_width="fill_parent"
     android:layout_height="wrap_content"
         android:numColumns="auto_fit" >
</GridView>

A: just create two separate layout files and call setContentView() in your onOrientationChanged().


text:
Q: Nasty SQL query: is there a way I can find first and last rows in a grouped set without a cursor? I have data that looks like this:

What I need to do is, for records having the same ClientId, I need to group consecutive rows (using CpId) where PlaceId is not null, and find the first and last row in each group so that I can retrieve the DateAdmitted value from the first row and the DateDischarged value from the last row.  So, the above data needs to be organized like this and then filtered for the values I need:

Using the above example, I would want the following based on ClientId:
ClientId    FirstCpIdInSet    DateAdmitted    LastCpIdInSet    DateDischarged
-----------------------------------------------------------------------------
1967        NULL              NULL            NULL             NULL
1983        45                1986-12-29      45               1987-10-09
1983        47                1990-10-01      49               2009-04-12
1983        52                2009-08-31      52               2009-11-30
1988        62                1997-12-15      65               2000-01-07

ClientId 1967 could be excluded from the result set, since it never has a row where PlaceId is not null.  A couple of other things to note:

*

*This is taken from a temp table that is created with CpId as the IDENTITY, and the table is populated with a strict ORDER BY, so CpId is sequential in the order needed.

*For those rows that have PlaceId and are consecutive for a single ClientId, the DateAdmitted should equal the DateDischarged in the previous row.

I'd really like to be able to do this without a cursor, if possible, but after puzzling on it for two days I just can't figure it out.  This is on SQL Server 2008 R2.

A: Nasty query indeed.  Like most SQL problems it comes down tackling different aspects of the problem in the correct order.  My solution doesn't use cursors.  It does use outer apply and partition by.
Realization:
row_number() over (partition by xx order by yy) by itself won't work, because, yy is typically spanning multiple xx partitions.
Example Data:
id  state
1   a
2   a
3   b
4   c

desired ranges:
1 <= x < 3
3 <= x < 4
4 <= x

Step 1 - Use an Outer Apply to find the next state transition for every row.  This allows you to check each row's next value based on any criteria you want.  This step likely generates more information than you want.  Several rows could transition to the same value. In this example id 1 and 2 transition at id 3.
pseudo code:
select t1.id, t1.state, t3.id, t3.state
from table1 t1
outer apply
(
  select
    --only grab one row
    top 1 t2.id, t2.state
  from table1 t2
  where
    --grab a value that's generated after the current value.
    t1.id < t2.id
    -- add whatever join logic you need for your case.
    and t1.memberid=t2.memberid
    -- make sure you get the correct order, typically an identity or time
    order by t2.id asc
) T3

This query generates something like this:
id  state id    state
1   a     3     b
2   a     3     b
3   b     4     c
4   c     null  null

We don't want the row with id = 2.
Step 2 - Partitioning by the transition column allows you to get a row number value that will always be 1 when a state transition occurs.  Just filter by 1 and you have your state transitions.
initial results:
row_number  id  state   id  state
1           1   a       3   b
2           2   a       3   b
1           3   b       4   c
1           4   c      null null

filtered results:
row_number  id  state   id  state
1           1   a       3   b
1           3   b       4   c
1           4   c      null null

A: You don't say what you are basing first and last on.  Let me assume it is CPID.  You can do this with ranking functions:
select ClientID, PlaceId,
       max(CpID) as max(CPId),
       min(case when seqnumasc = 1 then DateAdmitted end) as DateAdmitted,
       max(case when seqnumdesc = 1 then DateDischarged end) as DateDischarged
from (select t.*,
             row_number() over (partition by clientID, placeID order by cpid) as seqnumasc
             row_number() over (partition by clientID, placeID order by cpid desc) as seqnumdesc
      from t
     ) t
where placeID is not null
group by ClientID, placeID

This puts in sequence nubmers to determine the first and last rows in each group.  However, why can't you just use min and max on date addmited and discharged?
Based on enhanced information . . .
Now the question appears to be to define the "sets" of records according to the following conditions:

*

*Consecutive CPIDs

*Same client, same company

*Place not null

If so, the following will give you a "set id".  This uses a trick for bringing together consecutive values, based on subtracting a sequential number from the CPID.  This difference is a constant for consecutive values, providing a set id.
select clientid, setid,
       min(DateAdmitted) as DateAdmitted,
       max(DateDischarged) as DateDischarged,
       min(cpid) as minCPID,
       max(cpid) as maxCPID
from (select clientid, setid, cpid,
             row_number() over (partition by clientid, setid order by cpid) as seqnum,
             count(*) over (partition by clientid, setid) as setsize
      from (select t.*,
                   (cpid - row_number() over (partition by clientid order by cpid)
                   ) as setid
            from t
            where PlaceID is not NULL
           ) t
    ) t
group by clientid, setid


text:
Q: Mobile safari clear tab or detect history I'm trying to solve this problem:
iOS 7 - is there a way to disable the swipe back and forward functionality in Safari?
I have custom navigation on swipe and if there is history in the tab mobile safari automatically goes back in history. Is there any way to clear the tab history or detect that tab history exists so that it can open the site in a new tab?

A: I don't believe you can clear the tab history, but you could check the history length with window.history.length and open a new tab.


text:
Q: What do the modifyAllRecords and viewAllRecords Profile permissions mean? I'm currently modifying the profiles in my salesforce org through their xml files.
When I reach:
 <objectPermissions>
    <allowCreate>false</allowCreate>
    <allowDelete>false</allowDelete>
    <allowEdit>false</allowEdit>
    <allowRead>true</allowRead>
    <modifyAllRecords>false</modifyAllRecords>
    <object>Modem__c</object>
    <viewAllRecords>false</viewAllRecords>
 </objectPermissions>

Does anyone know what the <modifyAllRecords> and <viewAllRecords> tag represent? When I change those from false to true and I try to save the permission's xml file I receive an error:

"Save error: Permission Manage All Modem__c depends on permission(s):
  Read All Account"

Any one have any ideas?

A: "View and modify all records" means exactly what it says on the tin. Making this true for a profile will mean that users in that profile will have the ability to both view, and subsequently edit ALL the Modem__c records in your system.
The reason you are getting the error when trying to set this is because the Modem__c object is related to the Account object and thus you cannot grant an "All" permission on this child object without first considering the access permissions to the related records.
If you'd like to explain your object structure and/or intention for setting these permissions values to true, I'm sure the community could help out with some suggestions on how to progress?


text:
Q: Filter columns based on starting string, read number from filtered cells and perform arithmetic operation to generate summary of two rows in Excel I am having a Project and resource allocation report. I need help in generating the formula to display summary on the right section of the report.
Here're the specifications of my report:

*

*Column A from Row 2 to Row 15 represents the Resource (persons) allocated for each project

*Column B, Column C.... represents the percentage of resource allocated in each project per month

*Each resource of column A is merged into 2 cells because each resource can either work in 1 or 2 project per month

*Resource working on single project in a month will have both the cells merged . Resource working on 2 projects will have 2 rows representing the project

*Against each project there is number representing the percentage of that resource allocated to the project

Here's the screenshot of my report:

Here, in the summary, I am representing the total number of weeks each person will be spending on each project. To keep the calculation simplified, I am assuming each month is equivalent to exactly 4 weeks. So,

*

*If a Person A is working 100% in Project B in February. Then number to be considered for summation in summary should be 4 for Project B

*Similarly if Person A is working 50-50% on 2 projects in January. Then number to be considered for summation should be 2-2 weeks for each project

In general, the number to be considered in summary could be mathematically represented as:
4 *[Percentage from column] / 100

Here's what I am trying to achieve:

*

*Read string from cells (F1 - J1)

*Do a lookup in the person column on two rows (B2, C2... ) and (B3, C3...) to get the cells starting with project string

*Filter the numbers from the above cells (from step 2)
Do summation of the numbers and divide by 100 and multiply by 4 (to get number of weeks)

Here's what I created taking answer for similar question as reference from here:
=IFERROR((IFERROR(SUM(--((TRIM(RIGHT(SUBSTITUTE(FILTER($B2:$C2,ISNUMBER(SEARCH(J$1,$B2:$C2)))," ",REPT(" ",99)),99))))), 0) + IFERROR(SUM(--((TRIM(RIGHT(SUBSTITUTE(FILTER($B3:$C3,ISNUMBER(SEARCH(J$1,$B3:$C3)))," ",REPT(" ",99)),99))))), 0))*4, "")

which gives me 6 for Project B. Is there a way to simplify this? I think I am doing a lot of redundant operations here. Also, it returns 0 if project not found. I prefer empty string in it's place
Feel free to suggest if there's a better way to perform this calculation.
Note:

*

*For column with two cells merged, calculation should be considered just once for that person.

*Calculation of my summary is based on data from two rows

*Here I am using Person names ("Person A", "Person B", etc) and Project names ("Project A", "Project B", etc) strings just as a placeholder text. In real report these are going to real values with random alphabets.

PS: It is similar to my previous question where I was generating summary on single column, where two cells within the column could be merged: Excel - Filter rows based on starting string, read number from filtered rows and perform arithmetic operation to generate column summary . However, here I am performing calculation on two rows to get the summary. And merged row cells needs to be considered only once for calculation.

A: The solution is more complicated because the range to process is multi-dimensional. (In your previous question it was only a single dimension).
One way to process is to turn it into a single dimensional array which can be done using TEXTJOIN and FILTERXML.  There is a limitation in that the string resulting from the TEXTJOIN function can not exceed 32,767 characters.  If that will be a problem, then a VBA or Power Query solution might be better.
Also, FILTERXML is not available on Mac versions or on Excel Online.
If those limitations do not apply, then
F2: =IFERROR(4*SUM(FILTERXML("<t><s>" & SUBSTITUTE(FILTERXML("<t><s>" &TEXTJOIN("</s><s>",TRUE,$B2:$C3) & "</s></t>","//s[starts-with(.,'" & F$1 & "')]")," ","</s><s>") & "</s></t>","//s[last()]")),"")

*

*Fill right and down

*We first create an XML (using TEXTJOIN) to create a separate node for each cell

*

*our xPath argument returns only those nodes that start-with the Project name in row 1.

*We then use SUBSTITUTE to create another XML based on space-separated nodes with an xPath that returns the last node.

*Do the mathematical operations.

EDIT:
If you do NOT have the FILTERXML function, try this formula (O365 Mac or Windows and Excel Online) which uses a different method to convert the 2D array into a 1D array for processing:
=IFERROR(SUM(4*TRIM(RIGHT(
   SUBSTITUTE(LET(
        seq,IF(SEQUENCE(99)=1,1,(SEQUENCE(99)-1)*99),
        x,TRIM(MID(TEXTJOIN(REPT(" ",99),TRUE,$B2:$C3),seq,99)),
        y, FILTER(x,LEFT(x,LEN(F$1))=F$1),y),
   " ",REPT(" ",99)),99))),"")

This formula still has the 32,767 character limit. Whether you run into that will depend mostly on how many spaces there are in the project name.  Formula to compute is roughly:

*

*a = average number of characters in the cell

*b = number of spaces in the cell

*c = number of cells
 (a+b*99) * c

If you had, for example, 15 characters, 5 spaces, and 24 cells, that would work out to about 12,000 characters.

A: Maybe, try this shorter formula proposal.
1] In F2, formula copied across and down :
=SUMPRODUCT(4*TEXT(SUBSTITUTE($B2:$C3,F$1,""),"0%;;;\0"))

2] Your previous question can also be solved by this same formula, I put it in A19:C23.
In B19, formula copied across and down :
=SUMPRODUCT(0+TEXT(SUBSTITUTE(B$2:B$15,$A19,""),"0%;;;\0"))

And,
Edit
To remove 0
1] Using cell format :
All formula cells format in  >> "Accounting" >> "Symbol", choose "None" >> "Decimal place" : click "1"
2] Using IFERROR(1(/1.......),"") adding to F2 formula, and become >>
=IFERROR(1/(1/SUMPRODUCT(4*TEXT(SUBSTITUTE($B2:$C3,F$1,""),"0%;;;\0"))),"")


text:
Q: Java 8 How to get a some elements out of a list with parameters from a nother list I am not sure if someone ask it before. How can I get all User form the following list where the rightId is equal 30 for example.
User Object:
public class User {
    private int id;
    private String email;

    private List<Rights> RightsSet;
}

User Rights:
public class Rights{
    private int id;
    private String Name;

    private List<User> userSet;
}

The relation is a ManyToMany and I use JPA. But I won't use a namedQuery or other SQL statements.
I tried this:
List<User> userList = em2.getAllEntity(User.class); //I get all User
1.
List<User>o = userList.stream()
                .filter(x -> x.getRightsSet().stream()
                    .anyMatch(y -> y.getId() == 5201)
                    )
                .collect(Collectors.toList());
2.
List<User> rights = userList.stream()
               .filter(x -> x.getRightsSet().stream()
                        .filter(y -> y.getId() == 31).findAny().orElse(null) != null)
                .collect(Collectors.toList());

Can someone help me?


text:
Q: Deduping evnts using hiveContext in spark with scala I am trying to dedupe event records, using the hiveContext in spark with Scala.
df to rdd is compilation error saying "object Tuple23 is not a member of package scala". There is known issue, that Scala Tuple can't have 23 or more
Is there any other way to dedupe
val events = hiveContext.table("default.my_table")
val valid_events = events.select(
                              events("key1"),events("key2"),events("col3"),events("col4"),events("col5"),
                              events("col6"),events("col7"),events("col8"),events("col9"),events("col10"),
                              events("col11"),events("col12"),events("col13"),events("col14"),events("col15"),
                              events("col16"),events("col17"),events("col18"),events("col19"),events("col20"),
                              events("col21"),events("col22"),events("col23"),events("col24"),events("col25"),
                              events("col26"),events("col27"),events("col28"),events("col29"),events("epoch")
                              )
//events are deduped based on latest epoch time
val valid_events_rdd = valid_events.rdd.map(t => {
                                                  ((t(0),t(1)),(t(2),t(3),t(4),t(5),t(6),t(7),t(8),t(9),t(10),t(11),t(12),t(13),t(14),t(15),t(16),t(17),t(18),t(19),t(20),t(21),t(22),t(23),t(24),t(25),t(26),t(28),t(29)))
                                              })

// reduce by key so we will only get one record for every primary key
val reducedRDD =  valid_events_rdd.reduceByKey((a,b) => if ((a._29).compareTo(b._29) > 0) a else b)
//Get all the fields
reducedRDD.map(r => r._1 + "," + r._2._1 + "," + r._2._2).collect().foreach(println)

A: Off the top of my head:

*

*use cases classes which no longer have size limit. Just keep in mind that cases classes won't work correctly in Spark REPL,

*use Row objects directly and extract only keys,

*operate directly on a DataFrame,
import org.apache.spark.sql.functions.{col, max}

val maxs = df
  .groupBy(col("key1"), col("key2"))
  .agg(max(col("epoch")).alias("epoch"))
  .as("maxs")

df.as("df")
  .join(maxs,
    col("df.key1") === col("maxs.key1") &&
    col("df.key2") === col("maxs.key2") &&
    col("df.epoch") === col("maxs.epoch"))
  .drop(maxs("epoch"))
  .drop(maxs("key1"))
  .drop(maxs("key2"))

or with window function:
val w = Window.partitionBy($"key1", $"key2").orderBy($"epoch")

df.withColumn("rn_", rowNumber.over(w)).where($"rn" === 1).drop("rn")


text:
Q: Best way to print list output in python I have a list and a list of list like this
>>> list2 = [["1","2","3","4"],["5","6","7","8"],["9","10","11","12"]]
>>> list1 = ["a","b","c"]

I zipped the above two list so that i can match their value index by index.
>>> mylist = zip(list1,list2)
>>> mylist
[('a', ['1', '2', '3', '4']), ('b', ['5', '6', '7', '8']), ('c', ['9', '10', '11', '12'])]

Now I tried to print the output of above mylist using
>>> for item in mylist:
...     print item[0]
...     print "---".join(item[1])
...

It resulted in this output which is my desired output.
a
1---2---3---4
b
5---6---7---8
c
9---10---11---12

Now, my question is there a more cleaner and better way to achieve my desired output or this is the best(short and more readable) possible way.

A: Well, you could avoid some temporary variables and use a nicer loop:
for label, vals in zip(list1, list2):
    print label
    print '---'.join(vals)

I don't think you're going to get anything fundamentally "better," though.

A: The following for loop will combine both the print and join operations into one line.
 for item in zip(list1,list2):
     print '{0}\n{1}'.format(item[0],'---'.join(item[1]))

A: It may not be quite as readable as a full loop solution, but the following is still readable and shorter:
>>> zipped = zip(list1, list2)
>>> print '\n'.join(label + '\n' + '---'.join(vals) for label, vals in zipped)
a
1---2---3---4
b
5---6---7---8
c
9---10---11---12

A: Here's another way to achieve the result.  It's shorter, but I'm not sure it's more readable:
print '\n'.join([x1 + '\n' + '---'.join(x2) for x1,x2 in zip(list1,list2)])

A: What you might consider clean, but I do not, is that your the rest of your program needs to now the structure of your data and how to print it. IMHO that should be contained in the class of the data, so you can just do print mylist and get the desired result.
If you combine that with mgilson's suggestion to use a dictionary ( I would even suggest an OrderedDict) I would do something like this:
from collections import OrderedDict

class MyList(list):
    def __init__(self, *args):
        list.__init__(self, list(args))

    def __str__(self):
        return '---'.join(self)

class MyDict(OrderedDict):
    def __str__(self):
        ret_val = []
        for k, v in self.iteritems():
            ret_val.extend((k, str(v)))
        return '\n'.join(ret_val)

mydata = MyDict([
    ('a', MyList("1","2","3","4")),
    ('b', MyList("5","6","7","8")),
    ('c', MyList("9","10","11","12")),
])

print mydata

without requiring the rest of the program needing to know the details of printing this data.