Q: Type 'List' is not a subtype of type 'Map' I'm developing a flutter application that depends on API REST calls.The Response from the API is a bit complex.
I can see the response from the log when calling my API (e.g : api/products) :
But i have this Error :  type 'List< dynamic >' is not a subtype of type 'Map< String, dynamic >'
I've seen all the questions/answers on the internet without any result.
I've tried with a simple RestAPI like : https://my-json-server.typicode.com/typicode/demo/posts and it works.
but it doesn't in my case
API Response Example :
[
   {
      "id":1,
      "tenant":{
         "id":1,
         "code":"company",
         "name":"company"
      },
      "type":{
         "code":"activity",
         "name":"Activité"
      },
      "subType":{
         "code":"ticket",
         "name":"Ticket"
      },
      "inventoryType":{
         "code":"external_source",
         "name":"Source externe"
      },
      "externalReference":"CAL6970",
      "externalSystem":{
         "code":"koedia",
         "name":"Koedia"
      },
      "active":true,
      "durationDays":12,
      "durationNights":14,
      "durationHours":9,
      "durationMinutes":10,
      "supplier":{
         "id":1,
         "tenant":{
            "id":1,
            "code":"company",
            "name":"company"
         },
         "name":"Jancarthier"
      },
      "group":null,
      "subGroup":null,
      "name":"Hôtel Koulnoué Village",
      "translations":[
         {
            "id":1,
            "name":"Hôtel Koulnoué Village",
            "locale":"fr"
         },
         {
            "id":24,
            "name":"Hôtel Koulnoué Village",
            "locale":"en"
         }
      ],
      "vatPercentage":"0.00",
      "longitude":null,
      "latitude":null,
      "departureTime":null,
      "arrivalTime":null,
      "arrivalDayPlus":1,
      "stars":4,
      "localities":[
         {
            "id":41,
            "locality":{
               "id":34,
               "code":"ARM",
               "name":"Armenia"
            },
            "role":{
               "code":"stop",
               "name":"Escale"
            }
         },
         {
            "id":49,
            "locality":{
               "id":55,
               "code":"hossegor",
               "name":"Hossegor"
            },
            "role":{
               "code":"drop_off",
               "name":"Retour"
            }
         },
         {
            "id":50,
            "locality":{
               "id":55,
               "code":"hossegor",
               "name":"Hossegor"
            },
            "role":{
               "code":"localisation",
               "name":"Localisation"
            }
         }
      ]
   }
]

StackTrace  :
I/flutter ( 2865): type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

[Updated] : return ProductsResponse.fromJson(response) instead of response
ProductsRespository :
import 'dart:async';
import 'package:day_experience/models/product/ProductResponse.dart';
import 'package:day_experience/networking/ApiProvider.dart';

class ProductRepository {
  ApiProvider _provider =  ApiProvider();

  Future<ProductsResponse> fetchProducts() async {

      final response = await _provider.getFromApi("products");
      // here line 11 where exception is thrown
      return ProductsResponse.fromJson(response);
  }

}

ProductsBloc :
import 'dart:async';

import 'package:day_experience/models/product/ProductResponse.dart';

import 'package:day_experience/networking/Response.dart';
import 'package:day_experience/repository/ProductRepository.dart';

class ProductBloc {
  ProductRepository _productRepository;
  StreamController _productListController;
  bool _isStreaming;
  StreamSink<Response<ProductsResponse>> get productListSink =>
      _productListController.sink;

  Stream<Response<ProductsResponse>> get productListStream =>
      _productListController.stream;

  ProductBloc() {
    _productListController = StreamController<Response<ProductsResponse>>();
    _productRepository = ProductRepository();
    _isStreaming = true;
    fetchProducts();

  }

  fetchProducts() async {
    productListSink.add(Response.loading('Getting Products.'));
    try {
     ProductsResponse productsResponse =
      await _productRepository.fetchProducts();
     if (_isStreaming) productListSink.add(Response.completed(productsResponse));
    } catch (e) {
      if (_isStreaming) productListSink.add(Response.error(e.toString()));
      print(e);
    }
  }

  dispose() {
    _isStreaming = false;
    _productListController?.close();
  }
}

Response :
class Response<T> {
  Status status;
  T data;
  String message;

  Response.loading(this.message) : status = Status.LOADING;
  Response.completed(this.data) : status = Status.COMPLETED;
  Response.error(this.message) : status = Status.ERROR;

  @override
  String toString() {
    return "Status : $status \n Message : $message \n Data : $data";
  }
}

enum Status { LOADING, COMPLETED, ERROR }

ApiProvider :
import 'package:day_experience/networking/CustomException.dart';
import 'package:http/http.dart' as http;
import 'dart:io';
import 'dart:convert';
import 'dart:async';

class ApiProvider {

  final String _baseApiUrl = "URL_API/";

  Future<dynamic> getFromApi(String url) async {
    var responseJson;
    try {
      final response = await http.get(Uri.encodeFull(_baseApiUrl + url),headers:{"Accept":"application/json"} );
      print(response);
      responseJson = _response(response);
    } on SocketException {
      throw FetchDataException('No Internet connection');
    }
    return responseJson;
  }

  dynamic _response(http.Response response) {
    switch (response.statusCode) {
      case 200:
        var responseJson = json.decode(response.body);

        print(responseJson);
        return responseJson;
      case 400:
        throw BadRequestException(response.body.toString());
      case 401:

      case 403:
        throw UnauthorisedException(response.body.toString());
      case 500:

      default:
        throw FetchDataException(
            'Error occured while Communication with Server with StatusCode : ${response.statusCode}');
    }
  }
}

Model : ProductResponses
import 'ExternalSystem.dart';
import './InventoryType.dart';
import './Localities.dart';
import 'SubType.dart';
import 'Supplier.dart';
import 'Tenant.dart';
import './Translation.dart';
import './Type.dart';

class ProductsResponse {
    final int id;
    final Tenant tenant;
    final Type type;
    final SubType subType;
    final InventoryType inventoryType;
    final String externalReference;
    final ExternalSystem externalSystem;
    final bool active;
    final int durationDays;
    final int durationNights;
    final int durationHours;
    final int durationMinutes;
    final Supplier supplier;
    final String name;
    final List<Translation> translations;
    final String vatPercentage;
    final int arrivalDayPlus;
    final int stars;
    final List<Localities> localities;
    final String group;
    final String subGroup;
    final double longitude;
    final double latitude;
    final String departureTime;
    final String arrivalTime;

    ProductsResponse({this.id, this.tenant , this.type, this.subType, this.inventoryType, this.externalReference, this.externalSystem, this.active, this.durationDays, this.durationNights, this.durationHours, this.durationMinutes, this.supplier, this.name, this.translations, this.vatPercentage, this.arrivalDayPlus, this.stars, this.localities, this.group, this.subGroup, this.longitude, this.latitude, this.departureTime, this.arrivalTime});

    factory ProductsResponse.fromJson(Map<String, dynamic> json) {
        return ProductsResponse(
            id: json['id'],
            tenant: json['tenant'] != null ? Tenant.fromJson(json['tenant']) : null,
            type: json['type'] != null ? Type.fromJson(json['type']) : null,
            subType: json['subType'] != null ? SubType.fromJson(json['subType']) : null,
            inventoryType: json['inventoryType'] != null ? InventoryType.fromJson(json['inventoryType']) : null,
            externalReference: json['externalReference'],
            externalSystem: json['externalSystem'] != null ? ExternalSystem.fromJson(json['externalSystem']) : null,
            active: json['active']?json['active']:null,
            durationDays: json['durationDays']?json['durationDays']:null,
            durationNights: json['durationNights']?json['durationNights']:null,
            durationHours: json['durationHours']?json['durationHours']:null,
            durationMinutes: json['durationMinutes']?json['durationMinutes']:null,
            supplier: json['supplier'] != null ? Supplier.fromJson(json['supplier']) : null,
            name: json['name']?json['name']:null,
            translations: json['translations'] != null ? (json['translations'] as List).map((i) => Translation.fromJson(i)).toList() : null,
            vatPercentage: json['vatPercentage']?json['vatPercentage']:null,
            arrivalDayPlus: json['arrivalDayPlus']?json['arrivalDayPlus']:null,
            stars: json['stars']?json['stars']:null,
            localities: json['localities'] != null ? (json['localities'] as List).map((i) => Localities.fromJson(i)).toList() : null,
            group: json['group'] != null ? json['group'] : null,
            subGroup: json['subGroup'] != null ? json['subGroup'] : null,
            longitude: json['longitude'] != null ? json['longitude'] : null,
            latitude: json['latitude'] != null ? json['latitude'] : null,
            departureTime: json['departureTime'] != null ? json['departureTime'] : null,
            arrivalTime: json['arrivalTime'] != null ? json['arrivalTime'] : null,
        );
    }

    Map<String, dynamic> toJson() {
        final Map<String, dynamic> data = new Map<String, dynamic>();
        data['id'] = this.id;
        data['externalReference'] = this.externalReference;
        data['active'] = this.active;
        data['durationDays'] = this.durationDays;
        data['durationNights'] = this.durationNights;
        data['durationHours'] = this.durationHours;
        data['durationMinutes'] = this.durationMinutes;
        data['name'] = this.name;
        data['vatPercentage'] = this.vatPercentage;
        data['arrivalDayPlus'] = this.arrivalDayPlus;
        data['stars'] = this.stars;
        if (this.tenant != null) {
            data['tenant'] = this.tenant.toJson();
        }
       if (this.type != null) {
            data['type'] = this.type.toJson();
        }
        if (this.subType != null) {
            data['subType'] = this.subType.toJson();
        }
        if (this.inventoryType != null) {
            data['inventoryType'] = this.inventoryType.toJson();
        }
        if (this.externalSystem != null) {
            data['externalSystem'] = this.externalSystem.toJson();
        }
        if (this.supplier != null) {
            data['supplier'] = this.supplier.toJson();
        }
        if (this.translations != null) {
            data['translations'] = this.translations.map((v) => v.toJson()).toList();
        }
        if (this.localities != null) {
            data['localities'] = this.localities.map((v) => v.toJson()).toList();
        }
        if (this.group != null) {
            data['group'] = this.group;
        }
        if (this.subGroup != null) {
            data['subGroup'] = this.subGroup;
        }
        if (this.longitude != null) {
            data['longitude'] = this.longitude;
        }
        if (this.latitude != null) {
            data['latitude'] = this.latitude;
        }
        if (this.departureTime != null) {
            data['departureTime'] = this.departureTime;
        }
        if (this.arrivalTime != null) {
            data['arrivalTime'] = this.arrivalTime;
        }
      print(data);

        return data;
    }
}

