text:
Q: Can a scrollController.animateTo be cancelled or interrupted in the middle of its scroll? Can a scrollController.animateTo be cancelled or interrupted in the middle of its scroll?
For example, lets say I have a  listview  and I want to  animateTo  the bottom over the course of 10 seconds:
_scrollController.animateTo
(
   _scrollController.position.maxScrollExtent,
    duration: Duration(seconds: 10),
    curve: Curves.linear
);

But 5 seconds into this, some event occurs, say a state change, so I want to immediately cancel the scroll wherever it happens to be.  Is this possible?

A: I'm not sure if there is a better solution but this seems to work.
You can call animateTo again, except with the current position as the destination, and 0 seconds as the duration.
You can try with this demo below:
import 'package:flutter/material.dart';

void main() {
  runApp(
    const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: ScrollDemoWidget(),
    ),
  );
}

class ScrollDemoWidget extends StatefulWidget {
  const ScrollDemoWidget({Key? key}) : super(key: key);

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

class _ScrollDemoWidgetState extends State<ScrollDemoWidget> {
  final ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Scroll Demo'),
        actions: [
          IconButton(
            icon: const Icon(Icons.arrow_upward),
            onPressed: () {
              double current = _scrollController.position.pixels;
              double extent = _scrollController.position.maxScrollExtent;
              double millis = 10 * 1000 * (current / extent);

              _scrollController.animateTo(0,
                  duration: Duration(milliseconds: millis.round()),
                  curve: Curves.linear);
            },
          ),
          IconButton(
            icon: const Icon(Icons.arrow_downward),
            onPressed: () {
              double current = _scrollController.position.pixels;
              double extent = _scrollController.position.maxScrollExtent;
              double millis = 10 * 1000 * (1 - (current / extent));

              _scrollController.animateTo(
                  _scrollController.position.maxScrollExtent,
                  duration: Duration(milliseconds: millis.round()),
                  curve: Curves.linear);
            },
          ),
          IconButton(
            icon: const Icon(Icons.stop),
            onPressed: () {
              _scrollController.animateTo(_scrollController.position.pixels,
                  duration: const Duration(seconds: 0), curve: Curves.linear);
            },
          ),
        ],
      ),
      body: ListView.builder(
        controller: _scrollController,
        itemCount: 100,
        itemBuilder: (context, i) => ListTile(title: Text('Tile $i')),
      ),
    );
  }
}


text:
Q: cannot resolve error. Missing a jar file? import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.HapiContext;

I'm getting a cannot resolve error for the above two lines. I don't know why, when I have all the jar files in my project. I'm just starting out using the hapi api so I might be missing something pretty easy to spot.

A: What version of HAPI do you (intend to) use? HapiContext and its implementation are only available starting as of HAPI 2.1-beta1. Probably you have an older HAPI version in your classpath.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ClickOnce download timeout issue Hope you might have come across the ClickOnce download timeout issue.
The download just stops at a point (where it tries to download a .deploy file of >2MB)
and throws the timeout error.
Any ideas on resolving this?

A: Check your network speed, your network connections, and talk to whoever is hosting your application. You can run fiddler and see the files coming across. This is not a ClickOnce problem, it is a network issue.


text:
Q: List of 10 rectangles, meant to draw every one, only draws one So I have a program that's supposed to append 10 instances of a class named Rectangle which creates random properties for the rectangle.
If I print multiple objects from the list, they appear as different values, but if I call the draw function I have for multiple, only one appears on the screen.
Here is the entire code: http://pastebin.com/hb6LBjss
The important bits of code here are these, the first is the rectangle class, the second appends a rectangle to an empty list 10 times, the third is in the main program loop and is supposed to draw all 10.
Thanks.
1.
class Rectangle():
    x = random.randrange(0, 701)
    y = random.randrange(0, 501)
    width = random.randrange(20,71)
    height = random.randrange(20,71)
    change_x = random.randrange(-3,4)
    change_y = random.randrange(-3,4)
    def move(self):
        self.x += self.change_x
        self.y += self.change_y
    def draw(self):
        pygame.draw.rect(screen, green, [self.x,self.y, self.width, self.height], 0)

2.
myList = []

for i in range(10):
    myList.append(Rectangle())

3.
for i in myList:
    i.draw()

I've tried a whole bunch of different things such as this but every time there's just one rectangle on the screen.
for i in range(10):
    x = myList[i]
    x.draw()

A: You are in fact drawing 10 rectangles, but they are all the same one.
You have not passed instances of your rectangle class to be drawn, but the class itself.
It is an easy fix.
class Rectangle():
    x = random.randrange(0, 701)
    y = random.randrange(0, 501)
    width = random.randrange(20,71)
    height = random.randrange(20,71)
    change_x = random.randrange(-3,4)
    change_y = random.randrange(-3,4)
    def move(self):
        self.x += self.change_x
        self.y += self.change_y
    def draw(self):
        pygame.draw.rect(screen, green, [self.x,self.y, self.width, self.height], 0)

Becomes:
class Rectangle():
    def __init__(self):
        self.x = random.randrange(0, 701)
        self.y = random.randrange(0, 501)
        self.width = random.randrange(20,71)
        self.height = random.randrange(20,71)
        self.change_x = random.randrange(-3,4)
        self.change_y = random.randrange(-3,4)

    def move(self):
        self.x += self.change_x
        self.y += self.change_y

    def draw(self):
        pygame.draw.rect(screen, green, [self.x, self.y, self.width, self.height], 0)

The init method is called when you construct an instance of an object, by default, this does nothing. Since you wrote all those variables/members into the base class, as opposed to an initializer, then every instance of the class had the same values for all variables/members, since they became class members, not instance members...


text:
Q: Same charset html and sql but errors in this example I'm working with html, php and sql. There is an SQL table with a field that is "utf8_unicode_ci". I want to put this field wich contains html code and italian text, but could be chinese or russian into an html page that is displayed by browsers.
Into the html page there is this:
<meta charset="utf-8">

The problem is that the text is displayed with some strange  charachters, can you help me please?

A: Do you set utf-8 on mysql connection? After connecting, execute this query: set names 'utf8'

A: Verifique a configuração do conexão no arquivo app/config/database.php
    public $default = array(
        'datasource' => 'Database/Mysql',
        'persistent' => false,
        'host' => 'localhost',
        'login' => 'root',
        'password' => '12345',
        'database' => 'myDb',
        'encoding' => 'utf8'
  );

Also check the configuration of the table and field that can be configured with another charset


text:
Q: Compare two list in javers I have a question regarding list comparator. I have a web application which have page with table.
I can edit data in this table and also delete row.
Standard comparator working correct when i edit data but i have problem when i remove row.
The problem is common (i think) when i remove e.g one row what is happening
javers comparing old list with now one it's looks something like this:
old list have two object now list have one object (i removed first one) now javers don't know which object
was removed and he compare first object from old list with second object from new list and for him
whole object was changed and that is not true.
My thought was I will wrote own list comparator and in this comparator before javers compare method will be colled
i check if comparing objects have the same ID.
Unfortunately i have problem to obtain object ID.
My comparator looks like this
public class ListComperator implements CustomPropertyComparator {

public ValueChange compare(List list1, List list2, GlobalId globalId, Property property) {

    for (Object o1 : list1) {

        for (Object o2 : list2) {
            if(o1.getId().equals(o2.getId()) )  {
                javers.compare(o1, o2);
            }
        }

    }}}

The second list "list2" have my object from which i can get any property e.g ID.
The firs list "list1" is list with some ValueObjectId and i don't know how to get property with id from object o1.
Is there a way to get this information or maybe i'm doing something totally wrong please help.

A: I suppose that you have ValueObjects stored in those Lists? Since ValueObjects has no identifiers, there is no way to detect how they 'move' between List indexes when List is changed. Custom comparator won't help much without a
way to identify you objects.
I suggest to add some kind of identifiers to your objects stored in a List and map them as Entities (use @Id annotation).


text:
Q: ASP.Net MVC Ajax call that returns JsonResult I'm starting to learn ASP.Net MVC (the release candidate), and I'm having a little trouble. I might just be being picky, but I thought I'd ask.
I want to use the built-in (extended) ASP.Net Ajax methods to make a call to my controller, called "GetNames," that returns a JsonResult object. I've seen examples that use the $.getJSON() jQuery method, but I would instead prefer to do something like this:
 <%using ( Ajax.BeginForm("GetNames", new AjaxOptions() { OnSuccess = "GetNamesSuccess", OnBegin = "GetNamesBegin", OnComplete = "GetNamesComplte", OnFailure = "GetNamesFailure" } ) ) { %>

    <%=Html.TextBox("DummyData") %>
    <input type=submit />

<% } %>

<script type="text/javascript">
    function GetNamesSuccess()
    {
        alert("Success");
    }

    function GetNamesBegin()
    {
        alert("Begin");
    }

    function GetNamesComplete()
    {
        alert("Complete");
    }

    function GetNamesFailure()
    {
        alert("Failure");
    }
</script>

When I click the Submit button, I get none of the alerts, and I get prompted to download a file containing the text of Json object, which I believe indicates that at least the controller method is working fine. But that's not the intended behavior for me... Ideally, Ajax.BeginForm would set it up such that the Json object would get passed to either the OnSuccess or the OnComplete method.
Is there a way to accomplish that?

A: Have you included both the MicrosoftAjax.js and MicrosoftMvcAjax.js javascript files in your view page?  It sounds to me like it is actually posting the form instead of using Ajax.  I've had this problem when I was missing the MicrosoftAjax.js include because the Ajax postback failed due to missing javascript classes and thus it invoked the normal form post.
On a related note, you should check to see if the request is Ajax or not in the controller and return a ViewResult (or Redirect) instead of Json if it's not.  If someone has javascript turned off or you have errors on your page you want it to gracefully degrade and handle it as a normal postback rather than return Json.


text:
Q: Spark Structured Stream Executors weird behavior Using Spark Structured Stream, with Cloudera solution
I'm using 3 executors but when I launch the application the executor that is used it's only one.
How can I use multiple executors?
Let me give you more infos.
This is my parameters:
Command Launch:
spark2-submit --master yarn \
--deploy-mode cluster \
--conf spark.ui.port=4042 \
--conf spark.eventLog.enabled=false \
--conf spark.dynamicAllocation.enabled=false \
--conf spark.streaming.backpressure.enabled=true \
--conf spark.streaming.kafka.consumer.poll.ms=512 \
--num-executors 3 \
--executor-cores 3 \
--executor-memory 2g \
--jars /data/test/spark-avro_2.11-3.2.0.jar,/data/test/spark-streaming-kafka-0-10_2.11-2.1.0.cloudera1.jar,/data/test/spark-sql-kafka-0-10_2.11-2.1.0.cloudera1.jar \
--class com.test.Hello /data/test/Hello.jar

