text:
Q: flutter, The index value I asked to remove is different from the index value that was actually deleted at List import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(body: Center(child: TestWidget())));
  }
}

class MovableItem extends StatefulWidget {
  final int removeIndex;
  final double xInit;
  final double yInit;

  MovableItem({
    @required this.removeIndex,
    @required this.xInit,
    @required this.yInit,
  });

  @override
  State<StatefulWidget> createState() {
    return _MovableItemState();
  }
}

class _MovableItemState extends State<MovableItem> {
  double xPosition = 0;
  double yPosition = 0;

  double _height = 150;
  double _width = 150;

  @override
  void initState() {
    super.initState();
    xPosition = widget.xInit;
    yPosition = widget.yInit;

    print(widget.removeIndex);
  }

  @override
  Widget build(BuildContext context) {

    return Positioned(
      top: yPosition,
      left: xPosition,
      child: GestureDetector(
        onPanUpdate: (DragUpdateDetails tapInfo) {
          setState(() {
            xPosition += tapInfo.delta.dx;
            yPosition += tapInfo.delta.dy;
          });
        },
        child: Row(
          children: <Widget>[
            GestureDetector(
                child: Container(height: _height, width: _width, child: Text(widget.removeIndex.toString()))
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();

    print(widget.removeIndex);
  }
}

class TestWidget extends StatefulWidget {
  TestWidgetState createState() => TestWidgetState();
}

class TestWidgetState extends State<TestWidget> {

  List<Widget> _stack = [];

  @override
  void initState() {
    super.initState();
    _stack.add(MovableItem(removeIndex: 0, xInit: 0, yInit:  0,));
    _stack.add(MovableItem(removeIndex: 1, xInit: 20, yInit: 20,));
  }

  void onChangedFunction(int removeIndex) {
    setState(() {
      _stack.removeAt(removeIndex);
    });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Column(
          children: <Widget>[
            RaisedButton(
              child: Text("remove 0 index"),
              onPressed: () {
              setState(() {
                _stack.removeAt(0);
              });

            },),
            SizedBox(
              width: 500,
              height: 500,
              child: Stack(
                children: _stack,
              ),
            ),
          ],
        ));
  }
}

When onPressed in RaisedButton, I hope removed zero index to _stack. but actually first index is deleted.
when onPressed is called, I get the following printing result.
1

I expected to print zero. how can I remove zero index in _stack variable?
in another code, first index is removed on _stack variable in this code.
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(body: Center(child: TestWidget())));
  }
}

class TestWidget extends StatefulWidget {
  TestWidgetState createState() => TestWidgetState();
}

class TestWidgetState extends State<TestWidget> {

  List<Widget> _stack = [];

  @override
  void initState() {
    super.initState();

    _stack.add(Positioned(
      top: 0,
      left: 0,
      child: Text("0"),
    ));

    _stack.add(Positioned(
      top: 20,
      left: 20,
      child: Text("1"),
    ));
  }
  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Column(
          children: <Widget>[
            RaisedButton(
              child: Text("remove 0 index"),
              onPressed: () {
              setState(() {
                _stack.removeAt(0);
              });

            },),
            SizedBox(
              width: 500,
              height: 500,
              child: Stack(
                children: _stack,
              ),
            ),
          ],
        ));
  }
}

A: you need to add a key value to your widgets
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(body: Center(child: TestWidget())));
  }
}

class MovableItem extends StatefulWidget {
  final int removeIndex;
  final double xInit;
  final double yInit;

  MovableItem({
    Key key,
    @required this.removeIndex,
    @required this.xInit,
    @required this.yInit,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _MovableItemState();
  }
}

class _MovableItemState extends State<MovableItem> {
  double xPosition = 0;
  double yPosition = 0;

  double _height = 150;
  double _width = 150;

  @override
  void initState() {
    super.initState();
    xPosition = widget.xInit;
    yPosition = widget.yInit;

    print('created: ${widget.removeIndex} with key ${widget.key}');
  }

  @override
  Widget build(BuildContext context) {

    return Positioned(
      top: yPosition,
      left: xPosition,
      child: GestureDetector(
        onPanUpdate: (DragUpdateDetails tapInfo) {
          setState(() {
            xPosition += tapInfo.delta.dx;
            yPosition += tapInfo.delta.dy;
          });
        },
        child: Row(
          children: <Widget>[
            GestureDetector(
                child: Container(height: _height, width: _width, child: Text(widget.removeIndex.toString()))
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    print('disposed: ${widget.removeIndex} with key ${widget.key}');
  }
}

class TestWidget extends StatefulWidget {
  TestWidgetState createState() => TestWidgetState();
}

class TestWidgetState extends State<TestWidget> {

  List<Widget> _stack = [];

  @override
  void initState() {
    super.initState();
    _stack.add(MovableItem(key: Key('0'), removeIndex: 0, xInit: 0, yInit:  0,));
    _stack.add(MovableItem(key: Key('1'), removeIndex: 1, xInit: 20, yInit: 20,));
  }

  void onChangedFunction(int removeIndex) {
    setState(() {
      _stack.removeAt(removeIndex);
    });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Column(
          children: <Widget>[
            RaisedButton(
              child: Text("remove 0 index"),
              onPressed: () {
              setState(() {
                _stack.removeAt(0);
              });

            },),
            SizedBox(
              width: 500,
              height: 500,
              child: Stack(
                children: _stack,
              ),
            ),
          ],
        ));
  }
}

the console output will be
created: 0 with key [<0>]
created: 1 with key [<1>]
disposed: 0 with key [<0>]

Why does this happen? When you setState and delete the wiget at index 0 the build method rebuilds itself and _stack is not the same object anymore, it check that the list now has a different length and delete the last objects (the ones outside of the new length). If this is undesirable you should add a key to your widgets so when they rebuild the state knows which one to delete based on the key value.
You can check also this code where I change the print values so you see what happens when you setState and delete the indexAt(0). didUpdateWidget changes and print the differences between the oldwiget and the new one be rebuilt
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: Scaffold(body: Center(child: TestWidget())));
  }
}

class MovableItem extends StatefulWidget {
  final int removeIndex;
  final double xInit;
  final double yInit;

  MovableItem({
    @required this.removeIndex,
    @required this.xInit,
    @required this.yInit,
  });

  @override
  State<StatefulWidget> createState() {
    return _MovableItemState();
  }
}

class _MovableItemState extends State<MovableItem> {
  double xPosition = 0;
  double yPosition = 0;

  double _height = 150;
  double _width = 150;

  @override
  void initState() {
    super.initState();
    xPosition = widget.xInit;
    yPosition = widget.yInit;

    print('created: ${widget.removeIndex}');
  }

  @override
  void didUpdateWidget(MovableItem oldWidget){
    print('updated: oldWidget ${oldWidget.removeIndex} vs newWidget ${widget.removeIndex}');
    super.didUpdateWidget(oldWidget);
  }