[Updated] : removed ProductsRepository (should only access via bloc)
ProductView
import 'package:day_experience/blocs/ProductBloc.dart';
import 'package:day_experience/models/product/ProductResponse.dart';
import 'package:day_experience/networking/Response.dart';
import 'package:day_experience/repository/ProductRepository.dart';
import 'package:day_experience/view/widget/Loading.dart';
import 'package:day_experience/view/widget/ProductList.dart';
import 'package:flutter/material.dart';
import 'package:day_experience/view/widget/Error.dart';

class ProductView extends StatefulWidget {
 @override
 _ProductViewState createState() => _ProductViewState();
}

class _ProductViewState extends State<ProductView> {
 ProductBloc _bloc = new ProductBloc();

 @override
 void initState() {
   super.initState();
   _bloc.fetchProducts();
 }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       elevation: 0.0,
       automaticallyImplyLeading: false,
       title: Text('Products',
           style: TextStyle(color: Colors.white, fontSize: 20)),
       backgroundColor: Color(0xFF333333),
     ),
     backgroundColor: Color(0xFF333333),
     body: RefreshIndicator(
       onRefresh: () => _bloc.fetchProducts(),
       child: StreamBuilder<Response<ProductsResponse>>(
         stream: _bloc.productListStream,
         builder: (context, snapshot) {
           if (snapshot.hasData) {
             switch (snapshot.data.status) {
               case Status.LOADING:
                 return Loading(loadingMessage: snapshot.data.message);
                 break;
               case Status.COMPLETED:
                 return ProductList(productList:snapshot.data.data);
                 break;
               case Status.ERROR:
                 return Error(
                   errorMessage: snapshot.data.message,
                   onRetryPressed: () => _bloc.fetchProducts(),
                 );
                 break;
             }
           }
           return Container();
         },
       ),
     ),
   );
 }

}

Tenant Example same logic for others(Translation,Type,SubType..)
class Tenant {
   final int id;
   final String code;
   final String name;

   Tenant({this.id, this.code, this.name});

   factory Tenant.fromJson(Map<String, dynamic> json) {
       return Tenant(
           id: json['id'],
           code: json['code'],
           name: json['name'],
       );
   }

   Map<String, dynamic> toJson() {
       final Map<String, dynamic> data = new Map<String, dynamic>();
       data['id'] = this.id;
       data['code'] = this.code;
       data['name'] = this.name;
       return data;
   }
}

A: You can copy paste run full code below
Because your json string produce a List<ProductResponse> not ProductResponse
In your code you can directly return response.body as String and parse with productsResponseFromJson
code snippet
List<ProductsResponse> productsResponseFromJson(String str) =>
List<ProductsResponse>.from(
    json.decode(str).map((x) => ProductsResponse.fromJson(x)));

Future<List<ProductsResponse>> fetchProducts() async {
  ApiProvider _provider = ApiProvider();
  String response = await _provider.getFromApi("products");
  // here line 11 where exception is thrown
  return productsResponseFromJson(response);
  //return ProductsResponse.fromJson(response);
}