The Code:
val lines = spark
      .readStream
      .format("kafka")
      .option("kafka.bootstrap.servers", <topic_list:9092>)
      .option("subscribe", <topic_name>)
      .option("group.id", <consumer_group_id>)
      .load()
      .select($"value".as[Array[Byte]], $"timestamp")
      .map((c) => { .... })

val query = lines
      .writeStream
      .format("csv")
      .option("path", <outputPath>)
      .option("checkpointLocation", <checkpointLocationPath>)
      .start()
query.awaitTermination()

Result in SparkUI:
SparkUI Image
What i expected that all executors were working.
Any suggestions?
Thank you
Paolo

A: Looks like there is nothing wrong in your configuration, it's just the partitions that you are using might be just one. You need to increase the partitions in your kafka producer. Usually, the partitions are around 3-4 times the number of executors.
If you don't want to touch the producer code, you can come around this by doing repartition(3) before you apply the map method, so every executor works on it's own logical partition.
If you still want you explicitly mention the work each executor gets, you could do mapPerPartion method.


text:
Q: Typescript - React Native: There is way to save switch button state? There is way to save switch button state with asyncstorage ?
My goal is that when the user clicks on the switcher, then its state will be preserved even when the user exits the application and returns back.
import { View, Text, Switch } from 'react-native';
import React from 'react';
import styles from './ViewFieldStyles';

type Props = {
  title: string;
  value: boolean;
  setValue: () => void;
};

const ViewField = ({ title, value, setValue }: Props) => {
  return (
    <View style={styles.optionView}>
      <View style={styles.sameRowTextView}>
        <Text style={styles.optionText}>{title}</Text>
        <View style={styles.switchView}>
          <Switch
            trackColor={{ false: '#767577', true: 'rgba(4, 76, 163, 0.38)' }}
            thumbColor={value ? '#1d16db' : '#f4f3f4'}
            ios_backgroundColor='#3e3e3e'
            onValueChange={setValue}
            value={value}
          />
        </View>
      </View>
    </View>
  );
};

export default ViewField;

A: You can easily do that using AsyncStorage.
Below is an example.
Install and import module.
import AsyncStorage from '@react-native-async-storage/async-storage';

Then use it like below.
<Switch
  trackColor={{false: theme.negative, true: theme.positive}}
  onValueChange={(result) => {
    AsyncStorage.setItem(
      AsyncStorageKey.DarkMode,
      JSON.stringify(result),
    );
    changeThemeType(result ? 'dark' : 'light');
    setIsDarkMode(result);
  }}
  value={isDarkMode}
/>

To get the value when component loads,
const [isDarkMode, setIsDarkMode] = useState(false);

useEffect(() => {
  const setDarkMode = async (): Promise<void> => {
    const result = JSON.parse(
      (await AsyncStorage.getItem('IS_DARK')) || 'false',
    ) as boolean;

    setIsDarkMode(result);
  };

  setDarkMode();
}, []);


text:
Q: ¿Como funciona strcmp en PHP? Quisiera saber como funciona strcmp en PHP, ya que tengo una duda en cuanto al resultado que arroja, se que cuando se compara y son igualas dara como resultado 0, pero en otros casos el resultado varia un poco (1,-1,5,45 etc.), cuales serian algunos ejemplos en el que varien los resultados con una breve explicacion.
<?php

    $variable1 = "walter";
    $variable2 = "Alejandro";

    $resultado = strcmp($variable1, $variable2);
    var_dump($resultado);

?>

A: Como bien lo indica la documentacion de PHP:

Comparación de string segura a nivel binario

Que significa esto?
La comparacion que se realice, tendra en cuenta diferentes elementos que puedan variar de una cadena a la otra, desde un espacio hasta una mayuscula.
¿Como podemos evidenciar ello?
He aqui un ejemplo:
<?php

$cadena = "hola mundo";

$cadena_A = "hola";
$cadena_B = "hola mundo";
$cadena_C = "hola mundo cruel";

if(strcmp($cadena_A, $cadena) < 0){
        print "$cadena_A es menor que $cadena\n";
}

if(strcmp($cadena_B, $cadena) == 0){
        print "$cadena_A es igual que $cadena\n";
}

if(strcmp($cadena_C, $cadena) > 0){
        print "$cadena_A es mayor que $cadena\n";
}

?>

Si ejecutamos el programa, el resultado sera:
hola es menor que hola mundo
hola es igual que hola mundo
hola es mayor que hola mundo

¿Porque nos devolvio ese resultado?
Como lo indica la documentacion de PHP:

Devuelve < 0 si str1 es menor que str2; > 0 si str1 es mayor que str2
  y 0 si son iguales.

¿Que quiere decir?
Se hace una diferencia entre las dos cadenas, indicando un valor, que variara si la una tiene mas o menos texto que la otra cadena contra la que se compara.


text:
Q: Flutter: Mapbox onMapCreated not called in widget test I'm using the Mapbox map and when I run the app in an emulator, it works fine. However, in my widget test, the onMapCreated method is never called, which makes it impossible to test the behavior of the app.
My MapWidget (condensed):
class MapWidget extends StatefulWidget {
  final LatLng initialCameraPositionCoordinates;
  final double initialZoomLevel;

  const MapWidget({
    Key key,
    @required this.initialCameraPositionCoordinates,
    @required this.initialZoomLevel,
   }) : super(key: key);

  @override
  State createState() => MapWidgetState();
}

class MapWidgetState extends State<MapWidget> {
  @override
  Widget build(BuildContext context) {
    return BlocConsumer<Cubit, State>(
      builder: (context, state) {
        return MouseRegion(
          cursor: MouseCursor.defer,
          child: MapboxMap(
            onMapCreated: _onMapCreated,
          ),
        );
      },
    );
}

void _onMapCreated(MapboxMapController controller) async {
    print("This is never called in the test");
}

And the corresponding widget test looks like this:
void main() {
    testWidgets("Mapbox", (WidgetTester tester) async {
        await tester.pumpWidget(
          BlocProvider(
            create: (_) => _cubit,
            child: MaterialApp(
              home: MapWidget(
                initialCameraPositionCoordinates:
                    _initialCameraPositionCorrdinates,
                initialZoomLevel: _initialZoomLevel,
              ),
            ),
          ),
        );
        await tester.pump(Duration(seconds: 10));
      });
}

No exception is thrown, meaning it renders fine. However, the print statement in the onMapCreated is never printed.
Running the app in an emulator, the print statement is called.
Does anyone have an idea what's going on here?

A: I ran into the same issue, and worked around it by manually invoking the callbacks. Something like this in your widget test:
var mapboxMap = tester.firstWidget(find.byType(MapboxMap)) as MapboxMap;
mapboxMap.onMapCreated!(<mocked controller>);
mapboxMap.onStyleLoadedCallback!();

Where "<mocked controller" is an instance of your MapboxMapController mock.
I imagine the underlying issue has to do with the native map view not actually being loaded during widget tests, and therefore, no callbacks are invoked.


text:
Q: Why is my TabHost's FrameLayout's only child loaded with visibility = View.GONE? I'm using a TabHost to render some tabs. In the XML definition everything is set up ~normally, a RelativeLayout is the only child of the FrameLayout for the TabHost.
Weirdly, that relative layout always loads up as View.GONE. Setting the RelativeLayout's visibiltiy in the XML file does not change this. Calling .setVisibility during onCreate to manually make that RelativeLayout visible works, but feels wrong. Switching between tabs also makes the RelativeLayout visible again.
Am I missing something fundamental? Is it normal to hand-specify tabs as XML children of the FrameLayout?

A: I ended up spending some time reading TabHost.java and discovered what was happening.

*

*TabHost.java (naively IMO ;) ) assumes that different tabs are attached to different content views.

*Every time a content view is added to a TabSpec the visibility of the view is set to GONE.

*Every time a TabSpec is added to the TabHost, the TabHost switches to tab 0.

*Every time setCurrentTab is called the visibility of the View of that tab is set to VISIBLE if and only if the newly selected tab is not the current tab.
When a bunch of tabs are added for the same view:

*

*first the view is added and its visibility is set to GONE,

*then the TabHost switches to tab 0 and sets the view's vis to VISIBLE,

*then the next tab is added and its view (the same view!) has its vis set to GONE,

*then the TabHost switches to tab 0 which is a ~noop because tab 0 was previously selected so the view isn't switched back to VISIBLE.

So this was caused by using the same view for the content of multiple tabs.
So, to fix this call: tabHost.getCurrentView().setVisibility(View.VISIBLE); ... after adding all the tabs


text:
Q: Wildcard for string before @ character How would I use a wildcard to filter out any permutation of the following. There can be any number of zeros before the "@" character.
Example
   0@test.com
   000000@test.com
   00000000000@test.com

Basically, I'm looking to wildcard any email address with only zeros before the @ character.
Any help would be greatly appreciated
Thank you !
Smiddy

A: T-SQL:
To remove all values with only zeros before the @
SELECT
    *
FROM (SELECT  '000@test.com' AS[values]  ) [table]
WHERE
    LEN(REPLACE((LEFT([values],CHARINDEX('@',[Values])-1)),'0',''))  <> 0

-- LEFT & CHARINDEX    : get the result LEFT of the @
-- LEN & REPLACE        : After all 0 are replaced by '' any email that contained only zeros will result in len = 0.

A: I would solve it with a regular expression, but the concrete answer depends on your database vendor and the available syntax.

*

*PostgreSQL:
SELECT * FROM table WHERE email ~ '^0+@'

*MySQL:
SELECT * FROM table WHERE email REGEXP '^0+@'

Synonyms are email RLIKE '^0+@' and REGEXP_LIKE(email, '^0+@').

*Oracle:
SELECT * FROM table WHERE REGEXP_LIKE(email, '^0+@')


text:
Q: How can I deploy a Spring Boot REST API to BanaHost cPanel? I created a full stack application (Angular front end, java spring boot back end, mysql database), and I was able to upload successfully both the angular files and mysql into BanaHost cPanel, however I have not found useful information on how to upload spring boot REST API, as a consequence only the front end is working. How can I deploy this REST API on cpanel?

A: Spring Boot Applications can't just upload and deploy if you're utilizing a cPanel Web hosting (shared) plan, like you deployed the Angular Application by uploading.
For spring boot you must do it yourself, a Virtual Private Server or Dedicated Server will unlock the site hosting restriction. If you are not much familiar with the Linux command line, you can use a Window VPS instead. Providers like, Digital Ocean, Linode, and Oracle Cloud all provide free trials.
And also, there are platforms, such as Heroku (Platform as a Service(PaSS)), where you can deploy your app without the need for a VPS. You can refer their documentation regarding this:
https://devcenter.heroku.com/articles/deploying-spring-boot-apps-to-heroku