  @override
  Widget build(BuildContext context) {

    return Positioned(
      top: yPosition,
      left: xPosition,
      child: GestureDetector(
        onPanUpdate: (DragUpdateDetails tapInfo) {
          setState(() {
            xPosition += tapInfo.delta.dx;
            yPosition += tapInfo.delta.dy;
          });
        },
        child: Row(
          children: <Widget>[
            GestureDetector(
                child: Container(height: _height, width: _width, child: Text(widget.removeIndex.toString()))
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();

    print('disposed: ${widget.removeIndex}');
  }
}

class TestWidget extends StatefulWidget {
  TestWidgetState createState() => TestWidgetState();
}

class TestWidgetState extends State<TestWidget> {

  List<Widget> _stack = [];

  @override
  void initState() {
    super.initState();
    _stack.add(MovableItem(removeIndex: 0, xInit: 0, yInit:  0,));
    _stack.add(MovableItem(removeIndex: 1, xInit: 20, yInit: 20,));
  }

  void onChangedFunction(int removeIndex) {
    setState(() {
      _stack.removeAt(removeIndex);
    });
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Column(
          children: <Widget>[
            RaisedButton(
              child: Text("remove 0 index"),
              onPressed: () {
              setState(() {
                _stack.removeAt(0);
              });

            },),
            SizedBox(
              width: 500,
              height: 500,
              child: Stack(
                children: _stack,
              ),
            ),
          ],
        ));
  }
}

The console output
created: 0
created: 1
updated: oldWidget 0 vs newWidget 1
disposed: 1

Without a key the 2 objects are created 0 and 1. Then I deleted the one at index 0 and rebuilt the parent, the children update and now (without a key) the widget at index 0 is the only widget and its value updates from 0 to 1 and the one at index 1 doesn't exist anymore (because your list now has a length of 1) so is disposed.
EDIT:
Also if you want to update all local parameters (xPosition and yPosition) without using keys you should do it inside the didUpdateWidget method
@override
  void didUpdateWidget(MovableItem oldWidget){
    print('updated: oldWidget ${oldWidget.removeIndex} vs newWidget ${widget.removeIndex}');
    xPosition = widget.xInit;
    yPosition = widget.yInit;
    super.didUpdateWidget(oldWidget);
  }

that way the positions will update when you delete one of the widgets from the list (if you don't want to use keys)


text:
Q: React and Emotion: Specify font size I am using emotion to style and display the equation for compound interest in my React app. My render() returns this:

  P (1 +

    1
    /
    2

  )
   (nt)

And outside of my component I have:
const fraction = css`
    display: inline-block;
    position: relative;
    vertical-align: middle;
    letter-spacing: 0.0001em;
    text-align: center;

    .num {
      display: block;
      padding: 0;
      height: 12px;
      line-height: 12px;
    }

    .bottom {
      border-top: thin solid black;
    }

    .symbol {
      display: none;
    }
`
const equation = css`
font-size: 100%;
.p{
    font-size:large !important;
  }
`;

The fraction is correctly styled. However, I cannot get the font of the p elements to change. The only way I got it to was by switching the p to h1 elements - but I don't want to do that. I want to be able to specify the font size inside my emotion css styling.

A: There are a couple of things I noticed as an issue in your code.

*

*You are passing .p { ... inside the equation which is not a class selector but should have been an element selector like p { ...

*Your react div has to use a className in order to make that effect applied

Here is the sandbox code changes: https://codesandbox.io/s/emotion-xh53z?fontsize=14
Just copying here for your reference:
import React from "react";
import { render } from "react-dom";
import { css } from "react-emotion";

const fraction = css`
  display: inline-block;
  position: relative;
  vertical-align: middle;
  letter-spacing: 0.0001em;
  text-align: center;
  .num {
    display: block;
    padding: 0;
    height: 30px;
    line-height: 12px;
  }
  .bottom {
    border-top: thin solid black;
  }
  .symbol {
    display: none;
  }
`;

 // Notice the p inside the equation
const equation = css`
  p {
    font-size: large !important;
  }
`;

// Rather than css={}, you should be using className={}
const App = () => (

      P (1 +

        1
        /
        2

      )(nt)

);

render(<App />, document.getElementById("root"));

I also moved the closing
 tag at the last to ensure it's getting applied as per inline-block
Updated 1:
Here is the latest updated version: https://codesandbox.io/s/emotion-1tjc7
As per their latest blog you should be using:
import styled from '@emotion/styled'
import { css } from 'emotion'

instead of import styled, { css } from 'react-emotion'
Update 2:
In case you cannot use vanilla emotion, then you can consider using the following:
import styled from "@emotion/styled";
/** @jsx jsx */
import { css, jsx } from "@emotion/core";

According to their documentation:
There are 2 ways to get started with the css prop.

*

*Babel Preset (Can't use in Create-React-App or CodeSandbox)

*JSX Pragma (This involves to just add the above to lines of code)

I have updated the same codesandbox: https://codesandbox.io/s/emotion-0z3vz

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can a docker image use executable from the host? I have several Java services, each packaged as a separate jar file. I plan to package the as docker images. Do I need to bundle the Java runtime on each image, or can I rely on the fact the host (that will run the image) already has the Java runtime?

A: You could use a volume to mount the Java runtime from the host into the container, but this makes the container less portable (as Andrew Fox points out).
If instead you use a common base image such as java:8-jre for your containers, the image will be shared between containers meaning that there is only one copy on disk (not one copy per container).
Not that in both cases, you will still have multiple JVMs running, one for each container.

A: The idea of docker is to make your setup portable so if you don't put in the Java runtime you can't guarantee it will work properly on a destination system. I don't believe docker can access host executables unless there is a special whitelist setting somewhere but in my experience no it can't.


text:
Q: codeigniter login validation not validating rules am using  codeigniter 3.0.4 .here this Here the action send to the controler(first.php)not validating anything it will turn to else statement and display login page again(as set as in redirect('welcome/login_page');). my register function in the same controller working good. what is the exact problem ..please help me to find it.thanks.
..............the controller(first.php).....
public function signup_validation(){
        $this->load->library('form_validation');

$this->form_validation->set_rules('email', 'Email',       'required|trim|xss_clean|valid_email|callback_validate_credentials');
$this->form_validation->set_rules('password', 'Password', 'required|md5|trim');

 if($this->form_validation->run() ){

$user_id= $this->model_users->get_id($this->input->post('email'));
$user_status = $this->model_users->get_status($this->input->post('email'));

$data = array (
      'user_id' => $user_id,
        'email' => $this->input->post('email'),
        'user_status' =>$user_status,
        'is_logged_in' => 1
    );

 $this->session->set_userdata($data);
}
      if ($this->session->userdata('user_status')=='0') {
    redirect('main/admins');
  }
  elseif ($this->session->userdata('user_status')=='1') {
    redirect('main/members');
  }else{

        redirect('welcome/login_page');
      }

 }

public function  validate_credentials(){

$this->load->model('model_users');

    if($this->model_users->can_log_in() ){

 return TRUE;
 } else {
$this->form_validation->set_message('validate_credentials', 'Invalid useername(email-id) or password. !');
return FALSE;
 }

}
....the view(login.php)......

                       echo form_open("first/signup_validation");
                   echo'
';
                echo'
';
                echo'Email';
                echo'<input type="text" class="form-control" id="email">';
                                        echo'
';
            echo'
';
            echo'Password';
        echo'<input type="password" class="form-control" id="password">';
                                        echo'
';
                                    echo'
';

                                    $data2 = array(

                                        'class'       => 'btn btn-default',
                                    );

                                         echo form_submit($data2, 'Login');

                                 echo form_close('');
        ?>

A: echo '<input type="text" class="form-control" id="email">';

Your input elements don't contain a name attribute.  The name is what's used as the identifier in the validation rule.
$this->form_validation->set_rules('email'... // <- 'email' is the name attribute

Do this...
echo'<input type="text" class="form-control" id="email" name="email">';


text:
Q: How to Remove Known Password from Secondary Hard Drive Not Appearing in BIOS I have a Dell Inspiron 7567 laptop with two hard drives. I added password protection using the Dell BIOS to both hard drives. Once I added password protection, both hard drives worked well, and I could see and interact with all the files on both.
Unfortunately, I discovered that upon a restart, the second hard drive did not appear in Windows Explorer, or even as a partition in Disk Management. Windows cannot see it at all.
However, if during the boot-up I enter the BIOS, after leaving the BIOS, I am presented with a BIOS pop-up window that says "Hard-Drive #XXXXX, the system internal HDD-1, is protected by a password authentication system. You cannot access data on this hard drive without the correct password. Please type in the hard drive password." When I enter the correct password, I can see the second hard drive without issue. However, as soon as I put the computer to Sleep, Hibernate, or Restart (without entering the BIOS), the second hard drive disappears, and Windows cannot see it. The only way to see the 2nd hard drive in Windows 10 is to ensure that you enter the BIOS before booting Windows.
I have since done some research, and realised that the Dell hard drive passwords are not very secure, and that disk encryption is better (using Bitlocker or Veracrypt). I entered the BIOS, and found the setting for the primary hard drive password, and removed it. However, while the secondary hard drive appears in the basic BIOS, it is missing from the Dell Advanced BIOS where password protection is added or removed. I have spent hours searching for how to turn off the password for the second hard drive (in the BIOS settings, and online solutions), but I cannot figure out how to remove the password from the second hard drive. I cannot get the second hard drive to appear in the Dell Advance BIOS ("advanced", because you can navigate with a mouse).

A: I did the following (based on a suggestion from Dell's "jphugan"):

*

*Temporarily remove your primary drive (physically from the motherboard) so that the secondary drive becomes the only one in the system.

*The BIOS then should show the secondary hard drive

*Remove the password from the secondary hard drive

*Reinsert the primary hard drive. Both should now show up in the BIOS.
The fact that the secondary hard drive no longer appears in the BIOS when a password is applied is probably a bug in the F1.9 BIOS firmware.


text:
Q: Name of 4-conductor twinned headphone wire I would like to get more serious about repairing headphones, as well as making my own extension cords ( as the ones you can buy tend to be pretty low quality, and I am tired of breaking).
The kind of cable I am looking for was the primary kind of cable used for headphones a while ago. [1] It is composed of four conductors. Sheathed in the insulation in pairs, with pairs of insulation bonded. You can split the insulation down the middle and and have two pairs of insulted wired ( each pair having two conductors )go to each speaker separately.
What is this cable called? ( A link to some such cable would be useful. )
[1] It seems that modern headphones mostly use three conductor cable. Or it seems that way to me. Possibly because I use behind the neck type headphones.

A: Wow, I thought that would be an easy search. Then it wasn't. Then I was really curious.
Looks like the cable you are referring to is called Dual-Pair Zip-Cord From wikipedia, zip cord:

refers to two or more electrical conductors held together by an insulating jacket that can be easily separated simply by pulling apart.

Searching "double-pair" or "dual-pair" seems to bring up the cable you are referring to. Belden comes up a lot as the manufacturer.
Example catalog (ctrl-f "zip"):
http://www.belden.com/products/catalogs/mastercatalog/brilliance/upload/19Broadcast_Cables.pdf
An example of a store listing:
http://www.interstatewire.com/double-pair-cable-1802b-z4b1000.html
Though a lot of the examples I'm seeing are shielded, twisted pairs. I'm not sure where the cheap, old headphone cables are hiding. You may want to invest in a bunch of heat shrink and a good heat gun for your uneven lengths.

A: Years ago I used to use a cable similar to what you are describing.  We called it Microphone cable and it had a rubber EPDM outer jacket.  The individual conductors were also insulated with Rubber EPDM and the individual conductors were bonded to each other as you describe.
The closest I could come in a search has Polyethylene insulation: http://www.alliedelec.com/search/productdetail.aspx?SKU=70005399
To get a list of selections, go onto any electronic supply website and search for Microphone or Musical Instrument cable.

A: I do not have a source of that twin-ZIP cord in bulk format but I can tell you where to get it.
I regularly repair professional headphones.  AKG is one supplier who makes dual-ear headphones used in broadcast and recording.  The cords for the headphones is a wear item and replacements are readily available.
Same for most other suppliers of professional headphones / headsets.  Sennheiser, Sony, Beyer-Dynamic, AKG are some of the headphones that I work with regularly.  Wear items are readily available as replacement parts.
Although these replacement parts may cost more than other sources, the headset wire is designed for continuous, heavy-duty use and it lasts a long time.  Much better quality than inexpensive consumer stuff.


text:
Q: RegEx No more than 2 identical consecutive characters and a-Z and 0-9 Edit: Thanks for the advice to make my question clearer :)
The Match is looking for 3 consecutive characters:
Regex Match =AaA653219
Regex Match = AA5556219
The code is ASP.NET 4.0. Here is the whole function:
public ValidationResult ApplyValidationRules()
{
    ValidationResult result = new ValidationResult();
    Regex regEx = new Regex(@"^(?=.*\d)(?=.*[a-zA-Z]).{8,20}$");

    bool valid = regEx.IsMatch(_Password);
    if (!valid)
        result.Errors.Add("Passwords must be 8-20 characters in length, contain at least one alpha character and one numeric character");

    return result;
}

I've tried for over 3 hours to make this work, referencing the below with no luck =/
How can I find repeated characters with a regex in Java?
.net Regex for more than 2 consecutive letters
I have started with this for 8-20 characters a-Z 0-9 :
^(?=.*\d)(?=.*[a-zA-Z]).{8,20}$

As Regex regEx = new Regex(@"^(?=.*\d)(?=.*[a-zA-Z]).{8,20}$");

I've tried adding variations of the below with no luck:
/(.)\1{9,}/
.*([0-9A-Za-z])\\1+.*
((\\w)\\2+)+".

Any help would be much appreciated!

A: http://regexr.com?34vo9
The regular expression:
^(?=.{8,20}$)(([a-z0-9])\2?(?!\2))+$

The first lookahead ((?=.{8,20}$)) checks the length of your string.  The second portion does your double character and validity checking by:
(
  ([a-z0-9])      Matching a character and storing it in a back reference.
  \2?             Optionally match one more EXACT COPY of that character.
  (?!\2)          Make sure the upcoming character is NOT the same character.
)+                Do this ad nauseum.
$                 End of string.

Okay.  I see you've added some additional requirements.  My basic forumla still works, but we have to give you more of a step by step approach.  SO:
^...$

Your whole regular expression will be dropped into start and end characters, for obvious reasons.
(?=.{n,m}$)

Length checking.  Put this at the beginning of your regular expression with n as your minimum length and m as your maximum length.
(?=(?:[^REQ]*[REQ]){n,m})

Required characters.  Place this at the beginning of your regular expression with REQ as your required character to require N to M of your character.  YOu may drop the (?: ..){n,m} to require just one of that character.
(?:([VALID])\1?(?!\1))+

The rest of your expression.  Replace VALID with your valid Characters.  So, your Password Regex is:
^(?=.{8,20}$)(?=[^A-Za-z]*[A-Za-z])(?=[^0-9]*[0-9])(?:([\w\d*?!:;])\1?(?!\1))+$

'Splained:
^
  (?=.{8,20}$)                 8 to 20 characters
  (?=[^A-Za-z]*[A-Za-z])       At least one Alpha
  (?=[^0-9]*[0-9])             At least one Numeric
  (?:([\w\d*?!:;])\1?(?!\1))+  Valid Characters, not repeated thrice.
$

http://regexr.com?34vol  Here's the new one in action.

A: Tightened up matching criteria as it was too broad; for example, "not A-Za-z" matches a lot more than is intended.  The previous REGEX was matching on the string "ThiIsNot". For the most part, passwords are only going to contain alphanumeric and punctation characters, so I limited the scope, which made all matches more accurate.  Used character classes for human readability.  Added and exclusion list, and differentiated upper and lower case letters.
^(?=.{8,20}$)(?!(?:.*[01IiLlOo]))(?=(?:[\[[:digit:]\]\[[:punct:]\]]*[\[[:alpha:]\]]){2})(?=(?:[\[[:digit:]\]\[[:punct:]\]\[[:upper:]\]]*[\[[:lower:]\]]){1})(?=(?:[\[[:digit:]\]\[[:punct:]\]\[[:lower:]\]]*[\[[:upper:]\]]){1})(?=(?:[\[[:alpha:]\]\[[:punct:]\]]*[\[[:digit:]\]]){1})(?=(?:[\[[:alnum:]\]]*[\[[:punct:]\]]){1})(?:([\[[:alnum:]\]\[[:punct:]\]])\1?(?!\1))+$

The breakdown:
^(?=.{8,20}$) - Positive lookahead that the string is between 8 and 20 chars
(?!(?:.*[01IiLlOo])) - Negative lookahead for any blacklisted chars
(?=(?:[\[[:digit:]\]\[[:punct:]\]]*[\[[:alpha:]\]]){2}) - Verify that at least 2 alpha chars exist
(?=(?:[\[[:digit:]\]\[[:punct:]\]\[[:upper:]\]]*[\[[:lower:]\]]){1}) - Verify that at least 1 lowercase alpha exists
(?=(?:[\[[:digit:]\]\[[:punct:]\]\[[:lower:]\]]*[\[[:upper:]\]]){1}) - Verify that at least 1 uppercase alpha exists
(?=(?:[\[[:alpha:]\]\[[:punct:]\]]*[\[[:digit:]\]]){1}) - Verify that at least 1 digit exists
(?=(?:[\[[:alnum:]\]]*[\[[:punct:]\]]){1}) - Verify that at least 1 special/punctuation char exists
(?:([\[[:alnum:]\]\[[:punct:]\]])\1?(?!\1))+$ - Verify that no char is repeated more than twice in a row


text:
Q: Check Recyclerview empty or not with Firebase Realtime Database I have made a Recyclerview in fragment with firebase realtime database and I want check the recyclerview is empty or not how can I access bookadapter.itemcount in fun Datasnapshot of addValueEventlistner
and have also added some condition in adapter to remove some item in Recyclerview but unable to check recyclerview is empty or not so,please solve my problem.
Books.kt
 private fun showbooks() {
    databaseReference.addValueEventListener(object : ValueEventListener {
        @SuppressLint("NotifyDataSetChanged")
        override fun onDataChange(snapshot: DataSnapshot) {
            try {
                booklist.clear()
                for (item in snapshot.children) {
                    val bookid = item.child("BookId").value.toString()
                    val bookname = item.child("BookName").value.toString()
                    val bookpublication = item.child("BookPublication").value.toString()
                    val bookdept = item.child("Department").value.toString()
                    val bookimage = item.child("BookImage").value.toString()
                    val bookyear = item.child("BookYear").value.toString()
                    val userid = item.child("UserUID").value.toString()
                    val date = item.child("Date").value.toString()
                    RedeleteBook(date, bookimage, bookid)
                    booklist.add(
                        Booksmodel(
                            bookid,
                            bookimage,
                            bookname,
                            bookdept,
                            bookpublication,
                            bookyear,
                            userid,
                        )
                    )
                    bookadapter =
                        bookadapter(
                            booklist,
                            this@Books
                        )
                    bookadapter.notifyDataSetChanged()
                    bookrecyclerView.adapter =
                        bookadapter
                    bookprogressbar.visibility =
                        View.GONE

                }

            } catch (e: Exception) {
                Toast.makeText(context, e.message, Toast.LENGTH_SHORT).show()
                bookprogressbar.visibility = View.GONE
            }
        }

        override fun onCancelled(error: DatabaseError) {
            Toast.makeText(context, "please check connection", Toast.LENGTH_SHORT).show()
            bookprogressbar.visibility = View.GONE
        }
    })

bookadapter.kt
package com.bookqueen.bookqueen.adapter

class bookadapter(
private var booklist: ArrayList<Booksmodel>,
private val itemClickListener: OnBookItemClicklistner
) : RecyclerView.Adapter<bookadapter.bookholder>() {

var searchText: String = ""

override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): bookholder {
    val view = LayoutInflater.from(parent.context).inflate(R.layout.singlebook, parent, false)
    return bookholder(view)
}

@SuppressLint("NotifyDataSetChanged")
fun filterlist(filterlist: ArrayList<Booksmodel>, searchText: String) {
    booklist = filterlist
    this.searchText = searchText
    notifyDataSetChanged()

}

override fun onBindViewHolder(holder: bookholder, position: Int) {
    val view = booklist[position]

    holder.bind(view, itemClickListener)

}

override fun getItemCount(): Int {
    Log.d("Booksize",(booklist.size.toString()))
    return if (booklist.size == 0) 0 else booklist.size
}

inner class bookholder(view: View) : RecyclerView.ViewHolder(view) {
    val bookname: TextView = view.findViewById(R.id.recbooknametxt)
    val bookpublication = view.findViewById<TextView>(R.id.recbookpubtxt)
    val bookdept = view.findViewById<TextView>(R.id.recbookdepttxt)
    val bookimage = view.findViewById<ImageView>(R.id.recbookimg)
    val bookview = view.findViewById<CardView>(R.id.bookcardView)

    fun bind(book: Booksmodel, clicklistner: OnBookItemClicklistner) {

        val database = FirebaseDatabase.getInstance()
        val auth = FirebaseAuth.getInstance()
        Mycollege.college(object : Mycollege.Mycallback {
            override fun onCallback(value: String) {
                Log.d("Mycoolege", value)
                database.getReference("Users").child(book.UserUID.toString())
                    .addListenerForSingleValueEvent(object : ValueEventListener {
                        @SuppressLint("NotifyDataSetChanged")
                        override fun onDataChange(snapshot: DataSnapshot) {
                            if (snapshot.value != null) {
                                val usercollege = snapshot.child("College").value.toString()

                                if (usercollege == value) {

                                    if (searchText.isNotBlank()) {
                                        val highlightedText = book.BookName!!.replace(
                                            searchText,
                                            "$searchText",
                                            true
                                        )
                                        bookname.text =
                                            HtmlCompat.fromHtml(
                                                highlightedText,
                                                HtmlCompat.FROM_HTML_MODE_LEGACY
                                            )
                                    } else {
                                        bookname.text = book.BookName
                                    }
                                    //bookname.text=book.BookName
                                    bookpublication.text = book.BookPublication
                                    bookdept.text = book.Department
                                    Picasso.get().load(book.BookImage)
                                        .error(R.drawable.ic_action_book)
                                        .into(bookimage)
                                } else {
                                    booklist.remove(book)
                                    notifyDataSetChanged()

                                }

                            }
                        }

                        override fun onCancelled(error: DatabaseError) {

                        }
                    })
            }
        })

        itemView.setOnClickListener {
            clicklistner.onBookItemclick(book)
        }
    }

}

interface OnBookItemClicklistner {
    fun onBookItemclick(books: Booksmodel)
}

}


text:
Q: Extracting Data from a .txt file using python I many, many .xml files and i need to extract some co-ordinates from them.
Extracting data straight from .xml files seems to be very, very complicated - so i am working saving the .xml files as .txt files and extracting the data that way. However, when i open the .txt file, my data is all bunched together on about 6 lines.. And all the scripts i have found so far select the data by reading the first word on each line.. but obviously that won't work for me!
I need to extract the numbers inbetween these comments:
<gml:lowerCorner>137796 483752</gml:lowerCorner> <gml:upperCorner>138178 484222</gml:upperCorner>

In the text file they are all grouped together! Does anyone know how to extract this data? Thank you!

A: This is absolutely the wrong approach. Leave it alone and improve your ways :-)
Seriously, if the file is XML, then just use an XML parser to read it. Learning how to do it in Python isn't hard and will make your life easier now and much easier in the future, when you may find yourself facing more complex parsing needs, and you won't have to re-learn it.
Look at xml.etree.ElementTree.ElementTree. Here's some sample code:
>>> from xml.etree.ElementTree import ElementTree
>>> tree = ElementTree()
>>> tree.parse("your_xml_file.xml")

Now just read the documentation of the module and see what you can do with tree. You'll be surprised to find out how simple it is to get to information this way. If you have specific questions about extracting data, I suggest you open another question in which you specify the format of the XML file you have to parse, and what data you have to take out of there. I'm sure you will have working code suggested to you in matters of minutes.

A: You can also open through the python script .xml file as you open a .txt file.
    data = open("file.xml")
    xml = data.read()

Then you can use regular expressions to find those numbers you want so badly.

A: The top answer is still the top answer.  However, I've been doing just this with HTML and this link lxml and xpath ideal.
Open your browser to the site (or data) which is of interest.  In Chrome, right click and 'Inspect Element'.  In the Developer window on the highlighted text right click again and 'Copy XPath'.  For google.com and clicking on the main search box I get the following XPath.
//*[@id="lst-ib"]

You can use lxml to grab various data from this item.  See what you get when you append 'text()' or '@value' or '@href' on the end.

A: For really simple xml i just use a regex, can't be botherd to start an slow xml parser for a simple xml packet.

In [1]: data = open("file.txt","r").read()

In [2]: import re

In [3]: re.compile("([\d]+)").findall(data)
Out[3]: ['137796', '483752', '138178', '484222']


text:
Q: JAXB: Unmarshaller tries to instantiate abstract class (ignoring xsi:type) I struggle with a strange problem since several days. A customer provides a Webservice
and a WSDL. I imported the WSDL by using wsimport and some jaxb customization. All Java
classes are generated without any error.
When I use the Java classes to unmarshall a response I got the following exception:
06.02.2012 09:18:50 com.sun.xml.bind.v2.ClassFactory create
INFO: failed to create a new instance of class net.bipro.v2_1_0_1_0.namespace.datentypen.STEGefahr
java.lang.InstantiationException
    at sun.reflect.InstantiationExceptionConstructorAccessorImpl.newInstance(InstantiationExceptionConstructorAccessorImpl.java:30)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    at com.sun.xml.bind.v2.ClassFactory.create0(ClassFactory.java:122)
    at com.sun.xml.bind.v2.ClassFactory.create(ClassFactory.java:131)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.createInstance(UnmarshallingContext.java:609)
    at com.sun.xml.bind.v2.model.impl.RuntimeClassInfoImpl$TransducerImpl.parse(RuntimeClassInfoImpl.java:392)
    at com.sun.xml.bind.v2.runtime.unmarshaller.TextLoader.text(TextLoader.java:69)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallingContext.text(UnmarshallingContext.java:514)
    at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.processText(SAXConnector.java:181)
    at com.sun.xml.bind.v2.runtime.unmarshaller.SAXConnector.endElement(SAXConnector.java:154)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.endElement(AbstractSAXParser.java:601)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanEndElement(XMLDocumentFragmentScannerImpl.java:1782)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:2939)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:648)
    at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:140)
    at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:511)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:808)
    at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:737)
    at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:119)
    at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1205)
    at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:522)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:217)
    at com.sun.xml.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:189)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:137)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:142)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:151)
    at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:169)
    at de.company.bipro.tarifierung.TestApp.<init>(TestApp.java:39)
    at de.company.bipro.tarifierung.TestApp.main(TestApp.java:143)