Future<String> getFromApi(String url) async {

String _response(http.Response response) {
    switch (response.statusCode) {
      case 200:
        print(response.body);
        //var responseJson = jsonDecode(response.body);

        //print(responseJson);
        return response.body;

working demo

full code
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
//     final productsResponse = productsResponseFromJson(jsonString);

import 'dart:convert';

List<ProductsResponse> productsResponseFromJson(String str) =>
    List<ProductsResponse>.from(
        json.decode(str).map((x) => ProductsResponse.fromJson(x)));

String productsResponseToJson(List<ProductsResponse> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class ProductsResponse {
  int id;
  Tenant tenant;
  ExternalSystem type;
  ExternalSystem subType;
  ExternalSystem inventoryType;
  String externalReference;
  ExternalSystem externalSystem;
  bool active;
  int durationDays;
  int durationNights;
  int durationHours;
  int durationMinutes;
  Supplier supplier;
  dynamic group;
  dynamic subGroup;
  String name;
  List<Translation> translations;
  String vatPercentage;
  dynamic longitude;
  dynamic latitude;
  dynamic departureTime;
  dynamic arrivalTime;
  int arrivalDayPlus;
  int stars;
  List<Locality> localities;

  ProductsResponse({
    this.id,
    this.tenant,
    this.type,
    this.subType,
    this.inventoryType,
    this.externalReference,
    this.externalSystem,
    this.active,
    this.durationDays,
    this.durationNights,
    this.durationHours,
    this.durationMinutes,
    this.supplier,
    this.group,
    this.subGroup,
    this.name,
    this.translations,
    this.vatPercentage,
    this.longitude,
    this.latitude,
    this.departureTime,
    this.arrivalTime,
    this.arrivalDayPlus,
    this.stars,
    this.localities,
  });

  factory ProductsResponse.fromJson(Map<String, dynamic> json) =>
      ProductsResponse(
        id: json["id"],
        tenant: Tenant.fromJson(json["tenant"]),
        type: ExternalSystem.fromJson(json["type"]),
        subType: ExternalSystem.fromJson(json["subType"]),
        inventoryType: ExternalSystem.fromJson(json["inventoryType"]),
        externalReference: json["externalReference"],
        externalSystem: ExternalSystem.fromJson(json["externalSystem"]),
        active: json["active"],
        durationDays: json["durationDays"],
        durationNights: json["durationNights"],
        durationHours: json["durationHours"],
        durationMinutes: json["durationMinutes"],
        supplier: Supplier.fromJson(json["supplier"]),
        group: json["group"],
        subGroup: json["subGroup"],
        name: json["name"],
        translations: List<Translation>.from(
            json["translations"].map((x) => Translation.fromJson(x))),
        vatPercentage: json["vatPercentage"],
        longitude: json["longitude"],
        latitude: json["latitude"],
        departureTime: json["departureTime"],
        arrivalTime: json["arrivalTime"],
        arrivalDayPlus: json["arrivalDayPlus"],
        stars: json["stars"],
        localities: List<Locality>.from(
            json["localities"].map((x) => Locality.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "tenant": tenant.toJson(),
        "type": type.toJson(),
        "subType": subType.toJson(),
        "inventoryType": inventoryType.toJson(),
        "externalReference": externalReference,
        "externalSystem": externalSystem.toJson(),
        "active": active,
        "durationDays": durationDays,
        "durationNights": durationNights,
        "durationHours": durationHours,
        "durationMinutes": durationMinutes,
        "supplier": supplier.toJson(),
        "group": group,
        "subGroup": subGroup,
        "name": name,
        "translations": List<dynamic>.from(translations.map((x) => x.toJson())),
        "vatPercentage": vatPercentage,
        "longitude": longitude,
        "latitude": latitude,
        "departureTime": departureTime,
        "arrivalTime": arrivalTime,
        "arrivalDayPlus": arrivalDayPlus,
        "stars": stars,
        "localities": List<dynamic>.from(localities.map((x) => x.toJson())),
      };
}

class ExternalSystem {
  String code;
  String name;

  ExternalSystem({
    this.code,
    this.name,
  });

  factory ExternalSystem.fromJson(Map<String, dynamic> json) => ExternalSystem(
        code: json["code"],
        name: json["name"],
      );

  Map<String, dynamic> toJson() => {
        "code": code,
        "name": name,
      };
}

class Locality {
  int id;
  Tenant locality;
  ExternalSystem role;

  Locality({
    this.id,
    this.locality,
    this.role,
  });

  factory Locality.fromJson(Map<String, dynamic> json) => Locality(
        id: json["id"],
        locality: Tenant.fromJson(json["locality"]),
        role: ExternalSystem.fromJson(json["role"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "locality": locality.toJson(),
        "role": role.toJson(),
      };
}

class Tenant {
  int id;
  String code;
  String name;

  Tenant({
    this.id,
    this.code,
    this.name,
  });

  factory Tenant.fromJson(Map<String, dynamic> json) => Tenant(
        id: json["id"],
        code: json["code"],
        name: json["name"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "code": code,
        "name": name,
      };
}

class Supplier {
  int id;
  Tenant tenant;
  String name;

  Supplier({
    this.id,
    this.tenant,
    this.name,
  });

  factory Supplier.fromJson(Map<String, dynamic> json) => Supplier(
        id: json["id"],
        tenant: Tenant.fromJson(json["tenant"]),
        name: json["name"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "tenant": tenant.toJson(),
        "name": name,
      };
}

class Translation {
  int id;
  String name;
  String locale;

  Translation({
    this.id,
    this.name,
    this.locale,
  });

  factory Translation.fromJson(Map<String, dynamic> json) => Translation(
        id: json["id"],
        name: json["name"],
        locale: json["locale"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "locale": locale,
      };
}

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

Future<List<ProductsResponse>> fetchProducts() async {
  ApiProvider _provider = ApiProvider();
  String response = await _provider.getFromApi("products");
  // here line 11 where exception is thrown
  return productsResponseFromJson(response);
  //return ProductsResponse.fromJson(response);
}

class ApiProvider {
  Future<String> getFromApi(String url) async {
    var responseJson;
    try {
      //final response = await http.get(Uri.encodeFull(_baseApiUrl + url),headers:{"Accept":"application/json"} );
      String jsonString = '''
      [
   {
      "id":1,
      "tenant":{
         "id":1,
         "code":"company",
         "name":"company"
      },
      "type":{
         "code":"activity",
         "name":"Activité"
      },
      "subType":{
         "code":"ticket",
         "name":"Ticket"
      },
      "inventoryType":{
         "code":"external_source",
         "name":"Source externe"
      },
      "externalReference":"CAL6970",
      "externalSystem":{
         "code":"koedia",
         "name":"Koedia"
      },
      "active":true,
      "durationDays":12,
      "durationNights":14,
      "durationHours":9,
      "durationMinutes":10,
      "supplier":{
         "id":1,
         "tenant":{
            "id":1,
            "code":"company",
            "name":"company"
         },
         "name":"Jancarthier"
      },
      "group":null,
      "subGroup":null,
      "name":"Hôtel Koulnoué Village",
      "translations":[
         {
            "id":1,
            "name":"Hôtel Koulnoué Village",
            "locale":"fr"
         },
         {
            "id":24,
            "name":"Hôtel Koulnoué Village",
            "locale":"en"
         }
      ],
      "vatPercentage":"0.00",
      "longitude":null,
      "latitude":null,
      "departureTime":null,
      "arrivalTime":null,
      "arrivalDayPlus":1,
      "stars":4,
      "localities":[
         {
            "id":41,
            "locality":{
               "id":34,
               "code":"ARM",
               "name":"Armenia"
            },
            "role":{
               "code":"stop",
               "name":"Escale"
            }
         },
         {
            "id":49,
            "locality":{
               "id":55,
               "code":"hossegor",
               "name":"Hossegor"
            },
            "role":{
               "code":"drop_off",
               "name":"Retour"
            }
         },
         {
            "id":50,
            "locality":{
               "id":55,
               "code":"hossegor",
               "name":"Hossegor"
            },
            "role":{
               "code":"localisation",
               "name":"Localisation"
            }
         }
      ]
   }
]
    ''';

      http.Response response = http.Response(jsonString, 200);
      print(response);
      responseJson = _response(response);
    } on Exception {
      //throw FetchDataException('No Internet connection');
    }
    return responseJson;
  }

  String _response(http.Response response) {
    switch (response.statusCode) {
      case 200:
        print(response.body);
        //var responseJson = jsonDecode(response.body);

        //print(responseJson);
        return response.body;
      /* case 400:
        throw BadRequestException(response.body.toString());
      case 401:

      case 403:
        throw UnauthorisedException(response.body.toString());
      case 500:

      default:
        throw FetchDataException(
            'Error occured while Communication with Server with StatusCode : ${response.statusCode}');*/
    }
  }
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

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;
  List<ProductsResponse> productResponseList;

  void _incrementCounter() async {
    productResponseList = await fetchProducts();
    print('${productResponseList[0].inventoryType}');
    setState(() {
      _counter++;
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            productResponseList == null
                ? CircularProgressIndicator()
                : Text('${productResponseList[0].inventoryType.name}'),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}


Q: Spring @Autowired(required = true) is null I have a webmodule with JSF 2 end Spring 4.3. In a backing bean I use @Autowired for DI of a service of a JAR. In EAR module there are WAR, JAR with @Service Spring and JAR with Spring configuration file.
Below a web.xml snippet:
    <context-param>
        <param-name>locatorFactorySelector</param-name>
        <param-value>classpath:beanRefContext.xml</param-value>
    </context-param>

    <context-param>
        <param-name>parentContextKey</param-name>
        <param-value>sharedContext</param-value>
    </context-param>
    <context-param>
    <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
<listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <listener>
        <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
    </listener>

applicationContext.xml:
    <context:annotation-config />
    <context:spring-configured />
<!-- package of @Service class in jar module in EAR-- >
    <context:component-scan base-package="com.ipdb.service" />

beanRefContext.xml:

<bean id="sharedContext" class="org.springframework.context.support.ClassPathXmlApplicationContext">    <constructor-arg>
    <list>
        <value>spring-ctx.xml</value>
    </list>
</constructor-arg>    </bean>

When I Use @Autowired(required=null) in a Backing Bean the value is null (there is not any exception). My JSF bean
@Component
@ManagedBean
@ViewScoped
public class PortfolioController {

    @Autowired(required = true)
    private PortfolioService portfolioService;

...

Can you help me, please.

A: PortfolioController is considered a JSF context bean adding @Component to @ManagedBean is totally wrong you can't mark same class as bean in two different contexts (JSF and Spring ).
Two solutions either make PortfolioController a spring bean thus remove the @ManagedBean and @ViewScoped or inject PortfolioController via JSF injection annotation @ManagedProperty
@ManagedProperty("#{portfolioService}")
private PortfolioService portfolioService;

A: if the applicationContext.xml is in your jar dependency, then you need to add asterisk after classpath:
  <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext.xml</param-value>
    </context-param>

With the asterisk  spring search files applicationContext.xml anywhere in the classpath not only the current project.


Q: For excel VBA, using "for each...next" statement. How can you use all the iterated elements at once Here is a sample code that im testing
Sub Selek()

Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)

Dim item As Variant
With fd
    If .Show = -1 Then
        For Each item In .SelectedItems
            MsgBox item
        Next item
    Else
    End If
End With
Range("K1") = item

End Sub

This script shows selected items one by one in different message boxes but I want all selected ones in just a single msgbox.
Followup question. I also need to work with the file paths found for each selected item. I realize I couldn't assign them to a variable once I'm outside of the "With" section. My solution is when I'm still in the "With" block, then I assign the item to a cell and then once I'm out of the "With" block then thats when I assign it to a variable. Is there a way to use the element directly without doing this?


Q: Why `boost::bind()` can't be replaced with `std::bind()` here? In this part of code from the example:
int main()
{
  boost::asio::io_service io;
  printer p(io);
  boost::thread t(boost::bind(&boost::asio::io_service::run, &io));
  io.run();
  t.join();

  return 0;
}

If I replace the boost::bind(&boost::asio::io_service::run, &io) to std::bind(&boost::asio::io_service::run, &io) I get the compilation error:
.../usr/lib/c++/v1/functional:1843:1: note: candidate template
  ignored: couldn't infer template argument '_Fp'
bind(_Fp&& __f, _BoundArgs&&... __bound_args)
^
/usr/lib/c++/v1/functional:1852:1: note: candidate template
  ignored: couldn't infer template argument '_Rp'
bind(_Fp&& __f, _BoundArgs&&... __bound_args)
^
1 error generated.

Why this error happen?
Why std::bind(&printer::print1, &p) works, but std::bind(&boost::asio::io_service::run, &io) doesn't work?

A: The compiler is telling you that it could not figure out the type of the first argument to std::bind.
If you look at io_service::run, you will see that it is overloaded. The compiler had a choice, and this is a possible reason for the compiler not figuring out the type. To test this, you can use a cast:
std::bind(static_cast<size_t (boost::asio::io_service::*)()>(&boost::asio::io_service::run), &io)

This way makes the choice explicit in the code.
With a modern compiler, you don't need to use bind at all. You can do something like this:
[&]() { io.run(); }

That avoids all the problems with the std::bind template. You need to consider variable lifetime and copies vs. references.


Q: how to convert date format range in php for ex below I am getting date range from input
22 Mar, 2021 - 22 Apr, 2021, so what my question is , in MySQL 2019-01-30 00:00:00 (created_at), how to set date range search laravel query

A: You can use php's native functiion to convert string to date format.
$startDate = date('Y-m-d', strtotime('22 Mar, 2021'));//2021-03-22
$endDate = date('Y-m-d', strtotime('22 Apr, 2021'));//2021-04-22

Now you can perform laravel search query. For example:
DB::table('yourTable')
    ->whereBetween('created_at', [$startDate, $endDate])
    ->get();

See Document: strtotime


Q: How to dual-boot Ubuntu and Android on Lenovo s10-3t? I have a problem with installing Android on Ubuntu. I have already 12.04 installed on Ideapad Lenovo s10-3t but I didn't leave an empty partition for Android.
Is it possible to separate it now or do I have to reboot Ubuntu?

A: You can change partitions sizesusing GParted for example. This program is in Ubuntu Software Center. After you succeded with creating partition for Android, you can install it. However be aware that changing partition size can lead to some problems when made wrong.


Q: Rspec not accessing datas updated via capybara? I have a form containing a "name" regular input field and a "content" CKeditor textarea. As described here I can fill in the form and if I stop here I can see the "name" and "content" columns correctly updated in the Test DataBase. Fine.
Now, if I do :
template = ContractTemplate.all.last
puts "#{template.name}" # => "template_name"
puts "#{template.content}" # => "
template_content
"

And then problem begins, if I try to update those two attributes (still using Capybara), I now always fall back on values saved at the "create" action, although they ARE correctly updated into the database. It's just like there where no update of the values. I've tried to do ContractTemplate.reload , but it doesn't work.
Full spec is like this :
it 'should edit a contract template', :js => true do

  visit contract_templates_path
  click_link "Add"

  fill_in "contract_template_name", :with => "test_template_name"
  fill_in_ckeditor "contract_template_content", :with => "test_template_content"
  click_button "Save"

  template = ContractTemplate.all.last
  template.name.should eq("test_template_name") # pass, content created
  template.content.should eq("
\r\n\ttest_template_content
\r\n") # pass

  visit contract_template_path(template.id)

  fill_in "contract_template_name", :with => "edited_test_template_name"
  fill_in_ckeditor "contract_template_content", :with => "edited_test_template_content"
  click_button "Save"

  template.name.should eq("edited_test_template_name") # Fail, because == "test_template_name"
  template.content.should eq("
\r\n\tedited_test_template_content
\r\n") # Fail, not updated too

end

My approach may be wrong, but since the "content" attribute is filled using a wisiwig editor, I just can't see any other way to test if the save action really updates name and content... BTW there is no view in the app where I could display the result of the textarea, it's all going to be rendered as PDF.
Could someone help me ?

A: You need a template.reload after your second save. Otherwise, the template record will  contain the values from when it was first loaded.

A: I GOT IT ! I just had to turn transactionnal fixtures to false inside spec_helper.rb :
RSpec.configure do |config|
  ...
  config.use_transactional_fixtures = false # true by default
  ...
end

Now everything runs fine. Ho my... 4 hours on this, I was just getting mad.


Q: Given $(b, m)$, how can we come up with $(b, m) = (b + mx, m)$? This is the way I prove $(b, m) = (b + mx, m)$:
Suppose $(b, m) = t$.
Then $b = pt$, $m = qt$, where $(p, q) = 1$.
$b + mx = pt + qtx$.
So $(b + mx, m) = (pt + qtx, qt) = t = (b, m)$
But if I am given $(b,m)$, I can't come up with $(b, m) = (b + mx, m)$ right away.
I need some better explanation about the relation between $(b, m)$ and $(b + mx, m)$.

A: If $x$ is an integer, then $(b,m) = (b+mx,m)$.
If $c = (b,m)$ you can easily show that $c\mid (b+mx)$ and $c\mid m$. So $c$ is a common divisor of both $b+mx$ and $m$. Thus $(b,m) \leq (b+mx,m)$ (by definition of $\gcd$).
On the other hand if $d = (b+mx,m)$, then first note $d\mid m$. Then $d\mid b$ as well, since $d\mid (b+mx)$ and $d\mid mx$. So $(b+mx,m) \leq (b,m)$.
Combining both inequalities yields $(b,m) = (b+mx,m)$.

A: Key idea: we can replace a gcd argument with one that yields the same set of common divisors.
Note if $\,d\mid m\,$ then $\,d\mid b\iff d\mid b\!+\!mx.\,$ Thus $\,m,b\,$ and $\,m,\,b\!+\!mx\,$ have the same set $S$ of common divisors $\,d,\,$ so they have the same greatest common divisor $(= \max S)$.
Using modular alrithmetic we can express this equationally, enabling a geometrical view:
${\rm mod\ d}\!:\ $ if $\, m\equiv 0\,$ then $\ b\equiv 0\iff b+mx\equiv 0,\,$ i.e. the systems $\,m\equiv 0,b\equiv 0\,$ and $\,m\equiv 0,\, b+mx\equiv 0\,$ are equivalent.
Geometrically, if we rename to customary  variables, then the equivalent systems of equations is $\ x\equiv 0, y\equiv 0\iff x\equiv 0,\, y+mx\equiv 0.\,$ This says the the origin $\, (x,y) \equiv (0,0)\,$ can be specified either as the intersection of the $y$ axis $(x\equiv 0)$ with the $x$ axis $(y\equiv 0)$ or, equivalently, as the intersection of the $y$ axis $(x\equiv 0)$ with the line $\, y\equiv -mx.\,$
If you know linear algebra you will recognize this equivalence as the effect of an elementary linear transformation. This connection between linear algebra and number theory will be made more explicit when one studies module theory in abstract algebra.


Q: Efficient way to convert units from one system to another I'm having an hard time figuring an efficient way to converts differents types of unit to various other types.
Switch cases would work, but IMO that's not an efficient way has I will have 3 different Systems (SI, Imperial and US).
My converter (inside my app) will always convert from SI to something or from something to SI.  It kinds of lower the complexity, but yet I still need advice on how to make clean code.
I had defined that my input parameters for conversion would be Value(number) and Unit(string).
I would have 2 functions.   SIToSomething(value, unit) and SOmethingToSi(value, unit).
Unit is defined because I would be converting length, weight, qty etc..
What would you suggest ?

A: How about this:
var converters = {
    'SIToImperial' : {
        'cm' : function(val) {
            // implementation, return something
        },
        'kg' : function(val) {
            // implementation, return something
        } //, etc.
    },
    'SIToUS' : {
        'cm' : function(val) {
            // implementation, return something
        },
        'kg' : function(val) {
            // implementation, return something
        } //, etc.
    },
    'USToSI' : {
        'cm' : function(val) { /* ... */ } // etc
    } // , etc
}

SIToSomething(value, unit, system) {
    return converters["SITo" + system][unit](value);
}

var meterInImperial = SIToSomething(100, 'cm', 'Imperial');
var fiftyKilosInUS = SIToSomething(50, 'kg', 'US');

A: What you can do is have a base unit, and for each target unit, define conversion functions to/from this base unit. Then, to convert from A to B, for example, you'd have this:
A -> base -> B

This way, you only need two conversion functions per unit (not counting the base unit):
var units = {
    a: {
        toBase: function(value) { return value * 2; },
        fromBase: function(value) { return value / 2; }
    },
    b: {
        toBase: function(value) { return 1.734 * value + 48; },
        fromBase: function(value) { return (value / 1.734) - 48; }
    }
}

function convertFromTo(unitA, unitB, value) {
    return unitB.fromBase(unitA.toBase(value));
}

convertFromTo(units.a, units.b, 36489);

A: Do all conversions to/from SI. For example if converting Imperial->US, you'd go Imperial->SI->US.
This is minimal effort you can put in. It also gets you SI "for free".


Q: Writing UTF-8 fields from mysql in PHP to CSV format I am using a php class, where it writes and stores CSV files in the folder of my site. But am unable to write UTF-8 characters of different languages which is present in my database.
I am using the following class to write csv file. How can I add support to write utf-8 characters to this class. I have tried google and other places, but no finding any luck.
class b3rtCSVWriter
{
var $filename;
var $delimiter;

var $fileHandle;
var $fileBuffer;
var $fileBufferSize;

var $errorList;

/*function b3rtCSVWriter()
    {
    }*/

    function __construct()
    {
    $this->filename = '';
    $this->delimiter = ',';

    $this->fileHandle = NULL;
    $this->fileBuffer = '';
    $this->fileBufferSize = 4096;

    $this->errorList = array();
    }

    function __destruct()
    {
    $this->closeFile();
    }

    function setFilename($filename)
    {
    $this->filename = $filename;

    return $this->openFile();
    }

    function setDelimiter($delimiter)
    {
    if (strlen($delimiter) != 1)
        {
        $this->setError('Invalid delimiter');
        return FALSE;
        }

    $this->delimiter = $delimiter;
    return TRUE;
    }

    function getErrors()
    {
    return $this->errorList;
    }

    function putRecord($recordData)
    {
    if ($this->errorList)
        return ($this->fileHandle === NULL ? '' : FALSE);

    $rowBuffer = '';

    // Check if recordData is an array
    if (isset($recordData) && is_array($recordData))
        {
        $currentFieldIndex = -1;
        $lastFieldIndex = count($recordData) - 1;

        // Loop through every array item
        foreach($recordData as $recordValue)
            {
            $currentFieldIndex++;
            $isQuotedField = FALSE;

            // Set isQuotedField if a " is present and replace " with ""
            if (strpos($recordValue, '"') !== FALSE)
                {
                $isQuotedField = TRUE;
                $recordValue = str_replace('"', '""', $recordValue);
                }

            // Set isQuotedField if a delimiter or newline is present
            if ((strpos($recordValue, $this->delimiter) !== FALSE) ||
                (strpos($recordValue, "\n") !== FALSE))
                $isQuotedField = TRUE;

            // Put field inside " if isQuotedField is set
            if ($isQuotedField)
                $recordValue = '"'.$recordValue.'"';

            // Add recordValue to rowBuffer and, if not at last field, a delimiter
            $rowBuffer .= $recordValue .
                ($currentFieldIndex != $lastFieldIndex ? $this->delimiter : '');
            }
        }

    // Add EOL to rowBuffer, even when it's empty
    $rowBuffer .= "\r\n";

    // If no file is currently open, return rowBuffer as is
    if ($this->fileHandle === NULL)
        return $rowBuffer;
    else // Else write rowBuffer to file
        return $this->writeFile($rowBuffer);
    }

    function openFile()
    {
    $this->closeFile();

    if ($this->filename == '')
        $this->setError('Invalid filename');

    if ($this->errorList)
        return FALSE;

    $this->fileHandle = @fopen($this->filename, 'w');
    if (!$this->fileHandle)
        {
        $this->setError('Could not open file');
        $this->fileHandle = NULL;
        return FALSE;
        }

    if (!flock($this->fileHandle, LOCK_EX))
        {
        $this->setError('Could not lock file');
        $this->closeFile();
        return FALSE;
        }

    return TRUE;
    }

    function writeFile($toWrite, $forceWrite = FALSE)
    {
    if ($this->fileHandle === NULL)
        {
        $this->setError('No file specified');
        return FALSE;
        }

    $this->fileBuffer .= $toWrite;

    if ($forceWrite || (strlen($this->fileBuffer) > $this->fileBufferSize))
        {
        if (@fwrite($this->fileHandle, $this->fileBuffer, strlen($this->fileBuffer)) === FALSE)
            {
            $this->setError('Could not write to file');
            return FALSE;
            }

        $this->fileBuffer = '';
        }

    return TRUE;
    }

    function closeFile()
    {
    if (is_resource($this->fileHandle))
        {
        // Force buffer to be written
        $this->writeFile('', TRUE);

        if (!fflush($this->fileHandle))
            $this->setError('Could not flush output to file');
        if (!flock($this->fileHandle, LOCK_UN))
            $this->setError('Could not unlock file');
        if(!@fclose($this->fileHandle))
            $this->setError('Could not close file');
        }

    $this->fileHandle = NULL;
    }

    function setError($error)
    {
    $this->errorList[] = $error;
    }
    }

After browsing from so many days, I found that I would have to need to add BOM to fix UTF-8 in Excel, but was unseccessful in adding to this class.
    $fp = fopen('php://output', 'w');
    fputs($fp, $bom =( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
    fclose($fp);

A: Add it here:
$this->fileHandle = @fopen($this->filename, 'w');
if (!$this->fileHandle)
    {
    $this->setError('Could not open file');
    $this->fileHandle = NULL;
    return FALSE;
    }
fputs($this->fileHandle, chr(0xEF) . chr(0xBB) . chr(0xBF));


Q: Ignore Rewrite Rule for images folder I have a .htaccess file on a website I'm working on which rewrites urls from mydomain.com/sub/folder/ to mydomain.com?index.php?controller=sub&view=folder
Unfortunately the way I've written it means I can't access images, stylesheets and other linked files anymore.  Could anyone tell me how best to exclude specific directories / URL requests from the rewrite rule?
Apologies if this is a bit of a newbie question, I'm still wrapping my head around this mod rewrite stuff!
The .htaccess file looks like this:
RewriteEngine on
RewriteRule ^([a-zA-Z0-9-]+)/?$ index.php?Controller=$1
RewriteRule ^([a-zA-Z0-9-]+)/([a-zA-Z0-9-_]+)/? index.php?Controller=$1&View=$2

A: If your images are in mydomain.com/images and you are linking to them using relative links on the page mydomain.com/sub/folder/ the browser is going to try to attempt to access the image via mydomain.com/sub/folder/images/i.gif. But if you change your links to absolute links, the browser will correctly attempt to load mydomain.com/images/i.gif. However, the RewriteRule will change it to: mydomain.com/index/php?Controller=images&View=i.gif. To avoid this you need to add a few RewriteConds:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([a-zA-Z0-9-_]+)\/?$ index.php?Controller=$1
RewriteRule ^([a-zA-Z0-9-_]+)/([a-zA-Z0-9-_]+)\/? index.php?Controller=$1&View=$2

So that when attempting at access an existing file/directory, don't rewrite to index.php.


Q: How can I save the array to a text file and import it back? Basically, I want to know how to get my array that gets data from peoples input saved to a text file and automatically imported back into the array when the program starts again.
Edit: Now after this, it seems saving and reopening adds data to the same subarrays
My code:
import json
import time

datastore=[]
datastore = json.load(open("file.json"))
menuon = 1

def add_user():
    userdata = input("How many users do you wish to input?")
    print("\n")

    if (userdata == 0):
        print("Thank you, have a nice day!")

    else:
        def add_data(users):
            for i in range(users):
                datastore.append([])
                datastore[i].append(input("Enter Name: "))
                datastore[i].append(input("Enter Email: "))
                datastore[i].append(input("Enter DOB: "))
        add_data(int(userdata))

def print_resource(array):
    for entry in datastore:
        print("Name:  "+entry[0])
        print("Email:  "+entry[1])
        print("DOB:  "+entry[2])
        print("\n")

def search_function(value):
  for eachperson in datastore:
      if value in eachperson:
          print_resource(eachperson)

while menuon == 1:
    print("Hello There. What would you like to do?")
    print("")
    print("Option 1: Add Users")
    print("Option 2: Search Users")
    print("Option 3: Replace Users")
    print("Option 4: End the program")
    menuChoice = input()

    if menuChoice == '1':
        add_user()

    if menuChoice == '2':
        searchflag = input("Do you wish to search the user data? y/n")
        if(searchflag == 'y'):
            criteria = input("Enter Search Term: ")
            search_function(criteria)

    if menuChoice == '3':
        break

    if menuChoice == '4':
        print("Ending in 3...")
        time.sleep(1)
        print("2")
        time.sleep(1)
        print("1")
        json.dump(datastore, open("file.json", "w"))
        menuon=0

A: This module would do what you want: http://docs.python.org/3/library/pickle.html
An example:
import pickle

array = ["uno", "dos", "tres"]

with open("test", "wb") as f:
    pickle.dump(array, f)

with open("test", "rb") as f:
    unpickled_array = pickle.load(f)
    print(repr(unpickled_array))

Pickle serializes your object. In essence this means it converts it to a storeable format that can be used to recreate a clone of the original.
Check out the wiki entry if you're interested in more info: http://en.wikipedia.org/wiki/Serialization

A: Python docs have a beautiful explanation on how to handle text files among other files to read/write. Here's the link:
http://docs.python.org/2/tutorial/inputoutput.html
Hope it helps!

A: You need to serialize the array somehow to store it in a file.  Serialize basically just means turn into a representation that is linear.  For our purposes that means a string.  There are several ways (csv, pickle, json). My current favorite way to do that is json.dump() and json.load() to read it back in.  See json docs
import json

def save_file():
    with open('datafile.json', 'w') as f:
        json.dump(datastore, f)

def load_file():
    with open('datafile.json', 'r') as f:
        datastore = json.load(f)

A: Use JSON; Python has a json module built-in :
import json

datastore = json.load(open("file.json")) // load the file

datastore["new"] = "new value" // do something with your data

json.dump(datastore, open("file.json", "w")) // save data back to your file

You could also use Pickle to serialize a dictionary, but JSON is better for small data and is human-readable and editable with a simple text editor, where as Pickle is a binary format.
I've updated your code to use JSON and dictionaries, and it works fine :
import json
import time

datastore = json.load(open("file.json"))
menuon = 1

def add_user():
    userdata = input("How many users do you wish to input?")
    print("\n")

    if (userdata == 0):
        print("Thank you, have a nice day!")
    else:
        def add_data(users):
            for i in range(users):
                datastore.append({"name":input("Enter Name: "), "mail":input("Enter Email: "), "dob":input("Enter DOB: ")})
        add_data(int(userdata))

def print_resource(array):
    for entry in datastore:
        print("Name:  "+entry["name"])
        print("Email:  "+entry["mail"])
        print("DOB:  "+entry["dob"])
        print("\n")

def search_function(value):
  for eachperson in datastore:
    for i in eachperson.keys():
        if value in eachperson[i]:
            print_resource(eachperson)

while menuon == 1:
    print("Hello There. What would you like to do?")
    print("")
    print("Option 1: Add Users")
    print("Option 2: Search Users")
    print("Option 3: Replace Users")
    print("Option 4: End the program")
    menuChoice = input()

    if menuChoice == '1':
        add_user()

    if menuChoice == '2':
        searchflag = input("Do you wish to search the user data? y/n")
        if(searchflag == 'y'):
            criteria = input("Enter Search Term: ")
            search_function(criteria)

    if menuChoice == '3':
        break

    if menuChoice == '4':
        print("Ending in 3...")
        time.sleep(1)
        print("2")
        time.sleep(1)
        print("1")
        json.dump(datastore, open("file.json", "w"))
        menuon=0


Q: $SO(n)$ algebra relations in the vector rep The $\mathfrak{so}(n)$ algebra has some relations between generators always indicated as
$$\left[T_{ij}, T_{kl}\right] = \delta_{ik}T_{jl} - \delta_{jk}T_{li} - \delta_{jl} T_{ik}  + \delta_{il}T_{jk}$$
now I would like to know how to indicate this in a vector rep, i.e. by objects intrinsically with one index. In particular, I am asking the explicit form of the structure constants
$$\left[T_a, T_b\right] = F_{ab}^{\phantom{ab}c}T_c\, .$$


Q: Post data in C# and use response in CefSharp I'm trying to post parameters to a website and use the response in my CefSharp browser. Using my current code it posts the data and loads the html in CefSharp. The html page that loads is exactly what I want meaning the post works but as soon as I click a button it just loads up the website without an of the parameters I posted. How could I use the cookies from the request so that if I click the button everything should remain the way it was posted.
Here is the code i'm using to post:
using (var client = new HttpClient())
{
    var values = new Dictionary<string, string>
    {
        { },
        { },
        { },  <----- Parameters go here
        { },
        { },
    };

    //WebClient client2 = new WebClient();

    client.DefaultRequestHeaders.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");
    var content = new FormUrlEncodedContent(values);
    var response = await client.PostAsync("URL", content);
    var responseString = await response.Content.ReadAsStringAsync();
    CookieContainer cookies = new CookieContainer();
    HttpClientHandler handler = new HttpClientHandler();
    handler.CookieContainer = cookies;
    chrome.LoadHtml(responseString, "URL");


Q: How to make Recycle Bin in ASP.Net i want to create a Recycle Bin in my web project, i use a Details View with EDIT and DELETE option to present and edit data from database and its worked perfectly but want a Recycle Bin for Deleted Data and if Owner wants to delete completely Delete from Recycle .
if u have some codes or  idea or some links help me please !

A: You shall have a field in db which means isDeteled or isRecycled and when it is set to 1 show it in recycleBin/ if user finally deletes record delete if from db.
Better choice is to have status field for enum Active/Archived/Deleted or Active/Archived/Deleted/Purged
when the record in last state of this enum delete it in real time, or by SQL clean-up job or something like this.


Q: Trouble finding the floor function of a given expression. I am currently learning a bit about number theory - currently studying continuous fractions and came up with the following task:
Task. Show that the floor function of $$ \frac{n + \sqrt{n^2+4}}{2},$$ where $n$ is a positive integer, i.e., $n \in \Bbb N$ is $n$.
Obviously, the objective of this is to say that $ \frac{n + \sqrt{n^2+4}}{2} = [n; (...)]$, but I can't make this first step. How would one prove what's wanted?
I have tried doing it by induction and also tried squaring the expression, but couldn't find something that helped me.
Thanks for any help in advance.

A: The major observation is that the addition of $4$ does not increase the value of $n^2$ by very much—after taking square roots and dividing by $2$, this $+4$ contributes little to the term.  In more detail:
Observe that
$$ n^2 + 4 = (n+2)^2 - 4n, $$
where $4n > 0$ (since $n > 0$).  Then, as all of the relevant terms are positive,
\begin{align}
n^2 < n^2 + 4 < (n+2)^2
 &\iff n < \sqrt{n^2 + 4} < n+2 && \text{(take square roots)}\\
 &\iff 2n < n + \sqrt{n^2+2} < 2n + 2 && \text{(add $n$)} \\
 &\iff n < \frac{n+\sqrt{n^2+4}}{2} < n+1. && \text{(multiply by $\tfrac{1}{2}$)}
\end{align}
This is precisely what was desired.

A: First we prove the following two properties of the square-root function:

(1) For any positive real numbers $a$ and $b$, if $a < b$, then $\sqrt{ a} < \sqrt{b}$.

Proof:

We note that, if $b > a > 0$, then $b-a > 0$ and $\sqrt{b} + \sqrt{a} > 0$, which implies that
$$
\sqrt{b} - \sqrt{a} = \frac{ \left( \sqrt{b} \right)^2 - \left( \sqrt{a} \right)^2 }{ \sqrt{b} + \sqrt{a} } = \frac{ b-a }{ \sqrt{b} + \sqrt{a} } > 0,
$$
and hence
$$
\sqrt{b} > \sqrt{a},
$$
as required.

Alternatively, we note that derivative of the function $f(x) = \sqrt{x}$ for $x > 0$ is given by
$$
f^\prime (x) = \frac{ 1 }{ 2 \sqrt{x} } > 0,
$$
which implies that the square root function is strictly increasing.
Our second property is as follows:

(2) If $a > 0$ and $b > 0$, then we have $\sqrt{ a+b} < \sqrt{a} + \sqrt{b}$.

Proof:

As $a > 0$ and $b > 0$, so we have $a + b > 0$, and thus
$$
\sqrt{ a} + \sqrt{ b} + \sqrt{a + b} > 0
$$
also.
Therefore we have
$$
\left( \sqrt{ a } + \sqrt{ b } \right) - \sqrt{ a+b } = \frac{ \left( \sqrt{ a } + \sqrt{ b } \right)^2 - \left( \sqrt{ a+b } \right)^2 }{ \sqrt{ a} + \sqrt{ b} + \sqrt{a + b}  } = \frac{ a + b + 2 \sqrt{a}\sqrt{b} - a - b}{ \sqrt{ a} + \sqrt{ b} + \sqrt{a + b} } = \frac{2 \sqrt{a}\sqrt{b} }{ \sqrt{a} + \sqrt{b} + \sqrt{ a + b}  } > 0,
$$
which implies that
$$
\sqrt{ a } + \sqrt{ b } > \sqrt{ a+b}.
$$

Now we show that, for each $n = 1, 2, 3, \ldots$, we have
$$
n < \frac{ n + \sqrt{ n^2 + 4 } }{2} < n+1.
$$
We note that
\begin{align}
n &= \frac{n + n}{2} \\
&= \frac{n + \sqrt{n^2} }{2} \\
&< \frac{ n + \sqrt{ n^2 + 4 } }{2} \qquad [\mbox{ because of our property (1) }] \\
&< \frac{ n + \sqrt{ n^2 } + \sqrt{ 4 } }{2} \qquad [\mbox{ because of our property (2) }] \\
&= \frac{ n + n + 2 }{2} \\
&= n+1.
\end{align}
Therefore we must have
$$
\left\lfloor \frac{ n + \sqrt{ n^2 + 4 } }{2}  \right\rfloor = n
$$
for each $n = 1, 2, 3, \ldots$.

A: Easy way: $\ \color{#c00}{x>1},\ \overbrace{x^2 = n\:\!x +1}^{\text{by quad. formula}}\,\underset{\!\!\div\,x}\Longrightarrow\, \overbrace{x = n + \frac{1}x}^{\large \color{#c00}{n\, <\, x \,<\, n+1\!\!\!\!\!\!}}\,\Rightarrow\, \color{#c00}{\lfloor x\rfloor = n}$


Q: Losing custom gridview font when new page selected I am using this code to change the font color in a grid view for a single column depending on value:
       For Each row As GridViewRow In gvSearch.Rows
           If row.Cells(8).Text.Trim = "Used" Then
               row.Cells(8).CssClass = "CautionRow"
           End If
        Next

This code runs after the gridview databind.  However, the gridview has pages available and this code only changes the first page of the grid view.  I can resolve the problem by not allowing pages, but this is a tacky solution.  Any suggetions?

A: Register PageIndexChanging event
onpageindexchanging="gvSearch_PageIndexChanging"

Then in event handler do your font changing logic like
Sub gvSearch_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
{
         For Each row As GridViewRow In gvSearch.Rows
           If row.Cells(8).Text.Trim = "Used" Then
               row.Cells(8).CssClass = "CautionRow"
           End If
        Next
}

A: Actually found my own answer thanks to help from my fellow programmer.  Here's what really works:
In the style sheet (.css) add this:
.CautionRow {
    color: red;
}

... then add this to your code:
Protected Sub gvSearch_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViwRowEventArgs) Handles gvSearch.RowDatabound

    If e.Row.Cells.Count > 1 Then
        If e.Row.Cells(8).Text.ToString.ToLower.Trim = "used" Then
            e.Row.Cells(8).CssClass = "CautionRow"
        End If
    End If
End Sub


Q: Can't attach Unity script to a GameObject I'm a new Unity user, and I'm having issues when trying to attach a C# script to a GameObject:

Can't add script component XYZ, because the script class cannot be found. Make sure there are no errors and that the file name and class name match.

Searching online this issue usually happens when the class name and file name are different, but I've checked that and they are the same. I even tried creating a new empty/default C# script and tried attaching that, but no luck. This is completely empty project, and there are no other scripts with compile errors. GIF showing the error

Any ideas, help would be appreciated?
I'm running Unity 2019.1.of2 Personal on Ubuntu 19.04

A: I managed to solve the issue with help from the comments above. The issue was that Unity was unable to compile/build the project, hence as 3Dave and Corey Smith said - if there are any compile errors you are unable to attache scripts to GameObjects.
I also realized I was unable to run the project. I first though it might be an issue with .NET versions on Ubuntu, but it turned out to be issue with libssl1.0 library (if you have a greater version then Unity won't work on Ubuntu 19.04). See this post for reference: https://forum.unity.com/threads/empty-log-errors-in-2019-1-0f2.669961/#post-4545013
Installing libssl1.0 solved the compile issues, I'm now able to attache scripts to GameObjects and run the project.

A: Old question, but I solved this problem using the Help menu and then Reset Packages to defaults.


Q: Javascript not working on mobile site I'm using JavaScript to submit the current URL, all works fine until I enter to mobile screen, then the JavaScript appears to be gone, this is not only for "mobile" apparently the problem is based on the screen width.
 $( document ).ready(function() {
    $( "#widgetu117_input" ).keyup(function( event ) {
       var getUrl = window.location;
       var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];
    })
})

This is my code.
The form was build using muse (not my doing)

A: I found a solution, it works for me. instead of using document ready, i changed everything to be a function and then, call it with settimeout at 7 seconds (tried with 3 but the problem persisted).
Hope nobody has this problem it was tricky to solve.


Q: Returning a strongly typed promiseValue from angular $modalInstance with TypeScript TypeScript newb Question.  I'm trying to return a strongly typed promise from angular's $modalInstance.
I have something similar to:
this.$modal.open(options).result.then(result => {
    Currently result is type 'any'.
    How do I cast it or affect it to be of type MyType?  (see below)
});

interface myType {
    a: string,
    b: number
}

result: myType;
...

$modalInstance.close(this.result)

A: I actually had to wrap the $modal and $modalInstance services to take a type T. The above answer (which I had initially tried) will not work because the $modalInstance result is a promise of type 'any'. The wrapped $modalInstance is a promise of type T.
module my.interfaces {

export interface IMyModalService<T> {
    open(options: ng.ui.bootstrap.IModalSettings): IMyModalServiceInstance<T>;
}

export interface IMyModalScope<T> extends ng.ui.bootstrap.IModalScope {
    $dismiss(reason?: any): boolean;
    $close(result?: T): boolean;
}

export interface IMyModalServiceInstance<T> extends ng.ui.bootstrap.IModalServiceInstance {
    close(result?: T): void;
    dismiss(reason?: any): void;
    result: angular.IPromise<T>;
    opened: angular.IPromise<any>;
    rendered: angular.IPromise<any>;
}

A: this.$modal.open(options).result.then((result: myType) => {
    Now result is declared to be of your type
});


Q: Transition not working properly on vue when div is being hiding I have simple transition to toggle a div text, however the transition works only when the text is being hiding, however when I click to show the text the transition doesn't work here it is my code:
<template>

    <transition name="fade">

My name is Simon

    </transition>
    <button @click="showName = !showName">Toggle</button>

</template>

A:

My name is Simon

You should open a p tag under the div tag


Q: Crash startActivityForResult(intent,1); I have a problem in my android application, I have a hand page, I change my business with
startActivityForResult (intent, CODE_DE_MON_ACTIVITE).

It works, but then when I replace this page since the second activity with the same code but nothing works. The application crashes.
Knowing that I have all the activities in the Manifest.
Log:
06-28 13:09:47.765: D/AndroidRuntime(254): Shutting down VM
06-28 13:09:47.765: W/dalvikvm(254): threadid=3: thread exiting with uncaught exception (group=0x4001b188)
06-28 13:09:47.765: E/AndroidRuntime(254): Uncaught handler: thread main exiting due to uncaught exception
06-28 13:09:47.775: E/AndroidRuntime(254): java.lang.RuntimeException: Unable to start activity ComponentInfo{referencehit.android/referencehit.android.AddTournamentActivity}: java.lang.NullPointerException
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2496)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread.access$2200(ActivityThread.java:119)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.os.Handler.dispatchMessage(Handler.java:99)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.os.Looper.loop(Looper.java:123)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread.main(ActivityThread.java:4363)
06-28 13:09:47.775: E/AndroidRuntime(254):  at java.lang.reflect.Method.invokeNative(Native Method)
06-28 13:09:47.775: E/AndroidRuntime(254):  at java.lang.reflect.Method.invoke(Method.java:521)
06-28 13:09:47.775: E/AndroidRuntime(254):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
06-28 13:09:47.775: E/AndroidRuntime(254):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
06-28 13:09:47.775: E/AndroidRuntime(254):  at dalvik.system.NativeStart.main(Native Method)
06-28 13:09:47.775: E/AndroidRuntime(254): Caused by: java.lang.NullPointerException
06-28 13:09:47.775: E/AndroidRuntime(254):  at referencehit.android.AddTournamentActivity.onCreate(AddTournamentActivity.java:38)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
06-28 13:09:47.775: E/AndroidRuntime(254):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2459)
06-28 13:09:47.775: E/AndroidRuntime(254):  ... 11 more
06-28 13:09:47.788: I/dalvikvm(254): threadid=7: reacting to signal 3
06-28 1
3:09:47.788: E/dalvikvm(254): Unable to open stack trace file '/data/anr/traces.txt': Permission denied

Have you an idea of my problem?

A: Have you actually assigned a value to the Intent? Simply coding Intent intent; will throw a NullPointerException when you call startActivity(intent); like the one you got. Alternately, have you added your second activity to the Manifest file? Android won't launch an Activity that isn't in its Manifest.

A: Add followin permission to ur AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

If u have forgotten to add it, then add it.


Q: Function with arguments in requestAnimationFrame I'm trying to define a recursive function with arguments using "requestAnimationFrame".
animate(frameElapsed,points,canvas){
        console.log("test");
        if(frameElapsed<points.length-1){
            requestAnimationFrame(this.animate(frameElapsed+1,points,canvas));
        }
        ...
}

When I do this, i get the error "Argument of type 'void' is not assignable to parameter of type 'FrameRequestCallback'. So I tried to define an anonymous function that calls animate to solve this problem.
animate(frameElapsed,points,canvas){
        console.log("test");
        if(frameElapsed<points.length-1){
            requestAnimationFrame(function() {
                this.animate(frameElapsed+1,points,canevas);
            });
        }
        ...
}

Then, I get "ERROR TypeError: Cannot read property 'animate' of undefined" in my web console. I can't manage to solve this problem.
Is there a way to pass arguments to af function called back by requestAnimationFrame ?
Thank you for your help !

A: user120242's solution worked for me !
    animate(frameElapsed, points, canvas) {
        console.log("test");
        if(frameElapsed < points.length - 1) {
            requestAnimationFrame(() => {
                this.animate(frameElapsed + 1, points, canvas);
            });
        }
        ...
    }

Thank you for your help !


Q: Codeigniter - array of json objects in post In fire bug I view my jquery post request parameters, its like this
adults            1
applicants[]    [object Object]
attendees   1
children    0

In this post request the array called applicants contains json object which I want ti iterate over and pull out values in my codeigniter controller. The json string may look like this
({attendees:"2",
  adults:"2",
  children:"0",
  grptype:"2",
  'applicants[]':[{firstname:"John", lastname:"Doe", age:"33", allergies:"true", diabetic:"true",    lactose:"false", note:"nuts"}, {firstname:"Jane", lastname:"Doe", age:"34", allergies:"true", diabetic:"false", lactose:"false", note:"pollen"}]
})

Look at the applicants[] above, see I have info for two people as a json object. I am not sure how access the data in my controller. see this
$applicants = $this->input->post('applicants');
$this->output->append_output("
Here: " . $applicants[0].firstname );

I was thinking $applicants[0] woild refer to the json object and I could just pull outs values on demand. Not sure hat I am doing wrong. Thanks guys.
EDIT
So I have adjusted my json and it looks like this
adults  2
applicants[]    {firstname:"John", lastname:"Doe", age:"23", allergies:"true", diabetic:"true", lactose:"false", note:"nuts"}
applicants[]    {firstname:"Jane", lastname:"Doe", age:"23", allergies:"false", diabetic:"false", lactose:"false", note:""}
attendees   2
children    0

Now I am still getting an error saying
**Message: json_decode() expects parameter 1 to be string, array given**

Any ideas ?
EDIT 2
Ok mu data now liiks like this
adults  1
applicants[]    {"firstname": "John", "lastname": "Doe", "age": "34", "allergies": "true", "diabetic": "true", "lactose": "false", "note": "nuts"}
attendees   1
children    0

In the controller id did this
$applications = $this->input->post('applicants');
foreach ( $applications as $item)
{
  $item = json_decode($item, true);
  $this->output->append_output(print_r($item));
}

This is the result of that logic
Array
(
    [firstname] => John
    [lastname] => Doe
    [age] => 34
    [allergies] => true
    [diabetic] => true
    [lactose] => false
    [note] => nuts
)

Not sure what I am doing wrong, no matter what I do to access the dater I get an error to the effect that I cannot access it like that. How do I pull out the values ?

A: You have to decode it on the server using
$applications = json_decode($this->input->post('applicants'), true);

So, it'll become an associative array and you can use it like an array, without the second argument (true) in json_decode the json will be converted to an object. Until you decode it, it's only a string (json/java script object notation  string).
Update: Since it's already an array of objects then you don't need to use json_decode, just loop the array in your view like
foreach($applicants as $item)
{
     echo $item->firstname . '
';
     echo $item->lastname . '
';
     // ...
}

According to the edit 2 it should be access as an array
echo $item['firstname'] . '
'

A: try this plz
$applicants = $this->input->post('applicants');
$json_output = json_decode($applicants );
foreach ( $json_output as $person)
{
  $this->output->append_output("
Here: " . $person->firstname );
}

or
$json_output = json_decode($applicants,TRUE );
echo $json_output[0][firstname] ;


Q: install matlab 2013a with error I tried to install Matlab2013a in my laptop (Ubuntu system). I download a ISO file (very big) and followed their instruction: mount it and run "install". But it returns me an error:
Cannot locate Java Runtime Enviroment (JRE). The directory ~/Matlab/sys/java/jre/glnx86/jre does not exist.
In the folder ~/Matlab/sys/java/jre/, what I have is "glnxa64". Does that mean that I can't install this version of Matlab in my 32bit laptop? This java comes from Matlab. How should I get it work?

A: Hello MATLAB supports only 64bits version so you must a ubuntu 64 bits see this link of mathworks:
http://www.mathworks.com/support/sysreq/current_release/index.html?sec=linux


Q: Race conditions I'm currently stuck trying to understand two things related to race conditions.
Issue 1:
I have been presented with the following question:
We consider the digital circuit and the value of its inputs a,
and b as given below. For all logic gates, we assume that
there is a gate delay of exactly one time unit (i.e. the gate
delay equals the time between two dotted lines in the
diagram). Give the values of c, d, e, f in the digital circuit for
every point of time between 0 and 8.

And the answer given is as follows:

How exactly is this achieved? This is what I think so far:

*

*c starts at 1 because a start at 0

*d starts at 0 because b start at 1

*When time is equal to 2 a becomes 1... there is a propogation delay of 1 for c to switch over to 0 hence it becomes 0 at 3 time units

*Same logic applies to d

*e and f are meant to be constant 1 or 0 but seem to be affected by something.

What's really going on here? Is it related to a boolean function or soemthing. If so what?
Issue 2:
Does anyone have a simple way or logical approach in which to produce a simple circuit (using XOR, AND, OR, NOT, NAND boolean functions with:

*

*static race condition - when the value is meant to be constant

*dynamic race condition - when a value is expected to change

Many thanks in advance!

A: Okay, so race conditions in asynchronous circuits happen when inputs change at different times  for a gate. Let's say your logical function looks like this
λ = ab + ~b~a

the most straightforward way to implement this function with gates looks like
NOTE: I assume your basic building blocks are AND, OR, and NOT. Obviously in CMOS circuits, NAND, NOR and NOT is how you build circuits, but the general principal stays the same. I also assume AND, NOR, and NOT have the same delay when in reality NAND and NOR have different delays if the output goes form 0 to 1 or 1 to 0, and NOT is about 20% faster than NAND or NOR.
a ->| AND |-------->| OR | -> λ
b ->|  1  |         |    |
                    |    |
a ->| NOT |->|AND|->|    |
b ->| NOT |->| 2 |  |    |

Now, assume that AND and NOT both have a delay of 2ns. That means the OR gate sees the value at it's first position change 2 ns before it sees the value at its second position change.
Which means if a and b both go from 1 to 0, you would expect λ to stay the same, since the output of the first AND gate is going from 1 to 0, but the output of the AND gate goes from 0 to 1, meaning the OR condition stays true.
However, if you get the output from the second AND gate a little bit after the first AND gate, then your OR gate will momentarily see 0,0 at it's input while transitioning from 1,0 to 0,1. Which means λ will have a momentary dip and it'll look like
     __
   a   |___________
     __
   b   |___________
     ____
AND1     |_________
            _______
AND2 ______|
     ______   _____
   λ       |_|

If you look at the inputs of the OR gate right between when AND1 goes down and AND2 goes up, it propagates a 0 through the OR gate, and sure enough, there's a dip in the output 2ns later.
That's a general overview for how race conditions arise. Hope that helps you understand your question.


Q: How to Write a Data Trigger to open Popup by Clicking dynamic Button in WPF? I'm having a dynamic Button in my WPF application, while clicking any one of the button the popup should open and the corresponding Button should turn the Background Color to Orange and rest of the Button should be in default Backgroud Color using DataTrigger and one more condition, at the time of Popup close, the corresponding Button Background Color should turn to the Default Color.

Note: I Can't able to give Name for the Buttons because of Dynamic
  Creation. Here I placed 5 Buttons without Name Property, Consider the
  Button as Dynamic Creation

My XAML Source Code is
<Grid>
    <Grid Height="30px" VerticalAlignment="Top" Margin="0,50,0,0">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="100px"/>
            <ColumnDefinition Width="100px"/>
            <ColumnDefinition Width="100px"/>
            <ColumnDefinition Width="100px"/>
            <ColumnDefinition Width="100px"/>
        </Grid.ColumnDefinitions>
        <Button Content="One" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/>
        <Button Content="Two" Grid.Column="1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/>
        <Button Content="Three" Grid.Column="2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/>
        <Button Content="Four" Grid.Column="3" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/>
        <Button Content="Five" Grid.Column="4" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75"/>
    </Grid>
    <Grid>
        <Popup Name="sPop" Placement="Mouse" StaysOpen="False">
            <Grid>
                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" Text="Welcome to Popup Screen"/>
            </Grid>
        </Popup>
    </Grid>
</Grid>

A: You cannot do it using DataTriggers. DataTriggers are for Data-Based scenarios, so if you are using DataBinding, then use them.
Recommended approach :
Assign a name to your Popup. And use Behaviors.
<Button ...>
    <Button.Style>
        <Style TargetType="Button">
            <Style.Triggers>
                <Trigger Property="IsFocused" Value="True">
                    <Setter Property="Background" Value="Red"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Button.Style>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <i:Interaction.Behaviors>
                <ei:ConditionBehavior>
                    <ei:ConditionalExpression>
                        <ei:ComparisonCondition LeftOperand="{Binding IsFocused, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" RightOperand="True"/>
                    </ei:ConditionalExpression>
                </ei:ConditionBehavior>
            </i:Interaction.Behaviors>
            <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="IsOpen" Value="True"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

To use Blend assemblies :
Add reference to System.Windows.Interactivity and Microsoft.Expression.Interactions and following namespaces :
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

To revert back old Background of the source Button :
<Button>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <i:Interaction.Behaviors>
                <ei:ConditionBehavior>
                    <ei:ConditionalExpression>
                        <ei:ComparisonCondition LeftOperand="{Binding IsFocused, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}" RightOperand="True"/>
                    </ei:ConditionalExpression>
                </ei:ConditionBehavior>
            </i:Interaction.Behaviors>

            <!-- Store Button's old Background -->
            <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="Tag" Value="{Binding Background, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}"/>

            <!-- Change Button's Background -->
            <ei:ChangePropertyAction PropertyName="Background" Value="Purple"/>

            <!-- Open Popup -->
            <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="IsOpen" Value="True"/>

            <!-- Save this Button, Popup will use it to revert back its old Background -->
            <ei:ChangePropertyAction TargetObject="{Binding ElementName=Popup1}" PropertyName="PlacementTarget" Value="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Button}}"/>

        </i:EventTrigger>
    </i:Interaction.Triggers>
</Button>

<Popup x:Name="Popup1" Placement="Mouse" StaysOpen="False">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Closed">
            <ei:ChangePropertyAction
                        TargetObject="{Binding PlacementTarget, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Popup}}"
                        PropertyName="Background"
                        Value="{Binding Tag, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Popup}}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>
    <Grid>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" Text="Welcome to Popup Screen"/>
    </Grid>
</Popup>

A: I tried to achieve what you asking for without using DataTrigger.
This is simple style trigger for changing background:
<Style TargetType="Button">
    <Style.Triggers>
        <Trigger Property="Button.IsFocused" Value="True">
            <Setter Property="Button.Background" Value="Red" />
        </Trigger>
    </Style.Triggers>
</Style>

Each your button can handle Click event:
<Button Content="One" Grid.Column="0" HorizontalAlignment="Center" VerticalAlignment="Center" Width="75" Click="Button_Click" />
...

And we need to take your Popup somehow. I just named it:
<Popup Name="popup" Placement="Mouse" StaysOpen="False">
...

Click event is simple:
private void Button_Click(object sender, RoutedEventArgs e) {
    var button = sender as Button;
    if (popup.IsOpen) { popup.IsOpen = false; }
    popup.PlacementTarget = button;
    popup.IsOpen = true;
}

So it works like you want.


Q: Expensive to set UILabel.attributedText to the same value? I have a view controller within my app that I use for debugging purposes to display some of the internals of the app (only for local xcode builds, the app store version doesn't have this controller).
In this controller, I have a label which I want to reflect the state of an internal component (specifically, I want it to display whether that component is enabled or disabled).
My questions:
#1: Is it expensive to set the .attributedText property of a UILabel to the same value as it was before, or should I cache the old value and only set the property when it changes?
#2: What about the .text (non-attributed) property?
I'm currently using the following code:
// Schedule timer to update the control panel. (This is debug-only, so not worth
// the complexity of making this event-based)
Timer.scheduledTimer(withTimeInterval: 0.5,
                 repeats: true) { [weak self] timer in

    DispatchQueue.main.async {

        // Stop timer if we've been dealloced or are no longer being presented
        guard let strongSelf = self,
              strongSelf.isBeingPresented else
        {
            timer.invalidate()
            return
        }

        // "Something Enabled / Disabled" label
        let somethingIsEnabled = strongSelf.someDepenency.isEnabled
        let somethingEnabledString = NSMutableAttributedString(string: "Something ")

        somethingEnabledString.append(NSAttributedString(string: isEnabled ? "Enabled" : "Disabled",
                                                         attributes: isEnabled ? nil : [NSForegroundColorAttributeName: UIColor(xtHardcodedHexValue: "0xCD0408")]))
        strongSelf.somethingEnabledLabel?.attributedText = somethingEnabledString

    }
}

A: Before I share some numbers, I'd highly recommend to not perform such premature optimizations. Consider the following code:
private func getAttributedString() -> NSMutableAttributedString{
    let attributedString = NSMutableAttributedString(string: "Something ")
    attributedString.append(NSAttributedString(string: "Enabled",
                                                     attributes:  [NSForegroundColorAttributeName: UIColor(rgb: 0xCD0408)]))
    return attributedString
}

//overwrites attributed text 100000 times
@IBAction func overwriteAttributedText(_ sender: Any) {
    let timeBeforeAction = Date.init()
    print ("Time taken to overwrite attributed text is ")
    for _ in 1 ... 100000{
        label.attributedText = getAttributedString()
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

//overwrites attributed text 100 times
@IBAction func cacheAttributedText(_ sender: Any) {
    let timeBeforeAction = Date.init()
    print ("Time taken to selectively overwrite attributed text is ")
    for i in 1 ... 100000{
        if i % 1000 == 0 {
            label.attributedText = getAttributedString()
        }
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

//overwrites text 100000 times
@IBAction func overWriteText(_ sender: Any) {
    let defaultText = "Hello World"
    let timeBeforeAction = Date.init()
    print ("Time taken to overwrite text is ")
    for _ in 1 ... 100000{
        label.text = defaultText
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

Here are the results:
Time taken to overwrite attributed text is 0.597925961017609
Time taken to selectively overwrite attributed text is 0.004891037940979
Time taken to overwrite text is 0.0462920069694519

The results speak for themselves, but I leave it you if such optimizations are even needed.

A: While 7to4 is correct in regards to premature optimizations, the demo code he's using is misleading.  The .attributedText setter itself is actually faster than setting .text; creating the attributed string is the bottleneck.  Here's a modified version of his code that includes a method where the attributed string is pre-cached:
private func getAttributedString() -> NSMutableAttributedString{
    let attributedString = NSMutableAttributedString(string: "Something ")
    attributedString.append(NSAttributedString(string: "Enabled",
                                               attributes:  [NSAttributedStringKey.foregroundColor: UIColor.red]))
    return attributedString
}

//overwrites attributed text 100000 times
@IBAction func overwriteAttributedText(_ sender: Any) {
    let timeBeforeAction = Date.init()
    print ("Time taken to overwrite attributed text is ")
    for _ in 1 ... 100000{
        label.attributedText = getAttributedString()
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

//overwrites attributed text 100000 times with a cached string
@IBAction func overwriteAttributedTextWithCachedString(_ sender: Any) {
    let timeBeforeAction = Date.init()
    let attributedString = getAttributedString()
    print ("Time taken to overwrite attributed text with cached string is ")
    for _ in 1 ... 100000{
        label.attributedText = attributedString
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

//overwrites text 100000 times
@IBAction func overWriteText(_ sender: Any) {
    let defaultText = "Hello World"
    let timeBeforeAction = Date.init()
    print ("Time taken to overwrite text is ")
    for _ in 1 ... 100000{
        label.text = defaultText
    }
    let timeAfterAction = Date.init()
    let timeTaken = timeAfterAction.timeIntervalSince(timeBeforeAction)
    print(timeTaken)
}

Results:
Time taken to overwrite attributed text is
0.509455919265747
Time taken to overwrite attributed text with cached string is
0.0451710224151611
Time taken to overwrite text is
0.0634149312973022

On average, the .attributedText setter itself is about 30~40% faster than the .text setter.  That said, take note that it probably takes a lot of labels before this actually becomes a bottleneck.  Also remember that (if by some crazy circumstance) this is your bottleneck, this optimization is only effective if the attributed string is pre-allocated ahead of time.


Q: NVARCHAR to VARCHAR2 insert I have the following table structure:
UDA_ID (NUMBER)
Translation (NVARCHAR2)

I need to insert in the table
UDA_ID (NUMBER)
Translation (VARCHAR2)

How do i convert NVARCHAR2 to VARCHAR2 ?

A: You can try like this:
insert into mytable(Translation)
(select to_char(Translation) from sometable);

or like
insert into mytable(Translation)
(select to_char('yourValue') from dual);


Q: VB 6.0 debugging breakpoint doesn't hit I have a VB 6.0 Project having Class (cls) files. When I start (Debug) my project, and try to execute following statement in Classic ASP page,
Set objMyObject = Server.CreateObject("ProjName.ClassName")

No breakpoint is hit and following error occurs.

Microsoft VBScript runtime error '800a01ad'  ActiveX component can't
  create object

While if I use the same statement in another VB Project (test project) then breakpoint hits with no error.
Can anyone help ?

A: Well you are trying to create an instance of a COM object with the name  'ProjName.ClassName' - which is unlikely to be a real COM object.
Either your COM class needs to be one that has been registered in Windows, or it needs to be a class defined within your VB project.
The example in MSDN is:
 Sub CreateADODB()
    Dim adoApp As Object
    adoApp = CreateObject("ADODB.Connection")
End Sub

Where ADODB.Connection is a COM class that has been previously registered in Windows.  The code you have provided above is trying to instantiate a non existant class (unless it is already within the same VB project).
You say that the other project this works, then I will hazard a guess that the test project has a class called ClassName.
Ok -Updated.  The error code is not 'DLL Missing' - It is likely to be some reason why the COM object could not be instantiated.  The following Microsoft support page suggests some reasons and ways of tracking down the problem.  Its likely to be some sort of missing dependency to the DLL.
http://support.microsoft.com/kb/194801


Q: Line Chart (Currency) I'm trying to develop a line chart using a third-party API and I'm using both react-chartjs-2 and chart.js
The problem is, the line doesn't appear in the chart and I assume the reason is: the date. This is my first time to develop a web application using Chart.js. Also, I read the documentations and couldn't find a solution.
dateDate which is an array that contains all dates. The Array has dates inside of it, not objects.
I console.log'd the date in using the map loop and it worked, but it doesn't appear in the chart. I don't know the reason behind it.
Here is the console.log:
2023-01-10 App.jsx:66 2023-01-11 App.jsx:66 2023-01-12 App.jsx:66 2023-01-13 App.jsx:66 2023-01-14 App.jsx:66 2023-01-15 App.jsx:66 2023-01-16 App.jsx:66 2023-01-17 App.jsx:66 2023-01-18 App.jsx:66 2023-01-19 App.jsx:66 2023-01-20 App.jsx:66 2023-01-21 App.jsx:66 2023-01-22 App.jsx:66 2023-01-23
RESTful API
When you check the picture of the API, you'll find out that the date is the key and its value is an object of all costs. So, I have to separate them all.
Line Chart
function App() {
  const [euroCurrencyData, setEuroCurrencyData] = useState([]);
  const [dateData, setDateData] = useState([]);
  const [candianCurrencyData, setCandianCurrencyData] = useState([]);

  // CHART DATA
  const [chartData, setChartData] = useState({
    labels: dateData.map((date) => date),
    datasets: [
      {
        label: "EUR",
        data: euroCurrencyData.map((currency) => currency.EUR),
        backgroundColor: ["red", "green", "blue", "black"],
      },
      {
        label: "CAD",
        data: candianCurrencyData.map((currency) => currency.CAD),
        backgroundColor: ["green", "blue", "yellow", "green"],
      },
    ],
  });

  // EURO FETCH

  const getEuroData = async () => {
    const res = await axios.get(
      "https://api.freecurrencyapi.com/v1/historical?apikey=fGfh2W2M2jvc4drZkLCdOUhJSvQqRn0ZONHPWvTq&currencies=EUR&date_from=2022-12-23T07%3A50%3A10.865Z&date_to=2023-01-23T07%3A50%3A10.866Z"
    );

    const data = res.data.data;
    const euroCurrency = Object.values(data);
    const currencyDate = Object.keys(data);

    setEuroCurrencyData(euroCurrency);

    setDateData(currencyDate);
  };

  // CANDIAN FETCH

  const getCandianData = async () => {
    const res = await axios.get(
      "https://api.freecurrencyapi.com/v1/historical?apikey=fGfh2W2M2jvc4drZkLCdOUhJSvQqRn0ZONHPWvTq&currencies=CAD&date_from=2022-12-23T13%3A05%3A35.472Z&date_to=2023-01-23T13%3A05%3A35.473Z"
    );

    const data = res.data.data;
    const candianCurrency = Object.values(data);

    setCandianCurrencyData(candianCurrency);
  };

  useEffect(() => {
    getEuroData();
    getCandianData();
  }, []);

  return (

        <LineChart chartData={chartData} />

  );
}

import { Line } from "react-chartjs-2";
import { Chart as ChartJS } from "chart.js";
import Chart from "chart.js/auto";
const LineChart = ({ chartData }) => {
  return <Line data={chartData} />;

};


Q: gperftools: modify makefile to install in a different folder? I was installing  gperftools:
https://code.google.com/p/gperftools/
Everything worked, and I see that the project links to /usr/local/lib
I'd like to put the library in a folder local to my project, instead.
The reasoning behind this is that I'm putting the project on different machines, and I just need to link against the libprofiler and libtcmalloc libraries, instead of the entire package, that also comes with the pprof and such.
The machines also have different architectures, so I actually need to build into that directory, instead of copy-pasting over
Is this a trivial thing to do?

A: gperftools uses autoconf/automake, so you can do
./configure --prefix=/path/to/whereever
make
make install

This works for all autotools projects, unless they are severely broken.
On that note, it is generally a good idea to read the INSTALL file in a source tree to find out about this sort of stuff. There is one in the gperftools sources, and this is documented there.


Q: Microsoft.EntityFrameworkCore dont have method IsOptional() for PropertyBuilder I try transfer my solution from .Net Framowork to .Net Core.When I did mapping and I dint found method IsOptional() for PropertyBuilder:
.Net Framowork:
    public class PictureMap : EntityTypeConfiguration<PictureExt>
{
    public PictureMap()
    {
        this.ToTable("Picture");
        this.HasKey(p => p.Id);
        this.Property(p => p.SeoFilename).HasMaxLength(300);
        this.Property(p => p.ExternalUrl).IsOptional();
    }
}

and its work , but use EntityFrameworkCore:look in image
where I might found IsOptional()?

A: There is not IsOptional in EntityFrameworkCore but there is IsRequired to do the oposite. By default field are nullable if the C# type is nullable.

A: You can achieve the same effect with IsRequired(false).  This will override annotations like [Required] so be careful.  On another thread, it was pointed out that annotations that affect EF models or make no sense [Display...] should not be part of the EF model.  Move them to a ViewModel or DTO object.