text:
Q: Text widget not updating inside StreamBuilder I am getting a QuerySnapShot from a Firestore subcollection inside a StreamBuilder from another query, as follows:
  //ver fuegos
                              var estePost = listaFiltrada[indexPost].post_id;
                              int numero_fuegos = 0;
                              FirebaseFirestore.instance
                                  .collection('posts')
                                  .doc(estePost)
                                  .collection('fuegos')
                                  .get()
                                  .then((value) => {
                                        if (value.size > 0)
                                          {
                                            setState(() {
                                              numero_fuegos = value.size;
                                            }),
                                            print("tiene fuegos: " +
                                                numero_fuegos.toString()),
                                          }
                                        else
                                          {
                                            setState(() {
                                              numero_fuegos = value.size;
                                            }),
                                          }
                                  });

There are 3 items for value.size.
Here you have the print output:
 I/flutter (29797): tiene fuegos: 3

The issue is that putting the variable numero_fuegos inside a text widget, the output is always 0.

EDIT:
class ListaPosts extends StatefulWidget {
  @override
  _ListaPostsState createState() => _ListaPostsState();
}

class _ListaPostsState extends State<ListaPosts> {
  String _miId = "";

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

    FirebaseAuth.instance.idTokenChanges().listen((User user) {
      if (user == null) {
      } else {
        setState(() {
          _miId = user.uid;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    final postsProvider = Provider.of<PostsProvider>(context);

    return Container(
      color: Colors.transparent,
      child: Padding(
        padding: const EdgeInsets.only(top: 0.0),
        child: Column(
          children: [
            StreamBuilder<List<Post>>(
                stream: postsProvider.posts,
                builder: (context, snapshot) {
                  if (snapshot.data != null &&
                      snapshot.data.isNotEmpty &&
                      ConnectionState.done != null) {
                    List<Post> listaInicial = snapshot.data;
                    List<Post> listaFiltrada = [];
                    listaFiltrada = listaInicial;

                    return Padding(
                      padding: const EdgeInsets.all(0.0),
                      child: SizedBox(
                        width: MediaQuery.of(context).size.width,
                        height: MediaQuery.of(context).size.height - 140,
                        child: ListView.builder(
                            itemCount: listaFiltrada.length,
                            itemBuilder: (context, indexPost) {
                              bool es_ambassador = listaFiltrada[indexPost]
                                  .post_autor_is_ambassador;

                              //ver fuegos
                              var estePost = listaFiltrada[indexPost].post_id;
                              int numero_fuegos = 0;
                              FirebaseFirestore.instance
                                  .collection('posts')
                                  .doc(estePost)
                                  .collection('fuegos')
                                  .get()
                                  .then((value) => {
                                        if (value.size > 0)
                                          {

                                              numero_fuegos = value.size,

                                            print("tiene fuegos: " +
                                                numero_fuegos.toString()),
                                            print("tiene fuegos: " +
                                                value.size.toString()),
                                          }
                                        else
                                          {
                                            setState(() {
                                              numero_fuegos = value.size;
                                            }),
                                          }
                                      });

And that is the Stream:
  //Get Posts Entries
  Stream<List<Post>> getPosts() {
    return _db
        .collection('posts')
        .orderBy("post_fecha", descending: true)
        .snapshots()
        .map((snapshot) =>
            snapshot.docs.map((doc) => Post.fromJson(doc.data())).toList());
  }


text:
Q: pass a cookie in angular component I am creating an angular app that sits under iframe in .net application. I need to pass some data from .net application so angular app can do api calls as per requirements. How can I pass this data (such as a cookie or string value) from aspx page to angular component ?
one way to create cookie in .net code is
HttpContext.Current.Response.Cookies.Add(some_ cookie);

How can i access it in angular ? I tried using package 'angular2-cookie' like this but I always get some garbage value in angular.
this._cookieService.get(some_ cookie)

A: I've found the package of the link below very helpfull
https://www.npmjs.com/package/ngx-cookie-service
Stil... there are somethings you have to consider. The cookie you are creating on .net should have a name and a value. You must use the value to get this cookie in angular.
.NET
var some_cookie = new HttpCookie("cookie_name", "cookie_value");
HttpContext.Current.Response.Cookies.Add(some_cookie);

angular
this.cookieValue = this.cookieService.get('cookie_name');

The other thing you should consider is that both application must be in the same domain. Check the application tab on chrome developer tools when testing for help if this is the problem ;)


text:
Q: Removing a reaction on adding a reaction Hi I'm wanting to remove a reaction when another reaction is adeed. For example if user had reacted to emoji 1 but reacts to emoji 2 then emoji 1 is removed or if the user had react to emoji 1 but reacts to emoji 4 instead then emoji 1 is removed.
I'm using a async def on_raw_reaction_add(): event and defined the emojis I'd like to use however if I dide:
 await member.add_roles(role, reason='Added role')
        await message.remove_reaction(one, user)
        await message.remove_reaction(two, user)
        await message.remove_reaction(three, user)

This would remove all the emojis including the emoji the user selected.
Here is what I'm working with:
one = "1\N{COMBINING ENCLOSING KEYCAP}"
two = "2\N{COMBINING ENCLOSING KEYCAP}"
three = "3\N{COMBINING ENCLOSING KEYCAP}"

@commands.Cog.listener()
async def on_raw_reaction_add(self, payload):
    message_ids = [649600853048688642, ]
    channel = self.bot.get_channel(634023419482079232)
    message = await channel.fetch_message(649600853048688642)
    user = self.bot.get_user(payload.user_id)
    if not payload.guild_id:
        return
    if payload.message_id not in message_ids:
        return
    guild = self.bot.get_guild(payload.guild_id)  # You need the guild to get the member who reacted
    member = guild.get_member(payload.user_id)  # Now you have the key part, the member who should receive the role
    restricted_role = discord.utils.get(guild.roles, name="Commands Revoked")
    role_name = emoji_role_map.get(payload.emoji.name)
    if restricted_role in member.roles:
        return
    if role_name:  # None if not found
        role = discord.utils.get(guild.roles, name=role_name)
        await member.add_roles(role, reason='Added role')
        await message.remove_reaction(one, user)
        await message.remove_reaction(two, user)
        await message.remove_reaction(three, user)

Help appreciated.


text:
Q: how to do text to speech using custom keyboard in IOS 8? I make a custom keyboard using this link
 https://developer.apple.com/library/ios/documentation/General/Conceptual/ExtensibilityPG/Keyboard.html
Now I need to add functionality of text to speech . In other word when ever user press key it speech that word .can you please tell me how it is possible .is it possible in IOS 8?

A: Have a look into following class available in ios7 onwards
AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:@"whatever text"];
AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];

[synth speakUtterance:utterance];

For more info please check apple's library document
AVSpeechSynthesizer
AVSpeechUtterance


text:
Q: Where is the IndexCounter in db.serverStatus() on MongoDB 3.0 I saw idx miss % in mongostat but when I run
db.serverStatus().indexCounters

there is no response. where can I find this? And One more question, what is the appropriate page fault value I should concern?

A: The indexCounters information was specific to MMAP storage and not entirely accurate (for some examples, see: SERVER-9296, SERVER-9284, and SERVER-14583). The indexCounters section was removed during the development cycle leading up to MongoDB 3.0 along with some other former metrics like recordStats and workingSet. See: SERVER-16378 and discussion on related issues in the MongoDB Jira issue tracker.
If you have enabled the WiredTiger storage engine, note that there will be a new wiredTiger section in the serverStatus() output with relevant metrics.

what is the appropriate page fault value I should concern?

Page faults provide a good proxy for whether your working set fits in memory with MMAP, but the specific value of concern will depend on your deployment and whether there is any noticeable performance impact. Consistently high hard page faults (where data needs to be loaded from disk to RAM) will add I/O pressure, but this may not be significant depending on your disk configuration and overall workload.
A general best practice is to use a monitoring system like MMS (MongoDB Management Service) to capture a historical baseline of metrics for your deployment so you can then look for pain points when performance problems are observed.
It's also worth reading the Production Notes section of the MongoDB manual. If you are using Linux, for example, there are some suggestions on tuning file system and readahead parameters that can affect the efficiency of reading data from disk.
For an idea of how to approach metrics, see: Five MMS monitoring alerts to keep your MongoDB deployment on track. This blog post is a few years old but the general approach of determining normal, worrying, and critical limits (as well as identifying false positives) is still very relevant.


text:
Q: Component Exception: undefined is not an object (evaluating 'item[0].items.created') I want to render the news from the States.js file with having the data like below -
const StateNewsJSON = {
   "items": [
      {
         "title": "Man in poll position",
         "description": "   Man in poll position",
         "url": "https://www.indiatoday.in/magazine/states/story/20201123-man-in-poll-position-1740686-2020-11-13?utm_source=rss",
         "link": "https://www.indiatoday.in/magazine/states/story/20201123-man-in-poll-position-1740686-2020-11-13?utm_source=rss",
         "created": 1605289389000,
         "category": [],
         "content": null,
         "enclosures": []
      },
      {
         "title": "The CM vs. the judges",
         "description": "   The CM vs. the judges",
         "url": "https://www.indiatoday.in/magazine/states/story/20201102-the-cm-vs-the-judges-1734176-2020-10-23?utm_source=rss",
         "link": "https://www.indiatoday.in/magazine/states/story/20201102-the-cm-vs-the-judges-1734176-2020-10-23?utm_source=rss",
         "created": 1603435891000,
         "category": [],
         "content": null,
         "enclosures": []
      },
      {
         "title": "Whiff of a third front",
         "description": "   Whiff of a third front",
         "url": "https://www.indiatoday.in/magazine/states/story/20201102-whiff-of-a-third-front-1734179-2020-10-23?utm_source=rss",
         "link": "https://www.indiatoday.in/magazine/states/story/20201102-whiff-of-a-third-front-1734179-2020-10-23?utm_source=rss",
         "created": 1603423936000,
         "category": [],
         "content": null,
         "enclosures": []
      },
      {
         "title": "A grim battle ahead",
         "description": "   A grim battle ahead",
         "url": "https://www.indiatoday.in/magazine/states/story/20201102-a-grim-battle-ahead-1734181-2020-10-23?utm_source=rss",
         "link": "https://www.indiatoday.in/magazine/states/story/20201102-a-grim-battle-ahead-1734181-2020-10-23?utm_source=rss",
         "created": 1603421691000,
         "category": [],
         "content": null,
         "enclosures": []
      },
      {
         "title": "Mamata goes to war",
         "description": "   Mamata goes to war",
         "url": "https://www.indiatoday.in/magazine/states/story/20201019-mamata-goes-to-war-1729907-2020-10-10?utm_source=rss",
         "link": "https://www.indiatoday.in/magazine/states/story/20201019-mamata-goes-to-war-1729907-2020-10-10?utm_source=rss",
         "created": 1602298764000,
         "category": [],
         "content": null,
         "enclosures": []
      },
      {
         "title": "Delhi HC suspends life term of woman who murdered stepson, asks her to do social service",
         "description": "   Delhi HC suspends life term of woman who murdered stepson, asks her to do social service",
         "url": "https://www.indiatoday.in/india/story/delhi-high-court-suspends-life-sentence-woman-murder-social-service-1729109-2020-10-07?utm_source=rss",
         "link": "https://www.indiatoday.in/india/story/delhi-high-court-suspends-life-sentence-woman-murder-social-service-1729109-2020-10-07?utm_source=rss",
         "created": 1602043793000,
         "category": [],
         "content": null,
         "enclosures": []
      },
      {
         "title": "Brutal, diabolic crime deserves harshest punishment: Delhi man gets death for murder of 12-year-old boy",
         "description": "   Delhi: Man awarded death penalty for brutal murder of 12-year-old boy",
         "url": "https://www.indiatoday.in/crime/story/death-penalty-child-murder-kidnapping-1729090-2020-10-07?utm_source=rss",
         "link": "https://www.indiatoday.in/crime/story/death-penalty-child-murder-kidnapping-1729090-2020-10-07?utm_source=rss",
         "created": 1602039195000,
         "category": [],
         "content": null,
         "enclosures": []
      },
      {
         "title": "The battle of alliances",
         "description": "   The battle of alliances",
         "url": "https://www.indiatoday.in/magazine/states/story/20200928-the-battle-of-alliances-1723087-2020-09-19?utm_source=rss",
         "link": "https://www.indiatoday.in/magazine/states/story/20200928-the-battle-of-alliances-1723087-2020-09-19?utm_source=rss",
         "created": 1600489646000,
         "category": [],
         "content": null,
         "enclosures": []
      },
      {
         "title": "Prince of Trinamool",
         "description": "   Prince of Trinamool",
         "url": "https://www.indiatoday.in/magazine/states/story/20200921-prince-of-trinamool-1720876-2020-09-12?utm_source=rss",
         "link": "https://www.indiatoday.in/magazine/states/story/20200921-prince-of-trinamool-1720876-2020-09-12?utm_source=rss",
         "created": 1599886507000,
         "category": [],
         "content": null,
         "enclosures": []
      }
   ],
   "title": "India Today | States",
   "description": "India Today",
   "link": "http://indiatoday.intoday.in/?utm_source=rss",
   "category": [],
   "image": "https://www.indiatoday.in/sites/all/themes/itg/logo.png"
}

export const StateNewsData = Object.keys(StateNewsJSON).map(key => ({
   key,
   ...StateNewsJSON[key]
}))

I'm trying to render the data in the StateNews.js like below -
import React, { Component } from 'react'
import { View, Text, FlatList, TouchableHighlight } from 'react-native'
import { StateNewsData } from "../../../../assects/JSON/States"

class StateNews extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  renderStateNews = ({ item }) => {
    return (
      <TouchableHighlight>
        <View>
          <Text>{ item[0].items.title}</Text>
        </View>
      </TouchableHighlight>
    )
  }

  render() {
    return (
      <View>
        <FlatList
        data={StateNewsData}
        renderItem={this.renderStateNews}
        numColumns={2}
        keyExtractor={(item) => item[0].items.created}
      />
      </View>
    )
  }
}

export default StateNews

But when I'm navigating to the specific component in the app it shows the above error. I wonder I'm missing a silly problem. I have checked the documentation to see if I made any errors, but I could not find any. Can anyone help me out in this case?
I'm also attaching the URL of the screenshot of my error for further reference -
screenshot of my app with error

A:     const StateNewsData = StateNewsJSON.items;
  return (
    <View style={styles.app}>
      <FlatList
        data={StateNewsData}
        renderItem={({item}) => <Text>{item.title}</Text>}
      />
    </View>
  );
};

I did some modifications in the code. Please put console for your array length.


text:
Q: wxPython Frame disable/enable? I have created a wx.Frame(lets call it mainFrame). This frame contains a button on it, when the button is clicked, a new frame(lets call it childFrame) is created.
I want to know that how to disable the mainFrame when childFrame is created and enable the mainFrame again when childFrame distroyed/closed?
Regars,

A: May be you do not need another frame but a modal dialog e.g.
import wx

app = wx.PySimpleApp()
mainFrame = wx.Frame(None, title="Click inside me")
def onMouseUp(event):
    dlg = wx.Dialog(mainFrame,title="I am modal, close me first to get to main frame")
    dlg.ShowModal()

mainFrame.Bind(wx.EVT_LEFT_UP, onMouseUp)
mainFrame.Show()
app.SetTopWindow(mainFrame)
app.MainLoop()

A: May be you want something like this:

import wx

class MainFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, wx.NewId(), "Main")
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.button = wx.Button(self, wx.NewId(), "Open a child")
        self.sizer.Add(self.button, proportion=0, border=2, flag=wx.ALL)
        self.SetSizer(self.sizer)
        self.button.Bind(wx.EVT_BUTTON, self.on_button)

        self.Layout()

    def on_button(self, evt):
        frame = ChildFrame(self)
        frame.Show(True)
        frame.MakeModal(True)

class ChildFrame(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent, wx.NewId(), "Child")
        self.Bind(wx.EVT_CLOSE, self.on_close)

    def on_close(self, evt):
        self.MakeModal(False)
        evt.Skip()

class MyApp(wx.App):
    def OnInit(self):
        frame = MainFrame()
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

app = MyApp(0)
app.MainLoop()


text:
Q: Angular 6 Error trying to diff '[object Object]'. Only arrays and iterables are allowed I think my Problem is that the API delivers an Object instead of an array. So i need to Modify the Object to be an Array ?
How could this be done ?
Object.assign ?
Or Pipe ?
Does anyone have a proper example ?
I'am still learning Angular this is my second Project so i need some help ;)
thy so far !
Here is my code
getting data from API
..cant change the API it delivers an Object
KnowledgeBaseService
    import {Injectable, OnInit} from '@angular/core';
    import { HttpClient, HttpErrorResponse, HttpHeaders, HttpRequest, HttpResponse} from '@angular/common/http';
    import {environment} from '../../environments/environment';
    import { WikiModel } from '../../models/wikiItems.model'
    import {catchError, map, take} from 'rxjs/operators';
    import {throwError} from 'rxjs';

    @Injectable()
    export class KnowledgeBaseService {
      wikiApiUrl: string = environment.wikiApiUrl;
      wikiList: WikiModel[] = [];
     constructor(

      protected http: HttpClient,) {}

        getwikiList() {
          return this.http.get(this.wikiApiUrl + "/list")
            .pipe(map((data: any[]) => {return this.wikiList = data;
                }), catchError(error => {
                return throwError('Its a Trap!')
              })
            );
        }
    }

subscribe to that Data
KnowledgeBaseAdminComponent
    import { Component, OnInit } from '@angular/core';
import { KnowledgeBaseService } from '../../../services/knowledge-base.service';
import { WikiModel } from '../../../../models/wikiItems.model';
import { map, take } from 'rxjs/operators';
import {keyframes} from '@angular/animations';

@Component({
  selector: 'app-knwoledge-center-admin',
  templateUrl: './knowledge-base-admin.component.html',
  styleUrls: ['./knowledge-base-admin.component.scss']
})
export class KnowledgeBaseAdminComponent implements OnInit {

  wikiList: WikiModel[] = [];
  displayDialog: boolean = false;
  editItem: WikiModel = null;

  constructor(private knowledgebaseService: KnowledgeBaseService) {

  }

  ngOnInit() {
    this.getwikiItems()
  }

  getwikiItems(): void {
    this.knowledgebaseService.getwikiList().subscribe(
      data => {
        this.wikiList = data
      },
      err => console.error(err),
      () => console.log('Wiki Items Geladen')
    );
    console.log(this.wikiList)
  }

  showDialogToAdd() {
    this.displayDialog = true;

  }  showDialogToEdit() {
    this.displayDialog = true;
  }
}

WikiModel
export class WikiModel {
  title: string;
  text: string;
  keyWords: string;

}

Template

      Begriffsdatenbank

               Begriff
               Beschreibung
               Schlagworte

               {{wikiItems.title}}
               {{wikiItems.text}}
               {{wikiItems.keyWords}}

        Titel

        <input pInputText id="wikiTitle" />

        Wiki Text

          <textarea id="wikiText" [rows]="5" [cols]="35" pInputTextarea ></textarea>

        Schlagwörter

        <input pInputText id="wikikeywords" />

Error

ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed

The Data from the API looks like:
{
  "error": null,
  "status": 200,
  "result": [
    {
      "_key": "338330",
      "_id": "knowbaseItems/338330",
      "_rev": "XIQvCoG--",
      "title": "Test Eintrag",
      "text": "Lalala",
      "keyWords": [
        "test"
      ]
    },
    {
      "_key": "341705",
      "_id": "knowbaseItems/341705",
      "_rev": "XIHSQhy--",
      "title": "Personalpronomen",
      "text": "Fahren Schlitten",
      "keyWords": [
        "ich",
        "du",
        "er"
      ]
    }
  ],
  "code": "200"
}

A: Keep in mind that Http is asynchronous. That means with this code:
  getwikiItems(): void {
    this.knowledgebaseService.getwikiList().subscribe(
      data => {
        this.wikiList = data
      },
      err => console.error(err),
      () => console.log('Wiki Items Geladen')
    );
    console.log(this.wikiList)  // <-- ALWAYS UNDEFINED!!
  }

The last console.log line will always be undefined.
The flow is as follows:
1) The getwikiList().subscribe is called.
2) The Http Get request is executed.
3) The getwikiList() method returns.
4) Your console.log is executed and the value is undefined at this point.
5) A response is received from the Get request.
6) The method defined within the subscribe method is notified and the data is provided and set to the this.wikilist.
So it is only after step 6 that you have the data.
If you want to see your values, you need to move your logging within the subscribe as shown below:
  getwikiItems(): void {
    this.knowledgebaseService.getwikiList().subscribe(
      data => {
        this.wikiList = data;
        console.log(this.wikiList); // <-- here instead
      },
      err => console.error(err),
      () => console.log('Wiki Items Geladen')
    );
  }

A: You can also do the below:
getwikiList() {
return this.http.get(this.wikiApiUrl + "/list")
        .pipe(map((data: any) => data.result || [];
            }), catchError(error => {
            return throwError('Its a Trap!')
          })
        );

It worked for me

A: In your service map operator must return data.result
getwikiList() {
 return this.http.get(this.wikiApiUrl + "/list")
            .pipe(map((data: any) => data.result ),
                  catchError(error => { return throwError('Its a Trap!')})
            );
}

Just update p-table like this

       <ng-template pTemplate="header">

           Begriff
           Beschreibung
           Schlagworte

       </ng-template>
       <ng-template pTemplate="body" let-wikiList>

           {{wikiList.title}}
           {{wikiList.text}}
           {{wikiList.keyWords}}

       </ng-template>

stackblitz example

A: Look careful with your data coming from your api.
If you use model class only those elements define in model class access.so make your you add data.result and then pass into another object
For e.g
this.wikiList = data.result
In html
ngFor = "let wikilist of wikiList"


text:
Q: Send one SMS to Multiple phone numbers I have an arraylist of phone numbers. When I send a message it only sends to the last number on the list. Here is my code.
public void onActivityResult(int requestCode,int resultCode,Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == CONTACT_PICK_REQUEST && resultCode == RESULT_OK){

        ArrayList<Contact> selectedContacts = data.getParcelableArrayListExtra("SelectedContacts");

        String display="";
        for(int i=0;i<selectedContacts.size();i++){
            display += (i+1)+"   "+selectedContacts.get(i).toString()+"\n";
            theNumber=selectedContacts.get(i).phone;
        }
        contactsDisplay.setText("Selected Contacts : \n\n"+display);
    }
}

protected void sendMsg(String theNumber, String myMsg) {
    String SENT = "Message Sent";
    String DELIVERED = "Message Delivered";

    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SENT), 0);
    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED), 0);