I reduced the response object to a minimal valid xml:
<taa:getQuoteResponse
    xmlns:taa="http://www.bipro.net/namespace/tarifierung"
    xmlns:leben="http://www.bipro.net/namespace/leben"
    xmlns:sachen="http://www.bipro.net/namespace/sachen"
    xmlns:haftpflicht="http://www.bipro.net/namespace/haftpflicht"
    xmlns:fahrzeug="http://www.bipro.net/namespace/fahrzeug"
    xmlns:xyzkfz="http://www.xyz.de/kfz/namespace"
    xmlns:xyz-komposit="http://www.xyz.de/komposit/namespace"
    xmlns:sach="http://www.bipro.net/namespace/sach"
    xmlns:xyzleben="http://www.xyz.de/leben/namespace"
    xmlns:xyz="http://www.xyz.de/namespace"
    xmlns:partner="http://www.bipro.net/namespace/partner"
    xmlns:mime="http://www.w3.org/2005/05/xmlmime"
    xmlns:komposit="http://www.bipro.net/namespace/komposit"
    xmlns:kfz="http://www.bipro.net/namespace/kraftfahrt"
    xmlns:allgemein="http://www.bipro.net/namespace/allgemein">
  <taa:Response>
    <taa:Tarifierung>
      <taa:Verkaufsprodukt>
        <taa:Produkt xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="komposit:CT_SUHVersicherung">
          <taa:Elementarprodukt xsi:type="komposit:CT_Deckung">
            <komposit:Gefahr xmlns:daten="http://www.bipro.net/namespace/datentypen" xsi:type="daten:STE_GefahrBasis">L</komposit:Gefahr>
          </taa:Elementarprodukt>
        </taa:Produkt>
      </taa:Verkaufsprodukt>
    </taa:Tarifierung>
  </taa:Response>