    registerReceiver(new BroadcastReceiver() {
        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode()) {
                case Activity.RESULT_OK:

                        Toast.makeText(MainActivity.this, "SMS SENT", Toast.LENGTH_LONG).show();
                    break;
                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                    Toast.makeText(MainActivity.this, "Generic Failure", Toast.LENGTH_LONG).show();
                    break;
                case SmsManager.RESULT_ERROR_NO_SERVICE:
                    Toast.makeText(MainActivity.this, "No Service", Toast.LENGTH_LONG).show();
                    break;
            }
        }
    }, new IntentFilter(SENT));

    registerReceiver(new BroadcastReceiver() {

        public void onReceive(Context arg0, Intent arg1) {
            switch (getResultCode()) {
                case Activity.RESULT_OK:
                    Toast.makeText(getBaseContext(), "SMS delivered", Toast.LENGTH_LONG).show();
                    break;
                case Activity.RESULT_CANCELED:
                    Toast.makeText(getBaseContext(), "SMS not delivered", Toast.LENGTH_LONG).show();
                    break;
            }

        }
    }, new IntentFilter(DELIVERED));

    SmsManager sms = SmsManager.getDefault();
    sms.sendTextMessage(theNumber, null, myMsg, sentPI, deliveredPI);
}

A: Your loop is simply replacing the numbers from the list to theNumber variable.
theNumber=selectedContacts.get(i).phone;