</taa:getQuoteResponse>

Here is the data type definition:
<xsd:complexType abstract="true" name="STE_Gefahr">
    <xsd:simpleContent>
        <xsd:extension base="xsd:string"/>
    </xsd:simpleContent>
</xsd:complexType>

<xsd:complexType final="#all" name="STE_GefahrBasis">
    <xsd:simpleContent>
        <xsd:restriction base="daten:STE_Gefahr">
            <xsd:enumeration value="F"><xsd:annotation><xsd:documentation>Feuer</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="L"><xsd:annotation><xsd:documentation>Leitungswasser</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="S"><xsd:annotation><xsd:documentation>Sturm</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="H"><xsd:annotation><xsd:documentation>Hagel</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="E"><xsd:annotation><xsd:documentation>Einbruchdiebstahl</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="G"><xsd:annotation><xsd:documentation>Glas</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="U"><xsd:annotation><xsd:documentation>Ueberspannungsschaeden</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="N"><xsd:annotation><xsd:documentation>Nutzfeuer</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="M"><xsd:annotation><xsd:documentation>Elementarschaeden (alle Gefahren)</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="B"><xsd:annotation><xsd:documentation>Beraubung</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="M01"><xsd:annotation><xsd:documentation>Ueberschwemmung</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="M02"><xsd:annotation><xsd:documentation>Erdbeben</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="M03"><xsd:annotation><xsd:documentation>Schneedruck</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="M04"><xsd:annotation><xsd:documentation>Erdrutsch</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="M05"><xsd:annotation><xsd:documentation>Vulkanausbruch</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="M06"><xsd:annotation><xsd:documentation>Lawine</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="M07"><xsd:annotation><xsd:documentation>Rueckstau</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="M08"><xsd:annotation><xsd:documentation>Erdsenkung</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="M09"><xsd:annotation><xsd:documentation>Starkregen</xsd:documentation></xsd:annotation></xsd:enumeration>
            <xsd:enumeration value="M99"><xsd:annotation><xsd:documentation>sonstige Elementarschaeden</xsd:documentation></xsd:annotation></xsd:enumeration>
        </xsd:restriction>
    </xsd:simpleContent>
</xsd:complexType>

I have no clue why the xsi:type is ignored. Especially because in other elements,
which also use subclasses it works fine.
I also replaced the default jaxb which comes with JDK with the current JAXBRI - still
the same error.
Does anyone have an idea what is wrong? I guess, I am already "blinded by the lines" :-/
Regards
MausFan

A: Your issue is the same as the one reported here. It is still manifesting itself with Java 1.6.0_27, which seems to correspond to jaxb-ri-2.2-147. However, if the same code is executed using Java 1.7.0_02 all works fine. This points to an issue with the version of JAXB that you're using so try switching to a new JAXB/JDK (in my case the successful test ran on NetBeans 7.1 w/ JDK 1.7.0_02).

A: You are in a better position than I. I am bound to Java 1.5 due to the application server. With this general condition there is still no solution, see
http://java.net/jira/browse/JAXB-890