When the loop ends, it finds the variable theNumber updated with last number from the list.


text:
Q: Local Node.js server consistently fails to connect to AWS RDS database I have setup a RDS instance on my AWS account with the following configuration:
Engine: MySQL Community
Class: db.t3.small
Region: us-east-2b

Sometimes for testing I need to connect to the DB from my local node application which I am running from India. I am using Sequelize as my ORM. Before accessing my DB I make sure my IP is whitelisted in the RDS security group so my local server can access the db.
However in first few attempts I always keep getting the following error:
(node:7768) UnhandledPromiseRejectionWarning: SequelizeConnectionError: connect ETIMEDOUT
    at ConnectionManager.connect (C:\Projects\my-app\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:126:17)
    at processTicksAndRejections (internal/process/task_queues.js:93:5)
    at async ConnectionManager._connect (C:\Projects\my-app\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:318:24)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:7768) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:7768) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

My sequelize db configuration looks like this:
const Sequelize = require('sequelize');
const Op = Sequelize.Op;

const sequelize = new Sequelize(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASSWORD, {
    host: process.env.DB_HOST,
    port: 3306,
    dialect: 'mysql',
    pool: {
        max: 10,
        min: 0,
        acquire: 30000,
        idle: 10000
    },
    logging: false
});

The thing is after couple of attempts (say 3-4) of restarting the server it finally connects, only to do the same thing when the server is restarted (when I make any changes). Its frustrating to keep doing this and takes me a long time to test something small locally.
Any idea on why this might be happening? Is it my instance class (since its t3 small) or something in my sequelize configuration? I understand that I am accessing a database server setup in the north american continent all the way from asia but it shouldn't be this bad that I have keep restarting and trying many times to finally be able to connect to it.
Any suggestions to mitigate the problem will be very much appreciated.
Thank you.

A: Why are you connecting a db in us region from asia region? the network latency can be an issue of unstable app<->db connectivity and you surely don't want to do this in production, even in dev environment thats not desirable as it will affect your debugging speed. Try using all the same config and use a EC2 in us region (same region as your db) , and see if things work first.


text:
Q: Multithreaded Observer Pattern I have a question where a subject is updated in a different thread every time. So whenever the subject is updated it correspondingly updates the observer with the new information. However, if the list of observers is long, it will require some time to update all the observers. Think of a subject that gets updated very frequently. While the subject is updating the observers, "subject" object is locked and hence cannot be updated by a different thread. This will either create information traffic for subject or cause loss of information.
Do you have any idea how these issues are handled in a multi-threaded environment? Also, Can anyone recommend some books on parallel programming with C++?

A: Consider the use of producer-consumer queues or message queues. For your example, you can use a queue in two ways:

*

*Changes to the Subject are queued. When something updates the subject, it puts the new state in the queue and returns immediately. This way, the updater does not block while the observers are notified. You will need a thread that continuously dequeues state changes and updates observers.

*Notifications to Observers are queued. Each observer has a queue where subject state-change notifications are posted.
If you are using the Qt library, you can use the signals & slots mechanism with the Qt::QueuedConnection connection type. The slot goes through the receiver's event queue and is executed in the receiver's thread. This way, the sender does not block while the receivers execute their respective slots.
Your program might be a good candidate for the Actor model (paradigm). Here are some C++ libraries that implement the actor model:

*

*Theron

*libcppa (C++11 based)

*Asynchronous Agents Library (Microsoft)

Your program might also be a good candidate for the Dataflow paradigm. Check out the proposed Boost Dataflow library, which supports threading.

I don't have a book to recommend, but check out Herb Sutter's series of Dr Dobbs articles on C++ concurrency.

A: I wrote a Multithreaded observer pattern in Java
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

/**
 * An observer pattern that allows listeners to register(), unregister() in
 * multiple threads and also notify listeners in another thread.
 *
 * A HashMap keeps track of the listeners and their status (active, obsolete).
 * When a listener unregister, its entry is marked as obsolete in this map.
 *
 * During firing of an event, the observer notifies all the listeners that are
 * active, the active status will be stored in a Boolean that's synchronized so
 * rare race conditions like calling notify on an active listener that has just
 * turned obsolete will not happen.
 *
 *
 */
public class MultithreadedObserverPattern <T extends AbstractListener> {

    interface Handler<T> {
        void handleEvent(T listener);
    }

    class BooleanHolder {
        boolean val;

        BooleanHolder(boolean v) {
            val = v;
        }

        void set(boolean v) {
            val = v;
        }

        boolean get() {
            return val;
        }
    }

    Map<AbstractListener, BooleanHolder> listeners = new HashMap<AbstractListener, BooleanHolder>();

    public void register(AbstractListener l) {
        synchronized (listeners) {
            listeners.put(l, new BooleanHolder(true));
        }
    }

    public void unregister(AbstractListener l) {
        synchronized (listeners) {
            BooleanHolder status = listeners.get(l);
            if (status != null) {
                // notify call also syncing on status
                synchronized (status) {
                    status.set(false);
                }
            }
            // set to false
        }
    }

    public void notifyAll(Handler handler) {
        // here we do not synchroznie on listeners to avoid tricky lock situations
        // make a copy of the map
        List<Entry<AbstractListener, BooleanHolder>> activeListeners = new ArrayList<Entry<AbstractListener, BooleanHolder>>();
        List<AbstractListener> inactiveListeners = new ArrayList<AbstractListener>();

        synchronized (listeners) {
            for (Entry<AbstractListener, BooleanHolder> entry : listeners.entrySet()) {
                if (entry.getValue().get()) {
                    activeListeners.add(entry);
                } else {
                    inactiveListeners.add(entry.getKey());
                }
            }
        }
         // call the method on active listener
        //
        for (Entry<AbstractListener, BooleanHolder> e : activeListeners) {
            BooleanHolder status = e.getValue();
            // remove those listeners that are no longer active
            synchronized (status) {
                if (status.get()) {
                      handler.handleEvent(e.getKey());
                }
            }
        }

        synchronized (listeners) {
            // remove inactive listeners
            for (AbstractListener l : inactiveListeners) {
                listeners.remove(l);
            }
        }
    }
}


text:
Q: Graph API not recognizing '#' in given filter string I'm trying to get the users from Azure AD using filter parameter. For example if I want the user with email ID "Alex.ferguson@mutd.com" , the following would be my request and this is working fine for the given email.
  var filteredUsers = await client
    .api("/users")
    .select("displayName,userPrincipalName,jobTitle,companyName,id")
    .filter("userPrincipalName eq 'Alex.ferguson@mutd.com'")
    .get();

But if the email has '#' character in it and my filter query would look like
"userPrincipalName eq 'wayne.rooney#Wazza#@mutd.com'"

The api is giving me 400 Bad request error.
the url path would look like this
https://graph.microsoft.com/v1.0/users?$select=displayName,userPrincipalName,jobTitle,companyName,id&$filter=userPrincipalName%20eq%20%27wayne.rooney

The email is getting trimmed at the first '#' character. What can I do about it. I have many users in my Azure AD with the email ID's having a '#' character. I tried using an escape character '' before '#', still didn't work.

A: Try to encode the email.
https://graph.microsoft.com/v1.0/users?$filter=userPrincipalName eq 'wayne.rooney%23Wazza%23%40mutd.com'

and in your code
var filteredUsers = await client
.api("/users")
.select("displayName,userPrincipalName,jobTitle,companyName,id")
.filter("userPrincipalName eq 'wayne.rooney%23Wazza%23%40mutd.com'")
.get();


text:
Q: Riak-cs solution with antivirus Does riacks offer any feature of virus scanning, or can an easy software be implemented on top ?
I did not find anything on the documentation.

A: Sorry Riak KV, TS, and S2 (formerly C2) do not offer any anti virus scanning functionality. You will need to implement your own anti virus capability in front of whichever Riak you use.


text:
Q: Capital letter in the word "one"? Suppose I have a headline for a subsection of a book or article that goes something like: Everything Collected in One Place.
Is this correct or should it be: Everything Collected in one Place. ?

A: This is mostly a matter of style, but it would most often be capitalised.
In titles we generally capitalise all words except articles, coordinating conjunctions, and for most but not all styles, prepositions. Hence:

Everything Collected in One Place

Notably, in a lot of European languages, there is a lack of distinction between the word a/an (an article) and the word one (a determiner, specifically a cardinal number, but not an article). This though is not the case with Modern English (it was with Old English), so there can be no confusion on the point.
There are other styles in use. Some would capitalise even prepositions:

Everything Collected In One Place

Some would not capitalise determiners (including one) along with all conjuctions (not just coordinating):

Everything Collected in one Place

But these are rarer, and besides which, someone using such a style might decide that one was important enough in the concept conveyed (that is, that there was just 1 place was important) that they would bend the rule and capitalise it:

Everything Collected in One Place [again]

There are other title styles in use besides these, which for completeness, might only capitalise nouns:

Everything collected in one Place

Or else full all-caps, full all-lower and normal sentence case.

EVERYTHING COLLECTED IN ONE PLACE
everything collected in one place
Everything collected in one place

Unless you've a a style-guide to go for, I would strongly suggest the first style I list here as simple to follow and commonly understood and use. My next-strongest suggestion would be the fourth style, where we lower-case all determiners but title-case them again if they are particularly important to the title in question (which in this example ends up with the same capitalisation as the first style, but might not). The others though are not wrong, they are just different styles.


text:
Q: Book suggestion for a Math student taking Electromagnetism I'm hoping to double major in math and physics. I'm currently taking graduate math courses and undergrad physics courses.
I'm having a really hard time with my Electromagnetism class. A lot of the problems being given have solutions that aren't really detailed enough for me to make sense of them. They will write down the setup of the question like it is second nature, and then just go to the math. A great example is when they have said, "The 'horizontal' components cancel." Not only do they have "horizontal" in quotes, but they don't even show what is canceling. So I have no idea what they are referring to here or what cancels. So if I come upon a problem where "horizontal" doesn't cancel, I have no idea how to approach it.
Does anyone know of a good mathematical Electromagnetism book? One that really goes explains each problem mathematically and doesn't cut out parts without explaining them mathematically?

A: Somo classic ("old but gold") books are:

*

*Introduction to Electrodynamics, by David Griffitiths. [He has a really nice introduction to Vector Calculus (The required for Physics) before starting the actual physics of electromagnetism.]

*Classical Electrodynamics, Jackson (another classic.)

*The Feynman Lectures on Physics, by Richard Feynman (which is other master piece in Physics.)
You may also be interested in some online resources that explores undergrad electromagnetism, like the Walter Lewin's Lectures.
In the link https://youtu.be/rtlJoXxlSFE you find a whole list of lectures on electromagnetism.
Hope this material is useful!

A: You have asked for good mathematical electromagnetism book. Below mentioned books are mathematical in their style.
1.Classical electricity and magnetism
Textbook by Wolfgang K. H. Panofsky
This is a advanced Undergraduate book  and its more inclined on mathematical side and well supplemented with theory.
2.Modern Electrodynamics
Textbook by Andrew Zangwill
An engaging writing style and a strong focus on the physics make this comprehensive, graduate-level textbook unique among existing classical electromagnetism textbooks. Charged particles in vacuum and the electrodynamics of continuous media are given equal attention in discussions of electrostatics, magnetostatics, quasistatics, conservation laws, wave propagation, radiation, scattering, special relativity, and field theory.

*Principles of electrodynamics
Textbook by Melvin Schwartz

Suitable for advanced undergraduates and graduate students, this volume offers a superb exposition of the essential unity of electromagnetism in its natural , relativistic framework while demonstrating the powerful constraint of relativistic invariance.Its a thin book and quite mathematical.
4.
Classical Electrodynamics
Textbook by John David Jackson
only for advanced students. Not an introductory text.The book is notorious for the difficulty of its problems, and its tendency to treat non-obvious conclusions as self-evident.


text:
Q: What is exactly causing my main method to run infinitely when instead I want it to run my method incrementally based off the user's response? I'm trying to write a beginner program, where I roll 2 dies, and it tests the dies, if there's any evens it will say "evens are better then odds" and if there's a scenario where there's only odds it will say, "Odds are still cool", and after each roll it will ask the user if they want to play again, if not it will tell the user how many times they rolled the die. When I run the program, it will run, and ask the user if they want to roll again, when I type "YES" it runs infinitely. I don't know if the problem has to do with how my main method is written or if it's the TinasDice method.
I've tried going about using only the if/else statement in the main method where the user's input is tested, but that immediately exits out of the program.
            TinasDice();

            Console.WriteLine("Do you want to play again?");
            string answer;
            int counter = 0;
            answer = Console.ReadLine();

            while (answer == "YES")
            {

                if (answer == "YES")
                {
                    TinasDice();
                }
                else
                {
                    Console.WriteLine("The number of times the dice was die was thrown is: " + counter);
                    Console.WriteLine("Nice game!");
                    Console.WriteLine("Thanks for playing. Come play again soon!");
                }

            }
        }

                public static void TinasDice()
                {
                Random random = new Random();

                int dice1 = new int();
                int dice2 = new int();

                dice1 = random.Next(1, 6);
                dice2 = random.Next(1, 6);

                Console.WriteLine("Hey Welcome to Tina's Dice Game.");
                Console.WriteLine("Let's start!");

                if (dice1 % 2 == 0 || dice2 % 2 == 0)
                {
                    Console.WriteLine("I got  " + dice1 + " and " + dice2);
                    Console.WriteLine("Evens are better then odds!");

                }
                else
                {
                    Console.WriteLine("I got a " + dice1 + " and " + dice2);
                    Console.WriteLine("Odds ares still cool!");
                }

I'm just trying to get the program to run incrementally after TinasDice is ran the first time, so when the user types "YES" it will run TinasDice once, and then prompt the user again, until the user types something else other then "YES".

A: Taking your example from above.
   TinasDice();

        Console.WriteLine("Do you want to play again?");
        string answer = "YES";
        int counter = 0;

        while (answer == "YES")
        {
            answer = Console.ReadLine();
            counter++;
            if (answer == "YES")
            {
                TinasDice();
            }
            else
            {
                Console.WriteLine("The number of times the dice was die was thrown is: " + counter);
                Console.WriteLine("Nice game!");
                Console.WriteLine("Thanks for playing. Come play again soon!");
                break;
            }

        }
    }

Note the defaulting of the "YES" and the break


text:
Q: Stamp Contact Record based on contact being added to a Campaign as a Campaign Member I want to update a field(s) on the related Contact record each time they are added to a campaign so we can attribute donated funds to the correct campaign when no other identifier is given.
As a charity we get a huge amount of unspecified web donations and we would like to automate allocating the funds to the correct campaign. As Salesforce does not allow you to do field updates from the Campaign Member object back to the Contact record how can this be achieved in a in an automated way?


text:
Q: PHP Fatal error: Class 'GreetCommand' not found in /var/www/cli/application.php on line 11 I am using symfony console component
When I run this command by console
php application.php

Then this command give me this error

PHP Fatal error:  Class 'GreetCommand' not found in
  /var/www/cli/application.php  on line 11

I configured all setting according to this link
http://symfony.com/doc/current/components/console/introduction.html

My application.php file code
<?php
// application.php

require __DIR__.'/vendor/autoload.php';

//use GreetCommand;
use Symfony\Component\Console\Application;

$application = new Application();
$application->add(new GreetCommand());
$application->run();

And My Greet Command exist in same location of the application.php file
Code is:
<?php
//namespace Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;

class GreetCommand extends Command
{
    protected function configure()
    {
        $this
            ->setName('demo:greet')
            ->setDescription('Greet someone')
            ->addArgument(
                'name',
                InputArgument::OPTIONAL,
                'Who do you want to greet?'
            )
            ->addOption(
               'yell',
               null,
               InputOption::VALUE_NONE,
               'If set, the task will yell in uppercase letters'
            )
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $name = $input->getArgument('name');
        if ($name) {
            $text = 'Hello '.$name;
        } else {
            $text = 'Hello';
        }

        if ($input->getOption('yell')) {
            $text = strtoupper($text);
        }

        $output->writeln($text);
    }
}

So please help me what is the problem in my application.php file when  executing this command by using symfony console component


text:
Q: ElasticSearch, Nest and timeout for long queries I am using ElasticSearch with Nest (0.9.16) and have some queries which take longer than 60 seconds.  When that happens, I receive the following error:

The request was aborted: The request was canceled.

While I am concerned that the query is taking such a long time, for this question, I am just interested if there is a way to increase the timeout.  I have not been able to find a way to increase the timeout.
Note, I do see a couple of places where I can set a timeout, but these are not the right places:
var setting = new ConnectionSettings(new Uri(searchUrl)).SetTimeout(200000);

or
searchdescriptor.Timeout("120000");

The first one sets the connection timeout and the second one sets the ElasticSearch timeout, both of which are not helpful here.
Thanks,
Eric

A: Actually, much to my chagrin, the ConnectionSettings().SetTimeout() does in fact increase the request timeout and solve my problem. I am not sure why I missed this initially.


text:
Q: When multiple push notification selecting one disappears others from the tray I am having the case when i am getting multiple notifications and when i select any one of them it opens up my app and does according my code.Then when i check other notifications are disappeared from the tray. Is this the usual case with notifications that opening one will remove others too or I am missing something?
I also have the question about bedge icons for multiple notifications also it is always shows 1 on the app icon. on opening of any of notification i set it to 0(zero). Does this bedge manage by server? If so how server will identify that this device is sent this many number of notifications?
As bedge are always shows 1, if i set bedge count as
     int bedge = [UIApplication sharedApplication].applicationIconBadgeNumber;
     bedge--;
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:bedge];

It goes to negative numbers.

A: you're not missing anything its usual case just because by clicking on any noti your app is getting open so all were disappear because all are related to the same application that's why once you open your app from any noti other were disappears.

A: About APNS:
Once your app is registered to APNS you will receive the device token. That device icon your are passing to third party server and if third party want to send the notification to the device then it will contact to APNS and ask to push the notification.
About Badges:
The badges will handled by OS. That means whenever third party pushing the notifications to the device then OS is automatically increase the count.Once you open the any notification in device notification bar or lock screen it will directly navigate to the application. Because your app ID is registered to APNS and it automatically sets the count to 0.


text:
Q: mouseMoveTracking in QtGraphicsScene I want to track mouse in my main window.
I have enabled the moustracking in the QGraphicsView
here is the constructor for GraphicsView subclass, the rest is the default behavior.
GraphicsView::GraphicsView(QWidget* parent): QGraphicsView(parent)
{

  setMouseTracking(true);

  setDragMode(RubberBandDrag);
  setRenderHints(QPainter::Antialiasing|  QPainter::TextAntialiasing);
  setMinimumSize(600, 400);

}