text:
Q: How to apply Nested Mat-Table Grid to the third level in Angular? I have created a Mat-Table with nested grid with a nested json by a lot of research online and help . It has 2 grids for now . But now i have a requirement where i need an additional nested grid inside .
I tried to replicate what is done for the second level grid to generate the third level grid but the "ExpandedElements" array throws an error while generating the third level grid .
My updated JSON looks like -
{
name: 'Mason',
email: 'mason@test.com',
phone: '9864785214',
addresses: [
  {
    street: 'Street 1',
    zipCode: '78542',
    city: 'Kansas',
    comments: [
      {
        commenID: 1,
        comment: 'Test',
        commentStatus: 'Open'
      },
      {
        commenID: 2,
        comment: 'Test',
        commentStatus: 'Open'
      },{
        commenID: 3,
        comment: 'Test',
        commentStatus: 'Closed'
      },
    ]
  },

I want the comments to be an internal grid under address grid .
I have the 2 grids ready with the json in the stackblitz link -
https://stackblitz.com/edit/angular-nested-mat-table-sia2jn?file=app%2Ftable-expandable-rows-example.ts
Can anyone help me how to proceed with the third level of grid ?
Thanks

A: You could setup a similar variable for you nested comments on your addresses:
innerExpandedElements: any[] = [];

And then add another toggle function to manage that list:
toggleAddress(address) {
    const index = this.innerExpandedElements.findIndex(x => x === address);
    if (index === -1) {
      this.innerExpandedElements.push(address);
    } else {
      this.innerExpandedElements.splice(index, 1);
    }
  }

Then in your template display when those elements are in your array:
*ngIf="innerExpandedElements.includes(address)"

I made a quick example. It uses a ul and doesn't have animation but should conceptually work the same.
https://stackblitz.com/edit/angular-nested-mat-table-ynf8vb?file=app%2Ftable-expandable-rows-example.html


text:
Q: Two errors: unexpected EOF while looking for matching `'' and syntax error: unexpected end of file #include <iostream>
using namespace std;

int main()
{
   cout << "Hello World" << endl;
   return 0;
}

My current Ubuntu version is 17.10
I saved the above C++ program on my external hard disk and opened it with Sublime Text 2. The code compiles successfully but when I run it I get these two errors:
bash: -c: line 0: unexpected EOF while looking for matching `''
bash: -c: line 1: syntax error: unexpected end of file
[Finished in 0.0s with exit code 1]

The problem goes away if I save it and run it on anywhere other than my hard disk.
What's happening here?


text:
Q: Find item in object array with same property i have an array of objects like this:

Array
(
    [0] => stdClass Object
        (
            [date] => 12.09.2015
            [title] =>  Testtitle3
        )

    [1] => stdClass Object
        (
            [date] => 01.01.2015
            [title] =>  Testtitle3
        )

    [2] => stdClass Object
        (
            [date] => 12.09.2015
            [title] =>  Testtitle3
        )
}

now i wantr loop trough the arrays (with foreach) to check if a date is duplicated entry. If so put duplicates in new array to have a output like this (example with 12.09.2015 - cos this is a duplicate in my example array):
{12.09.2015 - title1:Testtitle3, title2:Testtitle3}
so basically the script should find duplicate dates in object array and echo them with both titles(same but dosent matter) and one date.
I tried something like this, but it doesnt work:
foreach($array as &$item){
    foreach($array as &$itemCheck){
    if($item->date === $itemCheck->date){
    echo '{' . $item->date . ' - ' .    $item->title . ',' . $itemCheck->title . '}';
    }
    }
}

im frustrated :) can u help me again guys? thx!!!

A: You should store the date in a variable
$temp = array();
foreach ($array as $item) {
    if (in_array($item->date, $temp)) {
       echo '{' . $item->date . ' - ' .    $item->title . ',' . $itemCheck->title . '}';
    } else {
        $temp[] = $item->date;
    }
}

A: foreach($array as $item){
    if (isset($helper){
        foreach($helper as $helperitem){
              if($item->date === $helperitem->date){
                 echo '{' . $item->date . ' - ' .    $item->title . ',' . $helperitem->title . '}';

              }
        }
    }
    $helper[]=$item;
}

A: You can collapse the array, and then you can check in a second loop.
$colapsedArray = array();
foreach($array as &$item){
    $colapsedArray[$item['date']][] = $item['title'];
} unset($item); //else you can have strange side effects in PHP

foreach($colapsedArray as &$item) {
   if (count($item) > 1) {
      //echo item
   }
} unset($item);

After collapsing the $collapsedArray should look like this:
Array
(
    [12.09.2015] => Array
        (
            'Testtitle3',
            'Testtitle3'
        )

    [01.01.2015] => Array
        (
            'Testtitle3'
        )
)


text:
Q: How to convert PDF file to XML Can any body tell me how to convert pdf file to xml file.
I want to store resume in xml file, i.e. if any user upload the resume in pdf file then it will convert in xml file and in xml file only store some basic detail like name, address, education detail, etc.
please give me answer

A: you have to read the PDF file using itextsharp
after that filter your required information and then create a xml file using XML


text:
Q: Aborting a linq query after finding x items? If I know there is only one matching item in a collection, is there any way to tell Linq about this so that it will abort the search when it finds it?
I am assuming that both of these search the full collection before returning one item?
var fred = _people.Where((p) => p.Name == "Fred").First();
var bill = _people.Where((p) => p.Name == "Bill").Take(1);

EDIT: People seem fixated on FirstOrDefault, or SingleOrDefault. These have nothing to do with my question. They simply provide a default value if the collection is empty. As I stated, I know that my collection has a single matching item.
AakashM's comment is of most interest to me. I would appear my assumption is wrong but I'm interested why.
For instance, when linq to objects is running the Where() function in my example code, how does it know that there are further operations on its return value?

A: Your assumption is wrong. LINQ uses deferred execution and lazy evaluation a lot. What this means is that, for example, when you call Where(), it doesn't actually iterate the collection. Only when you iterate the object it returns, will it iterate the original collection. And it will do it in a lazy manner: only as much as is necessary.
So, in your case, neither query will iterate the whole collection: both will iterate it only up to the point where they find the first element, and then stop.
Actually, the second query (with Take()) won't do even that, it will iterate the source collection only if you iterate the result.
This all applies to LINQ to objects. Other providers (LINQ to SQL and others) can behave differently, but at least the principle of deferred execution usually still holds.

A: I think First() will not scan the whole collection. It will return immediatelly after the first match. But I suggest to use FirstOrDefault() instead.
EDIT:
Difference between First() and FirstOrDefault() (from MSDN):
The First() method throws an exception if source contains no elements. To instead return a default value when the source sequence is empty, use the FirstOrDefault() method.
Enumerable.First

A: Substitue .Where( by .SingleorDefault(
This will find the first and only item for you.
But you can't do this for any given number. If you need 2 items, you'll need to get the entire collection.
However, you shouldn't worry about time. The most effort is used in opening a database connection and establishing a query. Executing the query doesn't take that much time, so there's no real reason to stop a query halfway :-)


text:
Q: Javascript - map value to keys (reverse object mapping) I want to reverse the mapping of an object (which might have duplicate values). Example:
const city2country = {
    'Amsterdam': 'Netherlands',
    'Rotterdam': 'Netherlands',
    'Paris': 'France'
};

reverseMapping(city2country) Should output:
{
    'Netherlands': ['Amsterdam', 'Rotterdam'],
    'France': ['Paris']
}

I've come up with the following, naive solution:
const reverseMapping = (obj) => {
    const reversed = {};
    Object.keys(obj).forEach((key) => {
        reversed[obj[key]] = reversed[obj[key]] || [];
        reversed[obj[key]].push(key);
    });
    return reversed;
};

But I'm pretty sure there is a neater, shorter way, preferably prototyped so I could simply do:
const country2cities = city2country.reverse();

A: There is no such built-in function in JavaScript. Your code looks fine, but given that there are so many edge cases here that could wrong, I'd suggesting using invertBy from lodash, which does exactly what you describe.
Example

var object = { 'a': 1, 'b': 2, 'c': 1 };

_.invertBy(object);
// => { '1': ['a', 'c'], '2': ['b'] }

A: You could use Object.assign, while respecting the given array of the inserted values.

const city2country = { Amsterdam: 'Netherlands', Rotterdam: 'Netherlands', Paris: 'France' };
const reverseMapping = o => Object.keys(o).reduce((r, k) =>
        Object.assign(r, { [o[k]]: (r[o[k]] || []).concat(k) }), {})

console.log(reverseMapping(city2country));

A: You can use something like this to get raid of duplicates first :
function removeDuplicates(arr, key) {
   if (!(arr instanceof Array) || key && typeof key !== 'string') {
    return false;
   }

  if (key && typeof key === 'string') {
    return arr.filter((obj, index, arr) => {
        return arr.map(mapObj => mapObj[key]).indexOf(obj[key]) === index;
    });

  } else {
    return arr.filter(function(item, index, arr) {
        return arr.indexOf(item) == index;
    });
  }
}

and then use this to make it reverse :
function reverseMapping(obj){
  var ret = {};
  for(var key in obj){
  ret[obj[key]] = key;
  }
    return ret;
  }

A: You could use reduce to save the declaration line reduce.
Abusing && to check if the map[object[key]] is defined first before using Array.concat.
It's shorter, but is it simpler? Probably not, but a bit of fun ;)
const reverseMapping = (object) =>
    Object.keys(object).reduce((map, key) => {
        map[object[key]] = map[object[key]] && map[object[key]].concat(key) || [key]
     return map;
    }, {});

A: You could try getting an array of values and an array of keys from the current object, and setup a new object to hold the result. Then, as you loop through the array of values -

*

*if the object already has this value as the key, like Netherlands, you create a new array, fetch the already existing value (ex: Rotterdam), and add this and the new value (Amsterdam) to the array, and set up this array as the new value for the Netherlands key.

*if the current value doesn't exist in the object, set it up as a new string, ex: France is the key and Paris is the value.

Code -

const city2country = {
    'Amsterdam': 'Netherlands',
    'Rotterdam': 'Netherlands',
    'Paris': 'France',
};

function reverseMapping(obj) {
  let values = Object.values(obj);
  let keys = Object.keys(obj);
  let result = {}
  values.forEach((value, index) => {
    if(!result.hasOwnProperty(value)) {
      // create new entry
      result[value] = keys[index];
    }
    else {
      // duplicate property, create array
      let temp = [];
      // get first value
      temp.push(result[value]);
      // add second value
      temp.push(keys[index]);
      // set value
      result[value] = temp;
    }
  });

  console.log(result);
  return result;
}

reverseMapping(city2country)

The benefit here is - it adjusts to the structure of your current object - Netherlands being the repeated values, gets an array as it's value in the new object, while France gets a string value Paris as it's property. Of course, it should be very easy to change this.
Note - Object.values() might not be supported across older browsers.

A: @Nina Scholz answer works well for this exact question. :thumbsup:
But if you don't need to keep both values for the Netherlands key ("Netherlands": ["Amsterdam", "Rotterdam"]), then this is a little bit shorter and simpler to read:
const city2country = { Amsterdam: 'Netherlands', Rotterdam: 'Netherlands', Paris: 'France' };

console.log(
  Object.entries(city2country).reduce((obj, item) => (obj[item[1]] = item[0]) && obj, {})
);
// outputs `{Netherlands: "Rotterdam", France: "Paris"}`


text:
Q: How can I stop do-while in windows form app by clicking on a button? I want to use a button in windows form app to stop do-while. When I click on stop button, the stop button does not work. How can I do it?
do{
            …….
  } while (stop == 0);

In Stop button:
stop = 1;

A: You can run your loop in a Task or async void, and use a CancellationToken to stop it
Given
private static CancellationTokenSource _cs;
private static CancellationToken _token;

public static async Task StartWhile()
{
   while (!_token.IsCancellationRequested)
   {
      Console.WriteLine("looping");
      await Task.Delay(1000);
   }

   Console.WriteLine("loop stopped");

}

Usage
   _cs = new CancellationTokenSource();
   _token = _cs.Token;

   Task.Run(StartWhile);

   Console.WriteLine("Press any key to exit");

   var result = Console.ReadKey();

   Console.WriteLine("You Pressed "+ result.Key);
   _cs.Cancel();

   Console.WriteLine("loop stopped");

   Console.ReadKey();

Output
Press any key to exit
looping
looping
looping
looping
You Pressed Enter
loop stopped

Or a Winforms example
private async void btnStart_Click(object sender, EventArgs e)
{
   try
   {
      btnStart.Enabled = false;

      _cs = new CancellationTokenSource();
      _token = _cs.Token;

      while (!_token.IsCancellationRequested)
      {
         Debug.WriteLine("looping");
         await Task.Delay(1000);
      }

      Debug.WriteLine("loop stopped");
   }
   finally
   {
      btnStart.Enabled = true;
   }
}

private void btnStop_Click(object sender, EventArgs e)
{
   Debug.WriteLine("You Cancelled");
   _cs?.Cancel();
}

A: @JohnG's comment above basically sums up the issue you are probably having. You can't do a long-running set of computations on the User-Interface (UI) thread. You have to shuffle that off to another thread or task.
This is where parallel programming comes in: You want to click a button, have that initiate some work, but also allow for the UI to allow the user to click another button to stop that work.
So, here is a small example of what we are talking about:
private CancellationTokenSource _tokenSource;

private async void BtnStartWork_Click(object sender, EventArgs e)
{
    BtnStartWork.Enabled = false;
    _tokenSource = new CancellationTokenSource();

    try
    {
        await Task.Run(() => CPUBoundWork(_tokenSource.Token));
    }
    finally
    {
        _tokenSource.Dispose();
        _tokenSource = null;
        BtnStartWork.Enabled = true;
    }

}

private void BtnStopWork_Click(object sender, EventArgs e)
{
    // signal cancel -- everyone listening will be notified.
    _tokenSource?.Cancel();
}

private void CPUBoundWork(CancellationToken cancellationToken)
{
    for (var i = 0; i < 10000; ++i)
    {
        if (cancellationToken.IsCancellationRequested)
        {
            // signaled for cancel, leave immediatly.
            break;
        }
        // simulate CPU-bound work:
        Thread.Sleep(10);
    }
}

Some things may look new to you, for example: The BtnStartWork_Click method has the keyword async in it's signature. There is the keyword await being used. I won't explain everything going on here because there are plenty of resources out there about the subject.
But, this is the general idea of parallel programming. Your UI thread is still free to process messages dealing with the UI, and the framework makes sure to do the tasks you need it to do... all this with very little effort for the programmer.


text: Q: Positive Projections on Matrix Subspaces Let $\mathcal{M}_d$ be the space of complex valued $d\times d$ matrices, and $\mathcal{S}\subset \mathcal{M}_d$ a subspace. Let $P_{\mathcal{S}}$ be a projection onto $\mathcal{S}$. My questions is about what properties must $\mathcal{S}$ fulfill to guarantee that there exists a $P_{\mathcal{S}}$ with the property of being positive preserving. Example: if $\mathcal{S}={\rm span}(A)$ where $A$ a positive semidefinite matrix, then by using the Hilbert-Schmidt inner product, one constructs a positive preserving $P_{\mathcal{S}}$ (completely positive actually).


text:
Q: Google sheets formula to extract 10-digit mobile number starting from 69 I want to extract the mobile phones from candidates' CVs.
The mobile phone format I want to extract is 69xxxxxxxx.
The mobile phone formats i come across in the CVs are:
69 xxx xxxxx
0030 69xxxxxxxx
+3069xxxxxxxx
69/xxxx/xxxx

The following formula works great but it extracts the first 10 digits detected and not the one that starts with 69.
=IFERROR(REGEXEXTRACT(TO_TEXT(SPLIT(REGEXREPLACE(I252;"\(|\)|\-| "; ""); CHAR(10))); "\d{10}"))

A: You may use
=IFERROR(REGEXEXTRACT(TO_TEXT(SPLIT(REGEXREPLACE(I252;"[-/() ]+"; ""); CHAR(10))); "(?:\+|00)?(?:30)?(69\d{8})"))

See the regex demo and the Google Sheets screenshot below:

The regex matches

*

*(?:\+|00)? - an optional + or 00

*(?:30)? - an optional 30

*( - start of the capturing group (only this value will be returned):

*

*69 -  69 value

*\d{8} - eight digits

*) - end of the group.

You might consider appending \b at the end of the regex to avoid matching the 8 digits in chunks of more than 8 digits.
Note that the separator cleaning regex is [-/() ]+ now, it matches 1 or more -, /, (, ) and spaces.

A: The solution to your problem is to make use of a regex lookbehind (although I do not know if Google Sheets supports this).
A regex lookbehind matches a pattern, but without including in the result. The syntax for this, with your example, is:
(?<=69)\d{10}
The picture below is taken from https://regex101.com/ (which is a super-useful tool when working with regexps).

Regex lookahead, lookbehind and atomic groups has some more examples of how lookaheads and lookbehinds work.

A: all you need is:
=ARRAYFORMULA(IFNA(REGEXREPLACE(REGEXEXTRACT(A1:A&""; "69.*"); "\s|/|\D+"; )))

or better:
=ARRAYFORMULA(IFNA(REGEXEXTRACT(REGEXREPLACE(A1:A&""; "\D+"; ); "69.{8}")))


text:
Q: What is the origin of the term "first contact"? This term has a long history in Star Trek:
Star Trek: First Contact
ST:TNG episode "First Contact"
First Contact Day
Also:
Stargate: Atlantis episode "First Contact"
Does this term originate in Star Trek or was it used in previous sci-fi works or does it predate sci-fi in discussing initial contact between cultures.

A: According to the Historical Dictionary of Science Fiction, the earliest known occurrence of the term first contact in the science-fictional sense of "[t]he first meeting between two different intelligent species" was in the novella "Proxima Centauri" by Murray Leinster (pseudonym of William F. Jenkins), which first appeared in the March 1935 Astounding Stories (available at the Internet Archive). The following quotation is from page 21,column 2, of the original magazine publication, or p. 669 of Isaac Asimov's anthology Before the Golden Age:

He had piloted the Adastra to its first contact with the civilization of another solar system.

A: As far as I know, the first use of this exact phrase was in 1945 (~20 years before Star Trek), in a short story by Murray Leinster called First Contact. This story has long been considered one of the best science fiction stories ever (it's in the "Hall of Fame", and is in a number of anthologies such as this one.)
In fact, the author's estate tried to sue Paramount for trademark infringement over Star Trek: First Contact. The court found that Leinster probably did coin the term, but in the interim decades, it had become too generic to trademark any more.

A: Actually, the first use of this exact phrase, at least in printed works, was in 1875, according to Google's handy Ngram Viewer:

*

*Term "First Contact" in the English corpus, between 1500 AD and present
This was used in an astronomical sense, in the Monthly Notices of the Royal Astronomical Society :

*

*Volumes 1874-1875
But for usage in the desired sense of "initial contact between cultures", the very first appearance was in the (rather lengthy) title of the following book:

*

*With a Prehistoric People, the Akikuyu of British East Africa, Being Some Account of the Method of Life and Mode of Thought Found Existent Amongst a Nation on Its First Contact with European Civilisation: With Illustrations and a Map
by W. Scoresby Routledge and Katherine Routledge, first published 1910.
These instances predate the term's first appearances in science fiction, i.e. Murray Leinster's 1935 novella Proxima Centauri and his 1945 novelette First Contact.
In the former, we have the passage

He had piloted the Adastra to its first contact with the civilization of another solar system...

which provides the first usage of the phrase in science fiction (in the desired sense).
(Thanks to @user14111 for the Proxima Centauri reference, and for pointing out that a 1916 instance reported in a prior version of this answer may not have been correct.)


text:
Q: Sending HTTP command in browser works, not when sent with httppost When in my browser I send the following string to a control unit I have http://192.168.0.215/i_activate/aterm?40~00 and a relay is activated.
I have tried many variations of the following:
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.0.215/i_activate/aterm?40~00");

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

With an HTML response "FAIL" from the unit
I have tried adding the 40~00 in many ways (NameValuePair, etc) and encoded in different forms without success but I am sure the problem lies there.
Any thoughts?

A: The problem is that the browser sends a GET request, where the parameter is in the URL itself as a query string, but you are sending a POST request without any body data.
Use HttpGet instead of HttpPost to send a GET request:
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://192.168.0.215/i_activate/aterm?40~00");

// Execute HTTP Get Request
HttpResponse response = httpclient.execute(httpget);


text:
Q: PHP - Array to string conversion using form Hello I am yousing form to insert new values into query.
Error which i got is:Array to string conversion.
What should I change to not get this error?
Thank you
if( isset($_POST["new_log"]) ){

//mysql_real_escape_string - ochrana proti mysql injection

$name       = $_POST["name"];
$surname    = $_POST["surname"];
$password   = $_POST["password"];
$email      = $_POST["email"];
$salary     = $_POST["salary"];
$msaving    = $_POST["msaving"];
$mfixpayment = $_POST["mfixpayment"];
$lastupdate = $_POST["lastupdate"];
$bio        = $_POST["bio"];
$money      = $_POST["money"];

$new_log=" INSERT INTO login SET `name`='$name', `surname`='$surname', `password`='$password', `email`='$email', `salary`='$salary', `msaving`='$msaving', `mfixpayment`='$mfixpayment', `lastupdate`='$lastupdate', `bio`='$bio', `money`='$money' ";

mysql_query( $new_log ) or die( mysql_error() );

}

here I am inserting new values by form
    echo ' <form method="post"> ';
    echo ' meno:                <input type="text" name="name['. $row_log["id"] .']" >
';
    echo ' priezvisko:          <input type="text" name="surname['. $row_log["id"] .']">
';
    echo ' heslo:               <input type="text" name="password['. $row_log["id"] .']">
';
    echo ' e-mail:              <input type="text" name="email['. $row_log["id"] .']">
';
    echo ' vyplata:             <input type="number" name="salary['. $row_log["id"] .']">
';
    echo ' chcem mesačne ušetriť <input type="number" name="msaving['. $row_log["id"] .']">
';
    echo ' platím každý mesiac: <input type="number" name="mfixpayment['. $row_log["id"] .']">
';
    echo ' posledná mena:       <input type="date" name="lastupdate['. $row_log["id"] .']">
';
    echo ' niečo o sebe:        <input type="text" name="bio['. $row_log["id"] .']">
';
    echo ' mám na účte:         <input type="number" name="money['. $row_log["id"] .']">
';
    echo "
";

    echo '<input type="submit" name="new_log" value="Pridať nového užívateľa" >';
    echo '</form>';

A: $name       = $_POST["name"];

should be
$name       = $_POST["name"][$id];

Alternatively, output this:
<input type="text" name="name" >

instead of
<input type="text" name="name['. $row_log["id"] .']" >


text:
Q: is there any differenc between these two selectors in Styled-components? ">" vs "&" greater than sign(>) refers to the direct parent.
ampersand sign(&) also does refer to its parent.
const Container = styled.div`
  > p{
    color:red;
  }
`

above equals to this ㄱ
const Container = styled.div`
  & p{
    color:red;
  }
`

both versions will make the p tag, which is the direct child of Container, have a red font color....
is that wrong? if so, how are they different?

A: "parent > p" will apply only to paragraphs that are direct children of parent, while "&" will apply to all paragraphs located inside its parent, no meter the level. Putting "& p {}" is equal to putting "parent p {}".


text:
Q: Large image in the header For some reason, the header in my document has to include an image which width has to be the width of the paper (in a4 format, it is 21cm).
But I don't want the margin of body to be changed, just the one of the header.
Here is an example :
\documentclass{article}

\usepackage{graphicx}
\usepackage{geometry}
\geometry{a4paper,includehead,top=0cm}
\usepackage{fancyhdr}
\pagestyle{fancy}
\setlength\headheight{28pt}
\chead{\includegraphics[width=\paperwidth]{hautpage1.jpg}}
\renewcommand{\headrulewidth}{0pt}

\begin{document}

gthfgh
\newpage
bzedgfhbd
\newpage
bzedgfhbd

\end{document}

As you can see, the image is shifted on the right, but does not fit all the paper width.
What can I do/change in order to have my picture to fit all the page ?
Here is what I want :

Any suggestion ?

A: The problem is, that your image is wider (\paperwidth) than the place where you want to put it (\headwidth). When compiling, you currently get the warning

Overfull \hbox (179.2542pt too wide) ...

which informs you about that.
A possible solution is to place the picture inside a box of width \headwidth. That box can then be placed correctly by LaTeX, as it has the correct width. You can do that with the \makebox[width][alignment]{content} command, with a width of \headwidth and c for centered alignment.
\documentclass{article}

\usepackage{graphicx}
\usepackage{geometry}
\geometry{a4paper,includehead,top=0cm}

\usepackage{fancyhdr}
\pagestyle{fancy}
\setlength\headheight{60.9pt}
\chead{\makebox[\headwidth][c]{\includegraphics{manyducks.jpg}}}

\renewcommand{\headrulewidth}{0pt}

\begin{document}

gthfgh
\newpage
bzedgfhbd
\newpage
bzedgfhbd

\end{document}


text:
Q: Space length between the chapter number and the chapter title How can I learn the horizontal distance between the chapter number and the chapter title both in ToC  and the body text where I use \documentclass[12pt,reqno]{book}. Which keys hold these values?

A: book (like report) sets the ToC entry for a chapter using \l@chapter. This is what it looks like:
\newcommand*\l@chapter[2]{%
  \ifnum \c@tocdepth >\m@ne
    \addpenalty{-\@highpenalty}%
    \vskip 1.0em \@plus\p@
    \setlength\@tempdima{1.5em}%
    \begingroup
      \parindent \z@ \rightskip \@pnumwidth
      \parfillskip -\@pnumwidth
      \leavevmode \bfseries
      \advance\leftskip\@tempdima
      \hskip -\leftskip
      #1\nobreak\hfil \nobreak\hb@xt@\@pnumwidth{\hss #2}\par
      \penalty\@highpenalty
    \endgroup
  \fi}

The specific thing to note here is the value of \@tempdima, set to 1.5em. The first argument of \l@chapter (or #1) uses \numberline, which is defined in the kernel latex.ltx as:
\def\numberline#1{\hb@xt@\@tempdima{#1\hfil}}

creating a box of width \@tempdima and left-aligning its contents. Note that this 1.5em is based on the prevailing font at the time of setting (\normalsize\bfseries by default).

The (numbered) chapter head in book (and report) is set via the macro \@makechapterhead. Here's a take on that:
\def\@makechapterhead#1{%
  \vspace*{50\p@}%
  {\parindent \z@ \raggedright \normalfont
    \ifnum \c@secnumdepth >\m@ne
      \if@mainmatter
        \huge\bfseries \@chapapp\space \thechapter
        \par\nobreak
        \vskip 20\p@
      \fi
    \fi
    \interlinepenalty\@M
    \Huge \bfseries #1\par\nobreak
    \vskip 40\p@
  }}

The space between the word Chapter (or \@chapapp in the definition above) and the number (\thechapter in the definition above) is a regular \space or \.

In both instances, if you want to change these defaults, you have at least 3 options:

*

*Use a package that allows you to modify this content (like titlesec or tocloft or the like);

*Copy the entire definition and change it to your liking (making \newcommand -> \renewcommand);

*Use etoolbox to patch the command. For example,
\usepackage{etoolbox}% http://ctan.org/pkg/etoolbox
\makeatletter
\patchcmd{\l@chapter}% <cmd>
  {1.5em}% <search>
  {5.5em}% <replace>
  {}{}% <success><failure>
\makeatother

would use a 5.5em wide box for setting the chapter number in the ToC, increasing the gap between the number and title. Also
\usepackage{etoolbox}% http://ctan.org/pkg/etoolbox
\makeatletter
\patchcmd{\@makechapterhead}% <cmd>
  {\space}% <search>
  {\hspace*{100pt}\ignorespaces}% <replace>
  {}{}% <success><failure>
\makeatother

would insert a 100pt gap between the word Chapter (or whatever \@chapapp is) and the number. \ignorespaces would just remove any trailing spaces left inside the original definition of \@makechapterhead.


text:
Q: update old processes with the new process definition -Activiti I have some processes that ran with old process definitions. But due to requirement change the user task data has been updated with new attributes and this process definition has been deployed. I'm aware that "SetProcessDefinitionVersionCmd" can be set to "yes" to point the processes to the new definition/version.
I would like to know how to migrate the old process data to have the newly added attributes of the user task updated in them?

A: There is no easy way to migrate process instance data, however, when you set the version to the new process definition the instance data will go with the migrated instance.
What you have to be careful of is to make sure you include null checks for any of the data that may not be present in the migrated process instances.
Hope this helps,
Greg

A: Indeed there is no easy way for migration, however depending on the differences between the two definitions and to what extend you may not prefer to use SetProcessDefinitionVersionCmd, you may find DynamicBpmnService useful when combined with detecting definitions' versions inside your logic.
And yes another way would be to use SetProcessDefinitionVersionCmd but  be extra cautions for tasks that were actually active prior to migration, as Activiti's database model have some redundant data (some for performance reasons), you are better studying the DB tables first for these tasks and then inspecting the before and after migration state. For example, keeping up with a simple changed attribute is much easier than an added boundary event on an active User Task, which affects the "execution tree".
I would also advice to compare SetProcessDefinitionVersionCmd's implementations between Activiti and Camunda, it is sad to have such enhancements efforts separated, but that is another story.


text:
Q: Convert wide character strings to boost dates I need to convert several million dates stored as wide strings into boost dates
The following code works.  However, it generates a horrible compiler warning and does not seem efficient.
Is there a better way?
#include "boost/date_time/gregorian/gregorian.hpp"
using namespace boost::gregorian;

#include <string>
using namespace std;

    wstring ws( L"2008/01/01" );

    string temp(ws.length(), '\0');
    copy(ws.begin(), ws.end(), temp.begin());
    date d1( from_simple_string( temp ) );

    cout << d1;

The better way turns out to be to use the standard C++ library locale, which is a collection of facets.  A facet is a service which allows the stream operators to handle a particular choice for date or time representation or just about anything else.  All the choices about diferent things, each handled by its own facet, are gathered together in a locale.
This solution was pointed out to me by litb  who gave me enough help to use facets in my production code, making it terser and faster.  Thanks.
There is an excellent tutorial on locales and facets by Nathan Myers who designed facets.  He has a light style which makes his tutorial easy to read, though this is advanced stuff and your brain may hurt after the first read through - mine did.  I suggest you go there now. For anyone who just wants the practicalities of converting wide character strings to boost dates, the rest of this post describes the minimum necessary to make it work.

litb first offered the following simple solution that removes the compiler warning.  ( The solution was edited before I got around to accepting it. )  This looks like it does the same thing, converting wide characters one by one, but it avoids mucking around with temp strings and therefore is much clearer, I think.  I really like that the compiler warning is gone.
#include "boost/date_time/gregorian/gregorian.hpp"
using namespace boost::gregorian;

#include <string>
using namespace std;

    wstring ws( L"2008/01/01" );

    date d1( from_simple_string( string( ws.begin(), ws.end() ) );

    cout << d1;

litb went on to suggest using "facets", which I had never heard of before.  They seem to do the job, producing incredibly terse code inside the loop, at the cost of a prologue where the locale is set up.
wstring ws( L"2008/01/01" );

// construct a locale to collect all the particulars of the 'greek' style
locale greek_locale;
// construct a facet to handle greek dates - wide characters in 2008/Dec/31 format
wdate_input_facet greek_date_facet(L"%Y/%m/%d");
// add facet to locale
greek_locale = locale( greek_locale, &greek_date_facet );
// construct stringstream to use greek locale
std::wstringstream greek_ss;
greek_ss.imbue( greek_locale );

date d2;

greek_ss << ws;
greek_ss >> d2;

cout << d2;

This, it turns out, is also more efficient:
clock_t start, finish;
double  duration;

start = clock();
for( int k = 0; k < 100000; k++ ) {
    string temp(ws.length(), '\0');
    copy(ws.begin(), ws.end(), temp.begin());
    date d1( from_simple_string( temp ) );
}
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
cout << "1st method: " << duration << endl;

start = clock();
for( int k = 0; k < 100000; k++ ) {
    date d1( from_simple_string( string( ws.begin(), ws.end() ) ) );
}
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
cout << "2nd method: " << duration << endl;

start = clock();
for( int k = 0; k < 100000; k++ ) {
    greek_ss << ws;
    greek_ss >> d2;
    ss.clear();
}
finish = clock();
duration = (double)(finish - start) / CLOCKS_PER_SEC;
cout << "3rd method: " << duration << endl;

Produces the following output:

1st method: 2.453
2nd method: 2.422
3rd method: 1.968

OK, this is now in the production code and passing regression tests.  It looks like this:
  //  .. construct greek locale and stringstream

  // ... loop over input extracting date strings

        // convert range to boost dates
        date d1;
        greek_ss<< sd1; greek_ss >> d1;
        if( greek_ss.fail() ) {
                       // input is garbled
            wcout << L"do not understand " << sl << endl;
            exit(1);
        }
         greek_ss.clear();

// finish processing and end loop

I have one final question about this.  Adding the facet to the locale seems to require two invocations of the locale copy constructor
    // add facet to locale
greek_locale = locale( greek_locale, &greek_date_facet );

Why is there not an add( facet* ) method?  ( _Addfac() is complex, undocumented and deprecated )

A: efotinis found a good way using from_stream .

I've looked into the manual of date_time and found it supports facets:
#include <boost/date_time/gregorian/gregorian.hpp>
#include <iostream>
#include <sstream>
#include <locale>

int main() {
    using namespace boost::gregorian;

    std::wstringstream ss;
    wdate_input_facet * fac = new wdate_input_facet(L"%Y-%m-%d");
    ss.imbue(std::locale(std::locale::classic(), fac));

    date d;
    ss << L"2004-01-01 2005-01-01 2006-06-06";
    while(ss >> d) {
        std::cout << d << std::endl;
    }
}

You could also go with that.

I've looked up how date facets work:

*

*The boost::date_time::date_input_facet template implements a facet.

*Facets are derived from std::locale::facet and every one has an unique id.

*You can imbue a new locale into a stream, replacing its old locale. The locale of a stream will be used for all sorts of parsing and conversions.

*When you create a new std::locale using the form i showed, you give it an existing locale, and a pointer to facet. The given facet will replace any existing facet of the same type in the locale given. (so, it would replace any other date_input_facet used).

*All facets are associated with the locale somehow, so that you can use std::has_facet<Facet>(some_locale) to check whether the given locale has some given facet type.

*You can use a facet from one locale by doing std::use_facet<Facet>(some_locale).some_member... .

*date_input_facet has a function get, which can be used like this:

The below is essentially done by operator>> by boost::date_type :
// assume src is a stream having the wdate_input_facet in its locale.
// wdate_input_facet is a boost::date_time::date_input_facet<date,wchar_t> typedef.

date d;

// iterate over characters of src
std::istreambuf_iterator<wchar_t> b(src), e;

// use the facet to parse the date
std::use_facet<wdate_input_facet>(src.getloc()).get(b, e, src, d);

A: You can use the from_stream parser function:
using boost::gregorian::date;
using boost::gregorian::from_stream;

std::wstring ws( L"2008/01/01" );
date d1(from_stream(ws.begin(), ws.end()));
std::cout << d1;  // prints "2008-Jan-01"


text:
Q: mod_rewrite query string with empty parameters So I want to do a mod_rewrite in my .htaccess file so that the following browser request:
www.mysite.com/portal/v1/v2/v3

...will be rewritten and processed in php as this:
www.mysite.com/portal.php?n1=v1&n2=v2&n3=v3

The caveat here is that some or all of those GET variables could be blank, meaning the browser request could take any of the following forms:
www.mysite.com/portal/v1/v2/v3
www.mysite.com/portal/v1/v2
www.mysite.com/portal/v1
www.mysite.com/portal

I can sort things out in the php file, but what code should I use for .htaccess? Thanks!

A: Try this in your /.htaccess
RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f

RewriteRule ^(.*)/(.*)/(.*)/?$ /portal.php?n1=$1&n2=$2&n3=$3 [QSA,L,NC]

RewriteCond ensures that if the request is already for a file or directory RewriteRule will be skipped.
$1 $2 $3 refer to a pattern matched inside a RewriteRule.

A: You can use this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^ - [L]

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/?$ portal.php?n1=$1&n2=$2&n3=$3 [QSA,L]

RewriteRule ^([^/]+)/([^/]+)/?$ portal.php?n1=$1&n2=$2 [QSA,L]

RewriteRule ^([^/]+)/?$ portal.php?n1=$1 [QSA,L]

RewriteRule ^/?$ portal.php [L]


text:
Q: Trouble with DPTR and DB I'm programming a SciLabs C8051F330 micro controller and daughter card in assembler. I'm struggling with the following code:
MOV         DPTR,#200H  ;
CLR         A
MOVC        A,@A+DPTR
MOV         P1,A

ORG         200H
DB          03H

According to my debugger the value of A is 03H and the DPTR is 200H, but when I MOV A into P1 the end result is 43H instead of 03H.
Thank you,
Brandon

A: If your all memory up to 200H was not filled then try to minimize it and make it 150H or if possible than make it 100H. And try it again.


text:
Q: Disable CORS in Mozilla Firefox for development purpose: Local Websocket connection in Tampermonkey I have a Tampermonkey addon contacting my local dev server using Websockets. This doesn't work and throw the following error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://127.0.0.1:3000/socket.io/?EIO=3&transport=polling&t=N9Bvvb3. (Reason: CORS request did not succeed).

So I tried the first three Addons found by a search by CORS:

*

*https://addons.mozilla.org/de/firefox/addon/cors-unblock/?src=search

*https://addons.mozilla.org/de/firefox/addon/cross-domain-cors/?src=search

*https://addons.mozilla.org/de/firefox/addon/cors-everywhere/?src=search
None of them seems to work. How can I fix this?
I know the security minds behind CORS. Since my software targets developers and is only be used locally, I don't need it. So I'm searching for an easy solution to allow my tampermonkey script to connect to localhost when accessing a web page like https://example.com.
I also tried different things on the server side to make CORS properly work like this or this, but still getting the error.
Server
let app = express();
app.use(express.static(path.resolve(`${__dirname}/../dist`)));
const certDir = "certs";
let httpOpts = {
  key: fs.readFileSync(`${certDir}/localhost.key`),
  cert: fs.readFileSync(`${certDir}/localhost.crt`),
  requestCert: false,
  rejectUnauthorized: false
};
var http = require("https").createServer(httpOpts, app);
var io = require("socket.io")(http);

Tampermonkey client scirpt
const localDevUrl = "https://127.0.0.1:3000";
this.socket = io(localDevUrl, { secure: true });


text:
Q: Vuetify toolbar alignement router-link I'm new in StackOverflow, so it's nice to join this community.
I'm trying to develop a VueJS app with Vuetify.
I have a toolbar on top and I would like to have a logo on the left of the toolbar title. I work until I put both in a router link, then the picture is above the title.
I just don't understand why. Can somebody explain to me?

<router-link to="/" align="middle">

  <v-toolbar-title class="font-weight-light">{{appTitle}}</v-toolbar-title>
</router-link>

A:

<router-link to="/" align="middle">
  <v-toolbar-title class="font-weight-light">{{appTitle}}
</v-toolbar-title>
</router-link>


text:
Q: how to derive schrodinger equation from heisenberg equation? canonical commutator relation(CCR) can be derived by switching classical poisson bracket to quantum commutator and this process is called as canonical quantization.
$[x_i,p_j]_{PB}=\delta_{ij} →\frac{1}{ih}[x_i,p_j]=\delta_{ij}$
and also, the classical hamilton's equation of motion can be written by this quantum meachanical language,
$ \frac{dp}{dt}=[p,H]_{PB},\frac{dq}{dt}=[q,H]_{PB} →i\hbar\frac{dp}{dt}=[p,H],i\hbar\frac{dq}{dt}=[q,H]$
This is the heisenberg equation of motion as far as I know.
I want to know, how to derive schrodinger equation from this heisenberg equation of motion.
Maybe it looks like a stupid question. But please help me.

A: Take $\hat{O}$ to be operator of some observable.
In Heisenberg picture the states are time independent, i.e.
$$\partial_t |\psi_H\rangle=0,$$
but the operators depend on time
$$\partial_t \hat{O}_H=\frac{i}{\hbar}\left[\hat{H},\hat{O}_H\right]$$
A 'solution' to this equation is:
$$\hat{O}_H\left(t\right) = \exp\left(\frac{it}{\hbar}\hat{H}\right)\hat{O}\exp\left(-\frac{it}{\hbar}\hat{H}\right)$$
where $\partial_t \hat{O}=0$.
Any observable corresponding to the above operator will be:
$$O\left(t\right)=\langle \psi_H | \hat{O}_H \left(t\right) |\psi_H\rangle=\langle \psi_H |\exp\left(\frac{it}{\hbar}\hat{H}\right) \hat{O} \exp\left(-\frac{it}{\hbar}\hat{H}\right) |\psi_H\rangle$$
We now choose to define the Schrodinger picture as time-independent operators and time-dependent states:
$$|\psi\left(t\right)\rangle = \exp\left(-\frac{it}{\hbar}\hat{H}\right) |\psi_H\rangle$$
$$O\left(t\right)=\langle \psi \left(t\right) | \hat{O} |\psi \left(t\right)\rangle$$
It follows that: $\partial_t |\psi\left(t\right)\rangle= \frac{-i}{h}\hat{H}|\psi\left(t\right)\rangle $, usually written as:
$$i\hbar \partial_t |\psi\left(t\right)\rangle= \hat{H}|\psi\left(t\right)\rangle $$


text:
Q: Firebase Custom Authentication - lastSignInTime = Null I'm using 'firebase-admin' for node to create custom tokens based on users created using admin.auth().createUser(params) and updated via admin.auth().updateUser(userId, updateParams)
However, when a custom user is created, such user's "signed in" field is "null" in the Firebase Authentication Dashboard as well as when I fetch user record using admin.auth().getUser('custom:uid').then((userRecord) => { console.log(userRecord.toJSON()); })
Below is the result from fetching user record (I have masked credentials):

{
uid: 'custom:uid',
email: 'xxx@yyy.com',
emailVerified: false,
displayName: 'testuser',
photoURL: 'https://xxxx.jpg',
phoneNumber: undefined,
disabled: false,
metadata: {
lastSignInTime: null,
creationTime: 'Mon, 29 Mar 2021 08:11:56 GMT'
},
passwordHash: undefined,
passwordSalt: undefined,
customClaims: undefined,
tokensValidAfterTime: 'Mon, 29 Mar 2021 08:11:56 GMT',
tenantId: undefined,
providerData: []
}

and below is my dashboard screenshot:

My question is what should I do to update 'lastSignInTime', so that it correctly updates upon a user sign in? I assumed that either when I createUser() or updateUser(), Firebase shall automatically record the "Signed In" field (as it did for "Created"), which it did not do.

A: The value of "Signed In" will update when the user signs in for the first time.  As far as I'm aware there's no other way to update that value.


text:
Q: How to pass data from by Android speech recognizer to a service? I have a widget which will open the default speech recognizer activity on click. Now I want the data from this activity to go to my service which does some processing. I can start the speech recognizer activity using the following code
    @Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
    super.onUpdate(context, appWidgetManager, appWidgetIds);
    ComponentName thisWidget = new ComponentName(context,
            MicWidgetProvider.class);
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);
    for (int widgetId : allWidgetIds) {
        RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
                R.layout.mic_widget_layout);

         // this intent points to activity that should handle results
         Intent serviceIntent = new Intent(context,
         SpeechWidgetService.class);
         // this intent wraps results activity intent
         PendingIntent resultsPendingIntent = PendingIntent.getService(
         context, REQUEST_CODE, serviceIntent, 0);

        // this intent calls the speech recognition
        Intent voiceIntent = new Intent(
                RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        voiceIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        voiceIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Jarvis");
        voiceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        voiceIntent.putExtra(RecognizerIntent.EXTRA_RESULTS_PENDINGINTENT,
                resultsPendingIntent);

        // this intent wraps voice recognition intent
        PendingIntent pendingIntent = PendingIntent.getActivity(context,
                REQUEST_CODE, voiceIntent, 0);
        remoteViews.setOnClickPendingIntent(R.id.arc_widget, pendingIntent);
        appWidgetManager.updateAppWidget(widgetId, remoteViews);
    }
    Log.d(TAG, "clicking..");
}

When I click on the widget, everything works fine and I can speak and it closes when I stop speaking. The problem is that the service is not at all being called. What am I doing wrong? For now I just have a dummy service to check whether data is coming in or not.
public class SpeechWidgetService extends Service {

private static final String TAG = "SpeechWidgetService";

@Override
public IBinder onBind(Intent intent) {
    ArrayList<String> voiceResults = intent.getExtras().getStringArrayList(RecognizerIntent.EXTRA_RESULTS);
    Log.d(TAG, voiceResults.get(0));
    Toast.makeText(getBaseContext(), voiceResults.get(0), Toast.LENGTH_SHORT).show();
    return null;
}

@Override
public void onCreate() {
    Log.d(TAG, "onCreate");
    super.onCreate();
}

@Override
public void onStart(Intent intent, int startId) {
    Log.d(TAG, "onStart");
}

}

A: never mind i figured it out. You will have to place an additional dummy activity, fire it from the widget and call the speech recognizer from there. You can always get back the result using onActivityResult().

A: you shouldn't need a dummy activity.
This could be a problem related to the request code for the PendingIntent.
See https://code.google.com/p/android/issues/detail?id=63666 for a bug report which could be related to your problem
Did you try to use another request code?