here is my GraphicsScene MouseMove method:
void GraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
  if (myMode == InsertLine && line != nullptr) {
      QLineF newLine(line->line().p1(), mouseEvent->scenePos());
      line->setLine(newLine);
  } else if (myMode == Select) {
      QGraphicsScene::mouseMoveEvent(mouseEvent);
  }
  QPointF point = mouseEvent->pos();
  //point = this->mapToScene(point);
  qDebug() << point.x() << " " << point.y() << " ";
  mouseMoved(point);
  QGraphicsScene::mouseMoveEvent(mouseEvent);
}

I get zero and zero for x and y  position. What am i doing wrong ?

A: If you review the docs of pos() method of QGraphicsSceneMouseEvent:

Returns the mouse cursor position in item coordinates.

That is, those coordinates are relative to a QGraphicsItem, but in this case there are no coordinates and consequently it has no meaning (it would only have it if the mouseMoveEvent would belong to a QGraphicsItem). In this case you must use the scenePos() method
void GraphicsScene::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
  // ...
  QPointF point = mouseEvent->scenePos();
  qDebug() << point.x() << " " << point.y() << " ";
  // ...
  QGraphicsScene::mouseMoveEvent(mouseEvent);
}


text:
Q: Use Custom Authorization API in wso2am I  have a following requirements.
I wants to use wso2 as getaway and generation of token and authentication. Of user.
I have a spring boot api which takes input a url and user id and based on these it decide whether user can access it or not
Now I wants to use this api in wso2am for authorizing the user for url..How can I used it .

A: You can write a custom handler and set it after the default authentication handler in the velocity xml.
See https://docs.wso2.com/display/AM260/Writing+Custom+Handlers


text:
Q: Liferay Exception Receiving exception after changing the database.
There are two application server with host name prodwpas01 and prodwpas02 respectively.
The following exception are being generated by Liferay
20:45:49,853 INFO  [MSC service thread 1-13][BaseReceiver:64] Accepted view [prodwpas02-59913|12] [prodwpas02-59913, prodwpmw02-20897, prodwpas01-18001]
20:45:49,863 ERROR [Incoming-3,shared=liferay][NAKACK2:766] failed to deliver message [dst: <null>, src: prodwpas02-59913 (2 headers), size=889 bytes]
java.lang.NullPointerException
    at com.liferay.portal.kernel.messaging.MessageBusUtil._sendMessage(MessageBusUtil.java:202)
    at com.liferay.portal.kernel.messaging.MessageBusUtil.sendMessage(MessageBusUtil.java:90)
    at com.liferay.portal.kernel.cluster.messaging.ClusterForwardMessageListener.receive(ClusterForwardMessageListener.java:42)
    at com.liferay.portal.cluster.ClusterForwardReceiver.receive(ClusterForwardReceiver.java:44)
    at org.jgroups.JChannel.invokeCallback(JChannel.java:749)
    at org.jgroups.JChannel.up(JChannel.java:710)
    at org.jgroups.stack.ProtocolStack.up(ProtocolStack.java:1025)
    at org.jgroups.protocols.pbcast.STATE_TRANSFER.up(STATE_TRANSFER.java:178)
    at org.jgroups.protocols.FRAG2.up(FRAG2.java:181)
    at org.jgroups.protocols.FlowControl.up(FlowControl.java:400)
    at org.jgroups.protocols.FlowControl.up(FlowControl.java:418)
    at org.jgroups.protocols.pbcast.GMS.up(GMS.java:896)
    at org.jgroups.protocols.pbcast.STABLE.up(STABLE.java:245)
    at org.jgroups.protocols.UNICAST.up(UNICAST.java:414)
    at org.jgroups.protocols.pbcast.NAKACK2.handleMessage(NAKACK2.java:763)
    at org.jgroups.protocols.pbcast.NAKACK2.up(NAKACK2.java:574)
    at org.jgroups.protocols.pbcast.NAKACK2$1.run(NAKACK2.java:856)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)

In portal-ext.properties following lines are turned on but still receiving the exception
cluster.link.enabled=true
org.quartz.jobStore.isClustered=true
lucene.replicate.write=true


text:
Q: How to define a C macro that uses another macro? I have the following scenario...
Header file:
#define TRIG_INDEX 200
#define PATH(target_p) some.path.to.target##target_p

Source file:
read_from_target(PATH(TRIG_INDEX));

As the PATH macro appends the target_p to the text at the end, compilation fails as
some.path.to.targetTRIG_INDEX is not a valid path.
I was expecting to get read_from_target(some.path.to.target200) in the above scenario.
How can I (if at all) define the macros to accept such scenario?

A: The argument must be expanded by the macro:
#define TRIG_INDEX 200
#define PATH_TARGET(x) some.path.to.target##x
#define PATH(target_p) PATH_TARGET(target_p)

A: The pre-processor macro expansion/replacement rules for function-like macros are rather intricate. Basically it does so in the following order:

*

*The stuff after the macro name is known as the replacement list. In this case PATH_TARGET(target_p) - things that PATH should be replaced with.

*The occurrence of ## or # together with a macro parameter means that the parameter gets replaced with its corresponding pre-processor token sequence (if applicable). In this case, the parameter target_p gets replaced with TRIG_INDEX, so we get some.path.to.target##TRIG_INDEX creating the new pre-processor token some.path.to.targetTRIG_INDEX , which is not as intended.

*Other macro parameters get expanded. Doesn't apply here.

*The replacement list is then rescanned for macro names to expand, but it's too late since pre-processor token concatenation with ## has already occurred.
The part "other macro parameters get expanded" above is useful to fix the problem. So macro parameters  in the replacement list take precedence over macro names. We can take advantage of this by adding a helper macro:
#define TRIG_INDEX 200
#define EXPAND(tgt) some.path.to.target##tgt
#define PATH(target_p) EXPAND(target_p)

Now in the expansion of the replacement list of PATH, we first get macro parameter expansion: taget_p is replaced and we get EXPAND(TRIG_INDEX). The replacement list is then rescanned for macro names to replace, the pre-processor finds two such macro names: EXPAND and TRIG_INDEX. Both are expanded and so TRIG_INDEX is replaced with 200. Then EXPAND is expanded recursively according to the same rules (## enforcing an expansion of that macro parameter tgt into 200 before anything else).
For details, see the C17 standard chapter 6.10.3 - this chapter is also the one which specifies the behavior of the # and ## operators.


text:
Q: Concurrent login Anyone here tried to implement a way in ColdFusion to not let same login account to be used concurrently, so if one login and the other login will either be disabled or kick out the first one.
please share your experience.

A: Two methods, the first is significantly lighter on performance than the other.
Deny any user who tries to login after the first.

*

*Add a loggedin field to your users table. Simple 0/1.

*When the user logs in, run a query like this

LoginQuery:
<cfquery name="validate">
  select userID,loggedIn,data,you,want
    from users
   where username=<cfqueryparam cfsqltype="cf_sql_varchar" value="#form.username#">
     <!--- I hope you're hashing/encrypting passwords, but this is a simple demo --->
     and password=<cfqueryparam cfsqltype="cf_sql_varchar" value="#form.password#">
</cfquery>

<cfif validate.recordcount eq 1>
  <cfif validate.loggedIn eq 0>
    <cfset session.userID = validate.userID
    ...collect whatever info from table
    <cfquery name="validate">
      update users
       set loggedIn=1
     where userID=<cfqueryparam cfsqltype="cf_sql_integer" value="#validate.userID#">
    </cfquery>
  <cfelse>
    Someone else is logged in.
  </cfif>
<cfelse>
  Invalid credentials.
</cfif>

When the user logs out, set the loggedIn flag in the table to 0
<cfquery name="validate">
  update users
   set loggedIn=0
 where userID=<cfqueryparam cfsqltype="cf_sql_integer" value="#session.userID#">
</cfquery>

Now, because a lot of users navigate away from the site, or walk away from the computer, you can use Application.cfc's onSessionEnd method, which executes when a session ends to do the same query as logout with one change. Session scope is not available to the method, instead you need to use Sessionscope argument of the method.
Therein lies the one flaw with this method. If a user walks away from the machine/navigates away from the page, noone can login til the first user's session expires. So if your session timeout is set to 20 minutes, and you walk away from the machine, noone can login to that account for 20 minutes. It's for this reason that you'd really want a short-ish session timeout (but nothing obnoxiously short that would penalize a user for taking too long to complete a form).
<cffunction name="onSessionEnd">
    <cfargument name = "SessionScope" required=true/>
    <cfargument name = "AppScope" required=true/>
    <cfquery name="validate">
      update users
        set loggedIn=0
      where userID=<cfqueryparam cfsqltype="cf_sql_integer" value="#SessionScope.userID#">
    </cfquery>
</cffunction>

Kick the first out after a second logs in
The problem with this route is that it really needs to run a query on every page (or at least, every member-specific page. You could conceivably have 10 users on the front page of the site under the same username, but who cares. But any, aside from the most recently logged in, who try to access a member page, are immediately kicked out. Of course, they would attempt to log back in, now becoming the most-recent, and kicking anyone else out. That's another downside to this practice.
Add a loginkey field to your users table.
When the user logs in, populate this field with a value unique to the user, you can do something like.
#randrange(1,10000000)#

Store this key in users.loginkey and session.loginkey.
Match this on each page, or at least each members page. If the first-login is browsing the front pages, let it slide, save on performance.
<cfquery name="validate">
  select userID
    from users
   where loginkey=<cfqueryparam cfsqltype="cf_sql_integer" value="#session.loginkey#">
     <!--- since you're doing this, might as well validate credentials --->
     and password=<cfqueryparam cfsqltype="cf_sql_varchar" value="#session.password#">
     and username=<cfqueryparam cfsqltype="cf_sql_varchar" value="#session.username#">
</cfquery>

You can move that loginkey section of the where statement to an if statement (like I demonstrated in the first method) and explain to the user why they were kicked out. Or you can do this query side.
(You can also use session.cfid and cftoken as the unique identifier, which is very valid, I simply wanted to show you where and how you'd need to store the data if you were creating a separate key. I personally would use cfid/cftoken because... why add more performance overhead)


text:
Q: How to save LLVM DEBUG into a file Hello, I'm studying on LLVM register allocation.
In order to understand the compilation flow, I tried to save DEBUG infos into a file but failed.
Since the application I'm running is in python, I tried as the followings:
gdb python
b Debug.cpp:43 -> Where DebugFlag = false resides
run test.py
set DebugFlag = 1
continue

I tried redirecting (run test.py > tmp.txt) and "set logging on" in gdb, but still doesn't show the information of DEBUG.
Can anyone give me an advice for saving DEBUG information of LLVM?
Regards,
Jake


text:
Q: Approximating dense subspaces of Fréchet spaces If $H$, $H_0$ are two separable Hilbert spaces and $H$ is continuously and densly embedded in $H_0$, it is possible to construct a sequence of linear operators
$$ P_n : H_0 \to H $$
such that for all $x \in H_0$ one has convergence $P_n x \to x$ in the $H_0$-norm.
The motivation is to generalize the idea of smoothing operators. For example, $H^2(\mathbb R)$ is densely embedded in $L^2(\mathbb R)$ and it is well known that one can approximate each $L^2$-function by an $H^2$-function. In this case $P_n$ could be a convolution with a smooth kernel with width $1/n$.
Can this be generalized to Fréchet spaces or even beyond? If $H$ and $H_0$ are Fréchet spaces rather than Hilbert spaces, is it always possible to construct a sequence of bounded operators $P_n$ as above?
In the Hilbert case one way to construct $P_n$ is by considering an unbounded, self-adjoint operator $A : D(A) \to H_0$, with $D(A)=H$, that represents the inner product via
$$ \langle v,w \rangle_H = \langle Av, Aw \rangle_{H_0}\,. $$
If $\{ P_\Omega\}$ is the spectral measure accociated to $A$, then we can use $P_{[-n,n]}$ as our sequence of operators. It is less clear to me, what to with Fréchet spaces.

A: Here is a very simple method for separable Hilbert spaces (which easily generalizes to Frechet spaces with Schauder bases): Take an orthonormal basis $(e_k)_k$ in $H_0$ and choose $f_{n,k}\in H_1$ such that $\|e_k-f_{n,k}\|_0 \le 1/(n^2+k^2)$. Then define $P_n(x)=\sum_{k=1}^n \langle e_k,x\rangle_0 f_{n,k}$. The difference $\|P_n(x)-x\|_0$ is estimated just using the triangle inequality (so that this construction isn't bound to Hilbert spaces).
EDIT. I add some details for the Frechet case showing (at least under a mild additional assumption) that one does not need an absolute basis (which would exclude many Banach spaces, I recall the definitions below).
Let $(\|\cdot\|_N)_{N\in\mathbb N}$ be an increasing sequence of seminorms giving the topology of the Frechet space $H_0$. A Schauder basis $(e_k)_k$ is a sequence such that that every $x\in H_0$ has a unique representation $x=\sum\limits_{k=1}^\infty \xi_k(x)e_k$. (The basis is called absolute if, for each $N$, there are $M$ and $c>0$ such that $\sum\limits_{k=1}^\infty |\xi_k(x)|\|e_k\|_N \le c\|x\|_M$ for all $x\in H_0$ -- this implies that the spaces is a projective limit of weighted $\ell^1$ spaces and excludes Hilbert spaces). By corollary 28.11 in the book Introduction to Functional Analysis of Meise and Vogt one has a slightly weaker condition for every Schauder basis: For every $N$ there are $M=M(N)$ and $c>0$ such that
$\sup\lbrace|\xi_k(x)|\|e_k\|_N:k\in\mathbb N\rbrace \le c\|x\|_M$. In particular, the coefficient functionals $\xi_k$ (which are linear by the uniqueness) are continuous.
We construct $P_n$ under the additional assumptions that $\|\cdot\|_1$ is a norm and not only a seminorm (I am quite optimistic that this can be removed). For $n,k \in\mathbb N$ choose $f_{n,k}\in H_1$ with $\|e_k-f_{n,k}\|_n\le \|e_k\|_1/n^2$ and set, as previously, $P_n(x)=\sum\limits_{k=1}^n\xi_k(x)f_{n,k}$. These are continuous linear operators $H_0\to H_1$, and for each $x\in H_0$, $N\in\mathbb N$, and $n\ge N$ we have
$$
\|P_n(x)-x\|_N \le \sum_{k=1}^n |\xi_k(x)|\|f_{n,k}-e_k\|_N + \|\sum_{k=n+1}^\infty\xi_k(x)e_k\|_N.
$$
The second term tends to $0$ and (since $n\ge N$) the first term can be estimated by
$\sum_{k=1}^n |\xi_k(x)|\|e_k\|_1/n^2 \le  c\|x\|_{M(1)}/n$.

A: Thanks to Jochen, Matthew and Bill, this is a detailed proof for Fréchet spaces.
Proposition. Let $E$ be a separable Fréchet space with the bounded approximation property, $F$ a topological vector space, continuously and densely embedded in $E$. Then there exists a sequence of continuous linear maps $P_n : E \to F$, such that
$$
\forall x \in E\,:\, P_n x \to x \text{ in }E\,.
$$
Proof.
Let $(x_n)_{n \in \mathbb N}$ be a countable, dense sequence in $E$ and $(\|\cdot\|_n)_{n \in \mathbb N}$ an increasing fundamental system of seminorms. We assumed that $E$ has the bounded approximation property, hence there exists an equicontinuous sequence of linear maps $T_n : E \to E$ with finite rank that converge to $\operatorname{Id}_E$, uniformly on compact sets. By passing to a subsequence we can assume that
$$
\| T_n x_j - x_j \|_n \leq \frac 1n \text{ for }j \leq n\,.
$$
Due to equicontinuity there exists for each $m$, an $N_m \in \mathbb N$ and $C_m>0$ such that
$$
\forall n \in \mathbb N\,,\; \forall x \in E\,:\, \| T_n x \|_m \leq C_m \| x \|_{N_m}\,.
$$
For each $n$, the space $T_n(E)$ is finite dimensional. Let $n'=n'(n)$ be such that $\|\cdot\|_{n'}$ is a norm on $T_n(E)$. We can construct a map $S_n : T_n(E) \to F$ with
$$
\| S_ny - y \|_{n} \leq \frac 1n \| y \|_{n'}\,,
$$
for all $y \in T_n(E)$.
To see that this is possible choose a basis $y_1, \dots, y_m$ of $T_n(E)$ and note that it is sufficient to define $S_n(y_i) \in F$, such that $\| S_n(y_i) - y_i \|_{n}$ is small enough. This is possible, because $F$ is dense in $E$. Define $P_n = S_n T_n$.
We have to show convergence $P_n x \to x$. Fix $x \in E$ and a seminorm $\|\cdot\|_m$. For $n$ and $k$ satisfying $m ,\,N_m,\,N_{m'} \leq n$ and $k \leq n$ we have
\begin{align*}
\| P_n x &- x \|_m \leq \|S_n T_n(x-x_k) -T_n(x-x_k) \|_m + \| T_n(x-x_k) \|_m + \\
&\qquad\qquad\qquad
+ \|S_n T_n x_k - T_n x_k \|_m  +\| T_n x_k - x_k\|_m  + \| x_k - x\|_m \\
&\leq \frac 1n \| T_n(x-x_k) \|_{m'} + C_m \| x - x_k \|_{N_m} + \frac 1n \| T_n x_k \|_{m'} + \frac 1n + \|x_k - x \|_m \\
&\leq
\frac {C_{m'}}{n} \| x-x_k \|_{N_{m'}} +  C_m \| x - x_k \|_{N_m}
+ \frac {C_{m'}}n \left( \| x\|_{N_{m'}} + \| x-x_k \|_{N_{m'}} \right) + \\
&\qquad\qquad + \frac 1n + \|x_k - x \|_m \,.
\end{align*}
We see that by choosing $n$ large enough and $\|x - x_k\|_n$ small enough we can achieve convergence.

A: Edit: So I think my real mistake was in the claim that "if $H_0$ is separable then we can use a sequence".  As Bill Johnson implictly points out, you can always find a net $P_\alpha:H_0\rightarrow H$.
Just to correct the argument (though Martins now gives it in more generality)...  If $H_0$ has the bounded approximation property, then there is an absolute constant $\lambda>0$ so that for $x_1,\cdots,x_n\in H_0$ there is a finite-rank operator $T:H_0\rightarrow H_0$ with $\|T\|\leq \lambda$ and $\|T(x_i)-x_i\| \leq \epsilon$ for each $i$.
In our case, $\iota:H\rightarrow H_0$ is a continuous map with dense range.  For $x_1,\cdots,x_n \in H_0$ and $\epsilon>0$ we find a finite-rank $T$ with $\|T\|\leq\lambda$ and $\|T(x_i)-x_i\| \leq \epsilon$ for each $i$.
As $T(H_0)$ is finite dimensional and $\iota$ has dense range, we can find a linear map $S: T(H_0) \rightarrow H$ so that that $\|\iota S(x) - x\| \leq \epsilon$ for all $x$ in the unit ball of $T(H_0)$.  [Proof: If $M\subseteq H_0$ is finite-dimensional, with linear basis $m_1,\cdots,m_n$, then as all norms are equivalent on $M$, if we can ensure that $\|\iota S(m_i)-m_i\|$ is very small, then $\|\iota S(x)-x\|$ will be small uniformly on the unit ball of $M$.  But this follows as $\iota$ has dense range and we can choose each $S(m_i)$ completely freely.]
Then $\| \iota ST(x_i) - x_i\| \leq \| \iota ST(x_i) - T(x_i) \|
+ \| T(x_i) - x_i \| \leq \epsilon \|T(x_i)\| + \epsilon$ $\leq \epsilon^2
+ \epsilon\|x_i\| + \epsilon$.  So $ST : H_0 \rightarrow H$ approximates the identity in the $H_0$ norm.

*

*If we want a net, we just let $(x_i)_{i=1}^n$ run through all finite subsets of $H_0$, and observe that we didn't use the bound on $T$, so as Bill Johnson suggests, we could just take $T$ to be a projection onto the span of the $(x_i)$, no condition on $H_0$ needed.

*If $H_0$ is separable, let $(x_k)$ be a countable dense subset, and let $S_nT_n$ be chosen as above for $(x_i)_{i=1}^n$ and $\epsilon=1/n$.  If $x\in H_0$ with $\|x - x_i\| \leq \epsilon$ for some $i\leq n$, then
\begin{align*}
& \| \iota S_nT_n(x) - x \| \leq \| \iota S_nT_n(x) - x \| \\
& = \| \iota S_nT_n(x-x_i) - T_n(x-x_i) + \iota S_n T_n(x_i) - T_n(x_i)
+ T_n(x) - x \| \\
&\leq \epsilon\|T_n(x-x_i)\| + \epsilon\|T_n(x_i)\| + \|T_n(x-x_i) - (x-x_i) + T_n(x_i) - x_i \| \\
&\leq \epsilon^2\lambda + \epsilon(\epsilon+\|x_i\|) + \epsilon\lambda + \epsilon \\
&\leq \epsilon^2\lambda + \epsilon(2\epsilon+\|x\|) + \epsilon\lambda + \epsilon.
\end{align*}
Without the BAP you seemingly cannot control $\|T(x-x_i)\|$ for example.
Remark 1:  Having the "compact approximation property" doesn't seem to help.  By definition, this means we can only choose $T$ to be compact not finite-rank.  Then the image of the unit ball of $H_0$ under $T$ is a compact set, but I don't know how to form the equivalent of $S$.  That is, how do you (linearly) distort a compact set from $H$ into $H_0$?