text:
Q: How to push data feed to Dashboard to be able create charts on it in react-admin? I have a basic dashboard.js which was on the Tutorial of React-admin.
import React from 'react';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import CardHeader from '@material-ui/core/CardHeader';

export default () => (
    <Card>
        <CardHeader title="Welcome to the administration" />
        <CardContent>Juhejj ez is mukodik!</CardContent>
    </Card>
);

Where can I find any documentation on how to push the data that's coming from my App.js < Resource > (from my Rest API) to dashboard?
I want to create Widgets, Charts onto my admin dashboard, but everything I've found so far was about creating a simple Dashboard with fake data in the dashboard.js.
const data = [{ bla: 1, bla2: 2 }];

My App.js looks like this:
import React from 'react';
import { Admin, Resource, mergeTranslations, ListGuesser } from 'react-admin';
import { AdList } from './ads/AdsList';
import { AdEdit } from './ads/AdsEdit';
import { PostCreate } from './ads/posts';
import { LeadList } from './leads/leads';
import { UserList, UserShow, UserEdit, UserCreate } from './users/users';
import { ClickList, ClickMonthly, ClicksmonthlyList } from './clicks/clicks';
import PostIcon from '@material-ui/icons/Book';
import UserIcon from '@material-ui/icons/Group';
import Dashboard from './dashboard/Dashboard';
import authProvider from './authprovider/authProvider';
import jsonServerProvider from './dataprovider/rest';
import { reducer as tree } from 'ra-tree-ui-materialui';
import englishMessages from 'ra-language-english';
import treeEnglishMessages from 'ra-tree-language-english';

const messages = {
    'en': mergeTranslations(englishMessages, treeEnglishMessages),
};

const dataProvider = jsonServerProvider('http://my.api.to/api/v1/');
const App = () => (
    <Admin dashboard={Dashboard} authProvider={authProvider} dataProvider={dataProvider} locale="en" messages={messages} customReducers={{ tree }}>
    {permissions => [
        <Resource name="ads" options={{ label: 'Hirdetések' }} list={AdList} edit={AdEdit} create={PostCreate} icon={PostIcon}/>,
        permissions === 'admin' ? <Resource name="users" options={{ label: 'Felhasználók' }} list={UserList} show={UserShow} edit={UserEdit} create={UserCreate} icon={UserIcon}/> : null,
        <Resource name="clicks" options={{ label: 'Legutóbbi kattintások' }} list={ClickList} />,
        <Resource name="clicksmonthly" options={{ label: 'Havi összesítés' }} list={ClicksmonthlyList} />,
        <Resource name="leads" options={{ label: 'Legutóbbi leadek' }} list={LeadList} />,
        <Resource name="sites" />

]}
    </Admin>
);

export default App;

A: There are two ways to do that:
One is doing it like in our official demo (source), where we call the dataProvider directly, without using redux. You call it like you would for a classic fetch (maybe inside your componentDidMount). Something like:
dataProvider(GET_LIST, 'commands', {
    filter: { date_gte: aMonthAgo.toISOString() },
    sort: { field: 'date', order: 'DESC' },
    pagination: { page: 1, perPage: 50 },
})
    .then(response => {
        this.setState({ commands: response.data });
    });

The downside of this approach is that you'll have to handle errors, notifications, etc. by yourself.
The other way would be to use react-admin redux action creators to do the same thing but leveraging its side effects handling (notifications on errors, etc.). This time, you have to make your <Dashboard> a connected component:
import { connect } from 'react-redux';
import { crudGetList } from 'react-admin';

const mapStateToProps = state => {
    const commandState = state.admin.commands;

    // Is an object where keys are the commands identifiers
    // and the values are the command
    const commandsByIds = commandState.data;

    return {
        commands: Object.values(commandsByIds),
    }
}

const mapDispatchToProps = {
    crudGetList,
}

const ConnectedDashboard = connect(mapStateToProps, mapDispatchToProps)(Dashboard);

You would then call the crudGetList in your componentDidMount too:
componentDidMount() {
    this.props.crudGetList(
        'commands', // resource name
        { page: 1, perPage: 50 }, // pagination
        { field: 'date', order: 'DESC' }, // sorting
        { date_gte: aMonthAgo.toISOString() } // filters
    );
}

Final notes:
We are aware the documentation could be improved for those use cases. The good news is that we are going to make it easier soon (probably in the 2.8 release): See https://github.com/marmelab/react-admin/pull/2899


text:
Q: Missing information and change format viewing itext pdf autofilled I got a problem with my generated Pdf files (as a template I created a pdf using Adobe Acrobat Pro with acroforms), I can view them correctly on Chrome, IE and Mozilla Firefox, also using my android mobile, but I have some problems with windows reader app and iOS divices...
This is my generated pdf: http://i58.tinypic.com/30ihmxf.jpg
But when I open the same pdf on windows reader app, at first sight everything is ok then if I click an element of my form I get this (My text size and format changes): http://i60.tinypic.com/dwdphc.jpg
And finally if I open the pdf on an ipod the field's information is missing:
//i57.tinypic.com/f3yosx.jpg (please ad the "http:" I can only post 2 links)
This is my Code
    PdfReader reader;
    PdfStamper stamper = null;
    AcroFields form = null;
    String categorias="";
    DateFormat dateFormat=null;
    Calendar cal = null;

    try {
        reader = new PdfReader("gacetas\\templates\\template.pdf");
        stamper = new PdfStamper(reader, new FileOutputStream("temps\\header_"+noGaceta+".pdf"));
        stamper.getAcroFields().setGenerateAppearances(true);
        //BaseFont bf =  BaseFont.createFont("c:/windows/fonts/arial.ttf",  BaseFont.WINANSI, BaseFont.EMBEDDED);

        form = stamper.getAcroFields();

        dateFormat = new SimpleDateFormat("yyyy/MM/dd");
        cal = Calendar.getInstance();

        form.setField("fecha", dateFormat.format(cal.getTime()));

        for(int i=0;i<combinacionesCategorias.size();i++){
            categorias= categorias.concat(i+1+") "+combinacionesCategorias.get(i).toString()).concat(" \n");

        }

        form.setField("categorias", categorias);
        stamper.close();
        reader.close();

        } catch (IOException ex) {
         Logger.getLogger(GeneradorGacetas.class.getName()).log(Level.SEVERE, null, ex);
        } catch (DocumentException ex) {
         Logger.getLogger(GeneradorGacetas.class.getName()).log(Level.SEVERE, null, ex);
    }

I thought that maybe "setFieldProperty" or "setGenerateAppearances" could solve the problem, but it didn't
form.setGenerateAppearances(true);
form.setFieldProperty("fecha", "textfont", bf, null);
form.setFieldProperty("fecha", "textsize", new Float(30), null);
form.setFieldProperty("fecha", "setfflags",PdfFormField.FF_READ_ONLY, null);
form.setField("fecha", dateFormat.format(cal.getTime()));

I really hope you can help me and thank you in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: Losing object information when copy map to other map I have many objects with a property description where is like this:
description: "This is <strong>my description<strong>"

I build a list A with this objects in a method and I return.
The other list B who is receiving the A list, it hides the html tags.
When I access the same object of list A in list B, the description is like this:
description: "This is my description"

I don't know if there is a property on maps or lists that lose HTML content when transfering one to another.
Can someone help me?
Code:
def bla {
    def mentions = [:]
    mentions = extractMentionsFromJSON(def json)
    println " 3 " + mentions[0].description
}

def extractMentionsFromJSON(def json){
    def result = []

    json.response.docs.each {
        try {
            Mention m = new Mention()
            m.title = json.highlighting[m.id].'title'.getAt(0)
            println "1 title --> " + m.title
            println "1 title  --> " + m.title.getClass()

            m.description = json.highlighting[m.id].'description'.getAt(0)
            println "1 description --> " + m.description
            println "1 description --> " + m.description.getClass()

            result.add(m)
        } catch (Exception e) {
            println "ERROR"
        }
        println " 2 "
        result.each { println it.title}
        return result
    }
}

In the print "1" and "2" the object description and title have the correct attributes with html content.
In the prin "3", no html content.

A: When you pass a list around in Groovy or Java, you don't pass a copy of the list and everything in it. You just pass a reference to the same list and the same items inside it.
If you change these objects in a method, any other place with a reference to them will see the changes. You'll need to explicitly make copies of these objects instead.
(I'm sorry if the answer is too vague and generic, but you haven't given enough information about your code to make a proper sample.)


text:
Q: Can't load UICollectionView from UITableViewCell My UITableViewController has cells with build-in UICollectionView. I wound want to move UIViceController logic into the cell class - JournalSceneCell. To implement it in the controller I assigned to the cell's variable imagesFilename a new value
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = ... as? JournalSceneCell
    cell.imagesFilename = Array(journalRef!.entries[indexPath.row].imagesFilenames)
    return cell
}

The images could be large, and to make the UITableViewController load as fast as possible I tried to perform loading images in the didSet section and also use a background thread:
class JournalSceneCell: UITableViewCell, UICollectionViewDataSource {

    @IBOutlet weak var entryTitle: UILabel!
    @IBOutlet weak var locationText: UILabel!
    @IBOutlet weak var desctiptionText: UILabel!
    @IBOutlet weak var editButton: UIButton!
    @IBOutlet weak var shareButton: UIButton!
    @IBOutlet var collectionViewRef: UICollectionView!

    convenience init() {
        self.init()
        self.collectionViewRef.dataSource = self
   }

    struct ImageEntry {
        var image:UIImage
        var imageURL:URL
    }

    let collectionCellID = "JournalCollectionCellID"

    var selectedImages = [ImageEntry]()

    var imagesFilename = [String]() {
        didSet {
            DispatchQueue.global(qos: .background).async {
                let documentURL = try! FileManager.default.url(for: .documentDirectory,
                                                               in: .userDomainMask,
                                                               appropriateFor: nil,
                                                               create: true)
                self.selectedImages.removeAll()
                for imageName in self.imagesFilename {
                    let imageURL = documentURL.appendingPathComponent(imageName)
                    let imageData = try! Data(contentsOf: imageURL)
                    let img = UIImage(data: imageData)!
                    self.selectedImages.append(ImageEntry(image: img, imageURL: imageURL))
                }
                DispatchQueue.main.async {
                    self.collectionViewRef.reloadData()
                }
            }
        }
    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return selectedImages.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionViewRef.dequeueReusableCell(withReuseIdentifier: collectionCellID,
                                                        for: indexPath) as? JournalCollectionCell else {
            fatalError("Cannot connect a collection cell")
        }

        cell.imageView.image = selectedImages[indexPath.row].image
        return cell

    }

}

The problem: JournalSceneCell does not call collectionView func from UICollectionViewDataSource at all. Everything is connected via IB, reuse identified was added, but nothing happened

A: You need to set
override func awakeFromNib() {
   super.awakeFromNib()
   self.collectionViewRef.dataSource = self
   self.collectionViewRef.delegate = self
}

class JournalSceneCell: UITableViewCell, UICollectionViewDataSource,UICollectionViewDelegate {

A: Reload collection view in tableView Cell,It will work
 cell.collectionViewRef.reloadData()

A: The convenience init() does not being called.
Finally I solve the problem by adding a func loadImages(fileNameArray:[String]) intoJournalSceneCell:
func loadImages(fileNameArray:[String]) {
    self.imageSetView.dataSource = self
    DispatchQueue.global(qos: .background).async {
        let documentURL = try! FileManager.default.url(for: .documentDirectory,
                                                       in: .userDomainMask,
                                                       appropriateFor: nil,
                                                       create: true)
        self.selectedImages.removeAll()
        for imageName in fileNameArray {
            let imageURL = documentURL.appendingPathComponent(imageName)
            let imageData = try! Data(contentsOf: imageURL)
            let img = UIImage(data: imageData)!
            self.selectedImages.append(ImageEntry(image: img, imageURL: imageURL))
        }

        DispatchQueue.main.async {
            self.imageSetView.reloadData()
        }

    }
}

Later I just called it from tableView(_:cellForRowAt:)
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = .. as? JournalSceneCell,
    cell.loadImages(fileNameArray:Array({...}))
    return cell
}

A: I was having a similar issue and it was because the UICollectionView wasn't even being drawn in the UITableViewCell, so I had to set a minimum height NSLayoutConstraint on the collection view.
You probably need the height of the UICollectionView to be dynamic though, in this case, but I'm not entirely sure your best route for that.


text:
Q: List of chart objects but not all plot I'm trying to collect a series of charts in a list then output them all in one run to Excel.
The list shows all the charts as "matplotlib.figure.Figure at (example) 0xb8eae80" but will not display all of them.  They all show in the iPython (in Spyder) console when the prog is run.
If I try to show them individually using list[i] in iPython, some charts show but some don't (the same charts are missing).
For the output to Excel, the  "missing" charts have a blank canvas of default size so, although XL is getting some info about the existence of a chart, it isn't even getting the "figsize" info.
The missing chart in the example code below is for the chart with multiple line plots (its a quick example, I realise it could be scripted better)
Thanks for any help.
Example code (which has same problem as my original code):
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import xlwings as xw

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
xdf = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD')) # splits out list into components
xdf = xdf.cumsum()

figlist = [] # set up list to collect charts (a list of objects)

fig = plt.figure()
xdf.A.plot(figsize = (9,5), grid=True) #plots individual column
plt.axhline(0,lw=2, color = "black")
plt.title('A')
figlist.append(fig)

fig = plt.figure()
xdf.B.plot(figsize = (9,5), grid=True) #plots individual column
plt.axhline(0,lw=2, color = "black")
plt.title('B')
figlist.append(fig)

fig = plt.figure()
xdf.C.plot(figsize = (9,5), grid=True) #plots individual column
plt.axhline(0,lw=2, color = "black")
plt.title('C')
figlist.append(fig)

fig = plt.figure()
xdf.D.plot(figsize = (9,5), grid=True) #plots individual column
plt.axhline(0,lw=2, color = "black")
plt.title('D')
figlist.append(fig)

fig = plt.figure()
xdf.plot(figsize = (9,5), grid=True) #plots all columns on same chart
plt.axhline(0,lw=2, color = "black")
plt.title('All')
figlist.append(fig)

# output all charts to XL
xw.Workbook() # open new workbook

for i in range(len(figlist)):
    plotno = 'Plot' + str(i)
    plot = xw.Plot(figlist[i])
    plot.show(plotno, left=30, top=(i*500+20))

A: You're not accessing the figure object correctly for plots generated by Pandas, from the docs:
import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.rand(10, 4), columns=['a', 'b', 'c', 'd'])
ax = df.plot(kind='bar')
fig = ax.get_figure()

in your case, something like
ax = xdf.plot(figsize = (9,5), grid=True) #plots all columns on same chart
plt.axhline(0,lw=2, color = "black")
plt.title('All')
figlist.append(ax.get_figure())

should do the trick for the last chart.


text:
Q: Convert API Response in JSON format to c# and print values I have an API response like below,
{
"Drivers.Pandemic.PeopleCount": {
"Value": "94",
"LastUpdatedTime": "2022-02-17T09:53:43.7418837+05:30",
"Status": "OK",
"HighLimit": 1000.0,
"LowLimit": 0.0,
"AlarmValue": null
},
"Drivers.Hospitality.Bollards": {
"Value": "1",
"LastUpdatedTime": "2022-02-17T09:53:42.5938448+05:30",
"Status": "OK",
"HighLimit": 1.0,
"LowLimit": 0.0,
"AlarmValue": null
},
"Drivers.Hospitality.FireAlarm": {
"Value": "0",
"LastUpdatedTime": "2022-02-17T09:53:02.1132161+05:30",
"Status": "OK",
"HighLimit": 1.0,
"LowLimit": 0.0,
"AlarmValue": "1"
}
}

I need to deserialize this response and print it using c#. How can I do this?

A: Well, as the JSON you're getting from the API is a little WEIRD youn need a little different aproach to the 'normal' serializacion.
Better aproach is to get help of a class with each element and a dictionary
Class:
public class Drivers
    {
        public string Value { get; set; }
        public DateTime LastUpdatedTime { get; set; }
        public string Status { get; set; }
        public double HighLimit { get; set; }
        public double LowLimit { get; set; }
        public object AlarmValue { get; set; }
    }

and then deserialize using Newtonsoft
var myDeserializedDict= JsonConvert.DeserializeObject<Dictionary<string, Drivers>>(text);

After this you got a 'normal' collection inside the Dictionary and can use it as you wish:
        foreach (KeyValuePair<string, Drivers> item in myDeserializedDict)
        {
            Console.WriteLine(item.Key + " (Status): " + item.Value.Status.ToString());
            Console.WriteLine(item.Key + " (LastUpdated): " + item.Value.LastUpdatedTime.ToString());
[...]
        }


text:
Q: Add coverity scan to Qt app I'm trying to add Coverity Scan static analysis to my Qt project but I'm not able to get the result.
I download the coverity scan build tools and use the following command line:
cov-build --dir cov-int make

Which produces the following log:
...
my build log
...
[WARNING] No files were emitted. This may be due to a problem with your configuration
or because no files were actually compiled by your build command.
Please make sure you have configured the compilers actually used in the compilation.
For more details, please look at:
    /Users/martin/dev/builds/ConsoleTest01-Desktop_Qt_5_3_clang_64bit-Debug/cov-int/build-log.txt

How can I go further?
I'm using Qt 5.3.2 under MacOS 10.9.

A: I didn't read the docs carefully enough: https://scan.coverity.com/download?tab=cxx
I had to configure coverity first by running:
cov-configure --comptype clangcxx --compiler clang++ --template

A: You need to run qmake first, then you can run the cov-int command with make.
I found it easiest to run cov-int in my build- folder created by Qt-Creator.


text:
Q: Videos com qualidade e o menor tamanho possível Tenho visto sites colocando um vídeo curto pra serem exibidos como se fossem background de uma div e fica muito lindo !
Alguém sabe orientar sobre como compactar ao máximo e os formatos adequados pra exibir nas ultimas versões do chrome/firefox sem perder muito a qualidade ?

A: MP4 é suficiente para o Firefox e o Chrome. Só no mobile não vai pegar, tem que ser WebM.


text:
Q: Progressive Web App: Error Accessing navigator.mediaDevices.getUserMedia? My app accesses the camera for purposes of webrtc, and works correctly.
I'm using pwacompat from Google Labs to add pwa features to my web app.
When running the app as a pwa, everything works fine until I access the camera. Then I get this console.log error:

getUserMedia failedObject {type: "error", msg: "undefined is not an object (evaluating 'navigat…"}
getUserMedia failed type: error msg: undefined is not an object (evaluating 'navigator.mediaDevices.getUserMedia')

What am I missing?

A: Update - 19/11/2020
WKWebView can use getUserMedia in iOS 14.3 beta 1.

*

*https://bugs.webkit.org/show_bug.cgi?id=208667

*https://bugs.chromium.org/p/chromium/issues/detail?id=752458
Update - 14/09/2019
There are changes to Safari on iOS 13 & Safari 13: https://developer.apple.com/documentation/safari_release_notes/safari_13_release_notes
SFSafariViewController has gained getUserMedia functionality (!!!, however I need to confirm this, please see below for reports of it working)

*

*https://bugs.webkit.org/show_bug.cgi?id=183201
However WKWebView does not seem to gain getUserMedia functionality:

*

*https://bugs.chromium.org/p/chromium/issues/detail?id=752458

*https://bugs.webkit.org/show_bug.cgi?id=185448
iOS 13 and Safari 13 release notes:

*

*https://developer.apple.com/documentation/ios_ipados_release_notes/ios_13_release_notes

*https://developer.apple.com/documentation/safari_release_notes/safari_13_release_notes
Edit
In short: A PWA or any website being used on iOS outside of the native Safari app will not be allowed access to getUserMedia as Apple is deliberately blocking access for "Security concerns". This includes any websites saved to the homescreen and/or viewed inside another application such as Facebook. The same restrictions apply to Android however on Android the app developer can ask for Camera permissions and get around this. (This means if you are a website developer and you need camera functionality, you will need to ask Facebook, etc, to rebuild their app to allow this on Android).
See their bug tracker here: http://www.openradar.me/33571214 and https://forums.developer.apple.com/thread/88052

From web based Safari experiences to Native Android, etc. I make crossplatform Apps in web and native for a living. There are several potential problems you will encounter with getUserMedia. To workout what is causing potential problems you should follow this list in order to create a successful application.
Your problem is specifically 1. because you are not successfully querying the API. Nevertheless the MediaCapture from getUserMedia should fail because after fixing 1. you will encounter 2. and 3.

*

*API Polyfil - Always make sure you include the latest getUserMedia adapter to stop any cross-platform inconsistencies in the getUserMedia API. Some browsers might use the old getUserMedia API (via 'navigator.getUserMedia) and have not been updated (to use navigator.mediaDevices.getUserMedia). You should also check this link for other needed polyfills.

*Support - Check CanIUse for getUserMedia support for your target audience and make sure you have the necessary fallbacks. Your fallback for if (navigator && navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { return true; } else return false; returns false, and if getUserMedia throws and error ideally should be the same.

*Permissions - Even though you include pwacompat it does not mean the browser window has the permissions to access the camera. This is because not all browsers are equal! iOS 11 allows getUserMedia access inside of the native Safari app only. However you cannot access getUserMedia on iOS 11 WKWebView or UIWebViews. When you save an app to the homepage it is hosted inside a WKWebView. Thus an experience which works inside of Safari will not work when saved to the homescreen or inside another application. Confusing eh?..! Thus if you want your experience to work you need to tell the user when they open upside another app that they must open the website in safari for real-time camera access. There is no way around this. On Android an app maker can override this permission and allow access to getUserMedia. If you use macOS or Windows you need to make sure the browser shell also has getUserMedia compatibility (e.g. Edge+, Chrome, Firefox, etc)

*Security - HTTPS websites can only access the camera (unless on localhost). Check the location prototcol '(location.protocol === 'https:') ? true : false;' to see if you are allowed to get a successful MediaCapture request

The following is a test link I use for platform support:
https://github.com/marcusbelcher/wasm-asm-camera-webgl-test
In my GitHub there are also Android and React-native getUserMedia solutions


text:
Q: How to remove blinking in leaflet with invalidateLater shiny It's an old problem which I think was never solved. Blinking in leaflet map when use invalidateLater().
Example
.
The app code:
library(shiny)
library(leaflet)

ui <- fluidPage(

            tags$style(type="text/css", ".recalculating { opacity: 1.0 !important; }"),

            leafletOutput("mymap")

      )

server <- function(input, output, session) {

      output$mymap <- renderLeaflet({

            invalidateLater(1000)
            leaflet(quakes[1:10,])%>%
                  addTiles() %>%
                  addMarkers()
      })
}

shinyApp(ui, server)

Joe Cheng recommended here
tags$style(type="text/css", ".recalculating { opacity: 1.0 !important; }")
and it's works perfectly fine e.g. in ggplot2 charts, but not in leaflet map.
Is there any workaround how to remove blinking in this app? Thanks!


text:
Q: D3.js AreaChart alignment issues I'm in need of a little assistance.  I have a stacked area chart in d3.js using ordinal for the x axis (and likely for the y as well but haven't implemented that yet) and while it's rendering, it's not quite right.  I need to figure out how to shift the chart (not the axis) so that the left most border is lined up vertically with the first tickmark and the rightmost is even with the last tickmark.
I've tried several variations and can't seem to figure out the starting x value.
Any help would be appreciated.
My x code
var x = d3.scale.ordinal().rangeRoundBands([0, width]);
x.domain(['Dec','Jan','Feb']); // Hard coded for now

var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom");

A js fiddle of the entire chart (with data):
http://jsfiddle.net/adeaver/FRNbq/6/

A: Have you tried:
var x = d3.scale.ordinal()
    .rangePoints([0, width]);

That may be what you are looking for.

A: This also works:
var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], 1, 0);


text:
Q: Call A method in controller from Nlog config I need to send an email every time the Nlog config writes into the database. Can i call a method in my controller from Nlog Config?

A: *

*You can call static methods from configuration: https://github.com/NLog/NLog/wiki/MethodCall-target

*You can send to an email from configuration: https://github.com/nlog/NLog/wiki/Mail-target
But since 1 is very clear about it, you need to have a static, public method which your controller isn't


text:
Q: EJB Timer goes off before scheduled time I'm creating a timer using javax.ejb.TimerService to start at a specific date and time, and thereafter expire periodically.
import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;

Date startDateTime = null;
DateTimeFormatter formatter = DateTimeFormat.forPattern("hh:mm a");
DateTime time = formatter.parseDateTime(ConfigProperties.getProperty("timer.starttime"));
DateTime dateTime = new DateTime().withTime(time.getHourOfDay(), time.getMinuteOfHour(), 0, 0);
startDateTime = dateTime.toDate();

long timerIntervalMs = Long.valueOf(ConfigProperties.getProperty("timer.interval.mins")) * 60 * 1000;
timerService.createTimer(startDateTime, timerIntervalMs, null);

The above initialization code is executed when my server boots up. However the timer expires while the server is still booting up (before startDateTime has been reached). Why is this happening? I'm trying this out on my local machine and startDateTime is initialized to a future time according to my local system clock.
After this first incorrect expiration, it works perfectly fine - expires at startDateTime and thereafter every timerIntervalMs ms.
I checked the documentation but didn't find anything pertinent to my problem -
http://docs.oracle.com/javaee/6/api/javax/ejb/TimerService.html#createTimer(java.util.Date, long, java.io.Serializable)


text:
Q: How to force input change trigger with ng-model-options's debounce in AngularJS? I'm testing my library. Problem is I have debounce in the textfield to avoid often updates.
Like
<input ... ng-model-options="{debounce: {'default': 500, 'blur': 0} }"

But I can't disable it in tests even I tried to trigger blur
it("""test input set with debounce""", function(){
    scope.obj = {
        name: 'John'
    }
    el = compileTemplate("<input ng-model=\"obj.name\" ng-model-options=\"{debounce: {'default': 500, 'blur': 0} }\"></input>")
    scope.$digest()
    input = el.find('input');
    expect(input.val()).toEqual('John');
    angular.element(input).val('Max').trigger('change').trigger('blur')
    scope.$apply()
    expect(scope.obj.name).toEqual('Max');
})

It'll fail because I have to add $timeout. So 10 tests = 5 seconds delay which is inappropriate.
How can I force change trigger to avoid debounce or trigger blur?

A: The mocked $timeout service has a flush method, you could use to trigger the update in unit tests.
it('should set with debounce', inject(function ($timeout) {
    input.val('Max').triggerHandler('input');
    $timeout.flush();
    expect(scope.obj.name).toEqual('Max');
}));

A: Seems like just using $timeout even without delay does the trick:
$timeout(function(){
    expect(scope.obj.name).toEqual('Max');
})


text:
Q: Traffic control with tc qdisc taprio Currently, I am working on a TSN project and I am trying to implement a TSN scenario in a Ubuntu 20.04 VM.
I leverage on tc qdisc command:
tc qdisc replace dev gateway-eth0 parent root handle 100 taprio \
num_tc 8 \
map 0 1 2 3 4 5 6 7 1 1 1 1 1 1 1 1 \
queues 1@0 1@1 1@2 1@3 1@4 1@5 1@6 1@7 \
base-time 1000 \

clockid CLOCK_TAI \

sched-entry S 10 300000 \
sched-entry S 32 500000 \
sched-entry S 128 200000 \

And also mangle the iptables to classify the packets based on the dscp field.
ip6tables
From what I have read, with this qdisc command I define:
i) 8 traffic classes
ii) map priority 0 to TC0, 1 to TC1 2 to TC2 etc.
iii) TC0 is mapped to one TX queue TX-0, TC1 to TX-1, TC2 to TX2 etc.
In the sched-entry part of the command, my goal is to open TC2 and TC5, and TC7 queues for different periods.
To test this I sent ping packets using ping -Q 0x40 <IP> in order to send packets to traffic class 5.
Are the sched-entries right?
Thank you.


text:
Q: Java putting set into map Whats the quickest way to put a set into a map?
public class mySet<T>
{
    private Map<T, Integer> map;

    public mySet(Set<T> set)
    {
        Object[] array = set.toArray();

        for(int i =0; i< array.length; i++)
        {
            T v = (T)array[i];
            map.put(v, 1);
        }
    }
}

Right now, I just converted set into an array and loop through the array and putting them in one by one. Is there any better way to do this?

A: One options would be this:
for (T value : set) {
  map.put(value, 1);
}

A: The quickest way is to not put it into a new Map at all but instead create your own dynamic implementation of the Map interface that dynamically delegates requests to the set instance. Of course this will only work if you need a live view of the Map or the set is immutable. Also depending on the API you require on Map, this might become a lot of work, however AbstractMap will help you a lot here.


text:
Q: Global array in C header? Okay, strange question time!
I'm refactoring some old C++ code that declares a bunch of arrays like so:
static SomeStruct SomeStructArray[] = {
    {1, 2, 3},
    {4, 5, 6},
    {NULL, 0, 0}
}

And so forth. These are scattered about in the source files, and are used right where they're declared.
However, I would like to move them into a single source file (mostly because I've come up with a way of auto-generating them). And, of course, I naively try to make a header for them:
static SomeStruct SomeStructArray[];

Actually, even I know that's wrong, but here's the compiler error anyway:
error C2133: 'SomeStructArray' : unknown size    arrays.h
error C2086: 'SomeStruct SomeStructArray[]' : redefinition    arrays.cpp

So, I guess, what's the right way to do this?

A: If you're going to put the arrays themselves all in one file (and apparently access them from other files) you need to remove the static from the definitions (which makes them visible only inside the same translation unit (i.e., file)).
Then, in your header you need to add an extern to each declaration.
Finally, of course, you'll need to ensure that when you have an array of SomeStruct (for example), that the definition of SomeStruct is visible before you attempt to define an array of them.

A: Try to use
.h file:
extern SomeStruct SomeStructArray[];

.cpp file:
extern SomeStruct SomeStructArray[] = {
  {1, 2, 3},
  {4, 5, 6},
  {NULL, 0, 0}
}

A: Create a header file and put this in it:
extern SomeStruct SomeStructArray[];

then put your existing code into a source file (not a header file):
SomeStruct SomeStructArray[] = {
    {1, 2, 3},
    {4, 5, 6},
    {NULL, 0, 0}
}

And the downside, you can't get the size of the array in other source files:
size_t size = sizeof SomeStructArray; // doesn't work in any source file apart
                                      // from the one defining the array.

You could add extra variables to get around this.
This was tested using DevStudio2k5.


text:
Q: Is it possible to run Node.js modules on browser using Chrome extension For my college project, I'm creating a Chrome extension to perform certain checks and validations for each URL the user visits on his browser. My aim is to alert the user when a suspicious site is detected using Chrome extension. So for this purpose, I need to use certain NPM modules such as whois-json, get-ssl-certificate and so on. So, since Node.js cannot run on the browser directly, I tried using Browserify module to convert this Node.js code such as require and module execution into plain Javascript bundle file. So, when I try to run this Javascript bundle using the Chrome extension, I get an error as:

"net.connect" is not a function

Is there any possible way to fix this error? Or can I use another solution as an alternative to Browserify to run my Node.js modules on the Chrome Extension.

A: No, you won't be able to use Node.js modules that use server-specific code in a Chrome extension. You have a few options here though.

*

*You could look for alternative modules that use browser APIs and use those instead.

*You could look for public REST APIs that achieve what your Node.js modules are doing.

*You could create your own REST API with the existing Node.js code you have, and then interface with that from your client-side Chrome extension.


text:
Q: When scraping from a webpage, the html isn't the same as when I inspect element? I'm trying to web scrape this website: https://www.footballindex.co.uk/top-200
More specifically I want to scrape the name, buy price, sell price of every player.
This is my code I used to get the web html:
import requests
from bs4 import BeautifulSoup

URL = "https://www.footballindex.co.uk/top-200"
page = requests.get(URL)
Soup = BeautifulSoup(page.text, "html.parser")
print(Soup)

When I print out the html the information I'm looking for doesn't come out under a relevant variable like in the inspect element. It comes out in one long line of code as below. (I've cut it off but it does this for every player on the page).

 window.__PRELOADED_STATE__ = {"tradingReducer":{"adjustedPrice":0,"isLoading":false},"playersReducer":{"players":[{"id":"phil-foden","name":"Phil Foden","rank":14,"country":"England","nationalTeam":null,"sector":"Midfielder","nationality":"England","team":"Manchester City","optimized_image":"phil-foden-g-t4.jpg","buyPrice":5.93,"sellPrice":5.87,"penceChange":0.12,"changePercent":2.05},{"id":"bruno-fernandes","name":"Bruno Fernandes",

I tried also using Selenium but it just gave me the data in the same place. From other posts I've read and info I've found it sounds like it's because the website uses Java to load the prices of players especially. On the page they're constantly updating every few seconds.
The code seems to be in JSON format. But I've been completely stumped as to how I can extract the information into python so I can capture each player and their relevant buy price.
I've tried using the find and find_all functions but every time it doesn't seem to extract any data.
Does anyone know what code I need to use to correctly extract the variables I want from the html?

A: My way around it - may not be the best - is to use selenium to make sure that a javascript loads all data and then pass this HTML to beautifulsoup to parse and use regex to match data needed. time.sleep is used to make sure that all data in Java is loaded. You can experiment with it and lower it as needed to speed up your script.

from selenium import webdriver
import time
from bs4 import BeautifulSoup
import re

browser = webdriver.Firefox()
browser.set_window_size(700,900)

url = 'https://www.footballindex.co.uk/top-200'

browser.get(url)
time.sleep(4)

html = browser.execute_script('return document.documentElement.outerHTML')

all_html = BeautifulSoup(html,'lxml')
root = all_html.find('div', {'class':'List__container___1xBmN'})

all_buy_prices= re.findall('(buy" type="button">)(\£\d+\.\d+)(</button>)', str(root))

buy_price= all_buy_prices
print('Buy prices:')
print(str(buy_price))

browser.quit()

This will get you main Div of the page with all data. Now, you can user REGEX to find some data you need.

Name

Team

Country

Position

24h

Watchlist

<button class="Dropdown__dropdown__button___9QeA8" type="button">Price inc. £</button>

8

P.PogbaManchester United

£0.19

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£7.92</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£8.06</button>

11

M.GreenwoodManchester United

£0.16

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£6.24</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£6.33</button>

2

B.FernandesManchester United

£0.09

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£10.13</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£10.35</button>

132

R.BrewsterSwansea City

£0.07

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£1.99</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£2.07</button>

131

S.BergwijnTottenham Hotspur

£0.06

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£1.96</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£2.08</button>

100

M.AsensioReal Madrid

£0.03

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£2.18</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£2.26</button>

144

R.OrsoliniBologna

£0.03

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£1.83</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£2.00</button>

181

L.GoretzkaFC Bayern München

£0.03

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£1.64</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£1.73</button>

17

A.FatiBarcelona

£0.02

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£4.66</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£4.88</button>

25

A.DaviesFC Bayern München

£0.02

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£4.02</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£4.32</button>

119

A.AouchicheParis Saint-Germain

£0.02

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£1.92</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£2.13</button>

129

B.WilliamsManchester United

£0.02

<button class="Button__sell-background___Pu5NC Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG SellButton__price___3omkd tradingMedium SellButton__default___2LgzG" id="sell" type="button">£1.97</button><button class="Button__buy-background___3wyrT Button__button___3_Ozh Button__tradingMedium___TOIwW Button__yellow-glow___20bvG BuyButton__price___1Ylr9 tradingMedium" id="buy" type="button">£2.08</button>

5

', '£8.08', '</button>'), ('buy" type="button">', '£6.33', '</button>'), ('buy" type="button">', '£10.36', '</button>'), ('buy" type="button">', '£2.09', '</button>'), ('buy" type="button">', '£2.08', '</button>'), ('buy" type="button">', '£2.00', '</button>'), ('buy" type="button">', '£2.26', '</button>'), ('buy" type="button">', '£1.73', '</button>'), ('buy" type="button">', '£6.09', '</button>'), ('buy" type="button">', '£4.88', '</button>'), ('buy" type="button">', '£4.32', '</button>'), ('buy" type="button">', '£2.13', '</button>'), ('buy" type="button">', '£2.08', '</button>'), ('buy" type="button">', '£5.16', '</button>'), ('buy" type="button">', '£4.03', '</button>'), ('buy" type="button">', '£3.48', '</button>'), ('buy" type="button">', '£3.35', '</button>'), ('buy" type="button">', '£3.31', '</button>'), ('buy" type="button">', '£3.18', '</button>'), ('buy" type="button">', '£3.14', '</button>'), ('buy" type="button">', '£2.95', '</button>'), ('buy" type="button">', '£2.90', '</button>'), ('buy" type="button">', '£2.85', '</button>'), ('buy" type="button">', '£2.81', '</button>'), ('buy" type="button">', '£2.79', '</button>'), ('buy" type="button">', '£2.79', '</button>'), ('buy" type="button">', '£2.75', '</button>'), ('buy" type="button">', '£2.63', '</button>'), ('buy" type="button">', '£2.62', '</button>'), ('buy" type="button">', '£2.56', '</button>'), ('buy" type="button">', '£2.55', '</button>'), ('buy" type="button">', '£2.53', '</button>'), ('buy" type="button">', '£2.50', '</button>'), ('buy" type="button">', '£2.47', '</button>'), ('buy" type="button">', '£2.43', '</button>'), ('buy" type="button">', '£2.38', '</button>'), ('buy" type="button">', '£2.37', '</button>'), ('buy" type="button">', '£2.36', '</button>'), ('buy" type="button">', '£2.30', '</button>'), ('buy" type="button">', '£2.28', '</button>'), ('buy" type="button">', '£2.25', '</button>'), ('buy" type="button">', '£2.21', '</button>'), ('buy" type="button">', '£2.20', '</button>'), ('buy" type="button">', '£2.19', '</button>'), ('buy" type="button">', '£2.17', '</button>'), ('buy" type="button">', '£2.09', '</button>'), ('buy" type="button">', '£2.08', '</button>'), ('buy" type="button">', '£2.04', '</button>'), ('buy" type="button">', '£2.02', '</button>'), ('buy" type="button">', '£2.02', '</button>'), ('buy" type="button">', '£2.01', '</button>'), ('buy" type="button">', '£1.90', '</button>'), ('buy" type="button">', '£1.86', '</button>'), ('buy" type="button">', '£1.85', '</button>'), ('buy" type="button">', '£1.84', '</button>'), ('buy" type="button">', '£1.81', '</button>'), ('buy" type="button">', '£1.80', '</button>'), ('buy" type="button">', '£1.80', '</button>'), ('buy" type="button">', '£1.79', '</button>'), ('buy" type="button">', '£1.77', '</button>'), ('buy" type="button">', '£1.75', '</button>'), ('buy" type="button">', '£1.74', '</button>'), ('buy" type="button">', '£1.73', '</button>'), ('buy" type="button">', '£1.70', '</button>'), ('buy" type="button">', '£1.69', '</button>'), ('buy" type="button">', '£1.69', '</button>'), ('buy" type="button">', '£1.68', '</button>'), ('buy" type="button">', '£1.66', '</button>'), ('buy" type="button">', '£1.64', '</button>'), ('buy" type="button">', '£1.64', '</button>'), ('buy" type="button">', '£1.64', '</button>'), ('buy" type="button">', '£1.63', '</button>'), ('buy" type="button">', '£6.05', '</button>'), ('buy" type="button">', '£4.40', '</button>'), ('buy" type="button">', '£4.01', '</button>'), ('buy" type="button">', '£3.67', '</button>'), ('buy" type="button">', '£3.49', '</button>'), ('buy" type="button">', '£2.96', '</button>'), ('buy" type="button">', '£2.69', '</button>'), ('buy" type="button">', '£2.58', '</button>'), ('buy" type="button">', '£2.39', '</button>'), ('buy" type="button">', '£2.31', '</button>'), ('buy" type="button">', '£2.26', '</button>'), ('buy" type="button">', '£2.20', '</button>'), ('buy" type="button">', '£2.19', '</button>'), ('buy" type="button">', '£2.11', '</button>'), ('buy" type="button">', '£2.09', '</button>'), ('buy" type="button">', '£2.08', '</button>'), ('buy" type="button">', '£2.05', '</button>'), ('buy" type="button">', '£2.01', '</button>'), ('buy" type="button">', '£1.99', '</button>'), ('buy" type="button">', '£1.99', '</button>'), ('buy" type="button">', '£1.95', '</button>'), ('buy" type="button">', '£1.89', '</button>'), ('buy" type="button">', '£1.89', '</button>'), ('buy" type="button">', '£1.85', '</button>'), ('buy" type="button">', '£1.83', '</button>'), ('buy" type="button">', '£1.82', '</button>'), ('buy" type="button">', '£1.69', '</button>'), ('buy" type="button">', '£1.68', '</button>')]

I recommmend https://pythex.org/ where you can test your regex without having to run script every time.


text:
Q: Chef - puts message in end of chef-client run? Is it possible to print out a message in the end of a chef-client run? Something like:
######################

Attention: blablabla

######################
Chef Client finished, 19/222 resources updated in 18 seconds

Thank you in advance

A: you can laverage event handlers, and it would look something like:
Chef.event_handler do
  on :run_completed do
    puts "Attention: blablabla"
  end
end


text:
Q: Convert int to two bytes in hex? Context: I'm working on a lighting protocol converter for architectural LED matrices and need to encode byte strings in a very specific way for the headers to be recognized by my hardware.
Q: How can I convert an int into two bytes such that I can then use them separately?
Example:
I want to convert
var aDynamicValue = 511 //where value will range from 0-511

to a list like: [0x01, 0xFF]
Such that I can then
<BytesBuilder> magicString.add(--the bytes above--)

Thanks

A: Use bit shifting together with logical AND to mask out all but first 8 bits. Pseudo code:
a = 511;
byte1 = a & 0xff;
byte2 = (a >> 8) & 0xff;

A: typed_data and int.toRadixString(16) can be used to get hex from integers:
final list = new Uint64List.fromList([511]);
final bytes = new Uint8List.view(list.buffer);
final result = bytes.map((b) => '0x${b.toRadixString(16).padLeft(2, '0')}');
print('bytes: ${result}');


text:
Q: filtering on visualisation metrics in Kibana I'm trying to apply a filter to line visualisations in Kibana 4.5.1. I have an index (xscores) with two different types (sd and sma), here is a sample:
 {
        "_index": "xscore",
        "_type": "xscore",
        "_id": "AVgAejjHwGMH9TPDlF04",
        "_score": 1,
        "_source": {
           "id": "AVgAejjHwGMH9TPDlF04",
           "value": 0.019607843137254926,
           "timestamp": 1477476480000,
           "minutes": 1,
           "type": "sma"
        }

I am trying to show the sum only for sma and the average only for sd by adding a filter in the json box. However I always get a search_phase_execution_exception. This is the code that Kibana sends to elasticsearch:
  {"query": {
"filtered": {
  "query": {
    "query_string": {
      "analyze_wildcard": true,
      "query": "*"
    }
  },
  "filter": {
    "bool": {
      "must": [
        {
          "range": {
            "timestamp": {
              "gte": 1477436400000,
              "lte": 1477522799999,
              "format": "epoch_millis"
            }
          }
        }
      ],
      "must_not": [

      ]
    }
  }
}},"size": 0,"aggs": {
"3": {
  "date_histogram": {
    "field": "timestamp",
    "interval": "30m",
    "time_zone": "Europe\/London",
    "min_doc_count": 1,
    "extended_bounds": {
      "min": 1477436400000,
      "max": 1477522799999
    }
  },
  "aggs": {
    "4": {
      "terms": {
        "field": "type",
        "size": 5,
        "order": {
          "1": "desc"
        }
      },
      "aggs": {
        "1": {
          "avg": {
            "field": "value"
          }
        },
         "2": {
          "sum": {
            "field": "value",
            "filter": {
              "term": {
                "type": "sma"
              }
            }
          }
        }
      }
    }
  }
}}}

The problem is in the last area I think but can't figure out what exactly is wrong.
Running the same query in ES returns the following error:
"shard": 0,
        "index": "xscore",
        "node": "mszD3Y_4T-aGNEkVtt4BCg",
        "reason": {
           "type": "search_parse_exception",
           "reason": "Unexpected token START_OBJECT in [2]."

I'm using ES 2.3 and Kibana 4.5 on a MacOS 10.10.


text:
Q: Saving user in cookie (headers already sent) I'm creating a multiplayer game in NodeJS using Express and socket.io. Most of the back-end is working, now I'm trying to create the front-end.
Really struggling trying to do the following:
A player opens the website for the first time > create a player in the database and remember the player.
When a player comes again another time we should read the cookie and log the player in again.
My code I have so far:
// app.js
app.get('/', function(req, res){

    if(!req.signedCookies.player) {

        var Player = new player();

        Player.on('playerLoaded', function(err, result) {
            if(result) {
                res.cookie('player', Player.id.toString(), { signed: true});
            }
        });

    } else {
        console.log(req.signedCookies.player);
    }

    res.render('index', { title: 'My Game' });

});

This line gives a Error: Can't set headers after they are sent.
res.cookie('player', Player.id.toString(), { signed: true});

What's happing at that line:
Player.prototype.createPlayer = function () {
    var self = this;

    // we only need a datetime to insert
    connection.query("INSERT INTO players SET `created_at` = now()", function (err, result) {
        process.nextTick(function () {
            if(result) {
                console.log("Successfully created player no. " + result.insertId);

                self.id = result.insertId;

                self.emit('playerLoaded', false, true);
            } else {
                console.log("Trouble inserting a new player");

                self.emit('playerLoaded', true, false);
            }
        });
    });
};

Then the exact error is happing at this line:
self.emit('playerLoaded', false, true);

So my questions are:

*

*Am I at least going in the right direction in terms of achieving my goal of creating a new player and saving it in a cookie? If not, could someone please help me?

*If question one is true, why is it giving a error?

A: Cookies is a part of Response Header. They must be set before first write() call. This is why the error. Set cookie before first res.write() or res.writeHead() call to fix the error.
This code should work for you.
// app.js
app.get('/', function(req, res){

  if(!req.signedCookies.player) {
    var Player = new Player();
    Player.on('playerLoaded', function(err, result) {
      if(result) {
        res.cookie('player', Player.id.toString(), { signed: true});
      }
      res.render('index', { title: 'My Game' });
    });

  } else {
      res.render('index', { title: 'My Game' });
      console.log(req.signedCookies.player);
  }

});

A:
Am I at least going in the right direction in terms of achieving my goal of creating a new player and saving it in a cookie? If not, could someone please help me?

Not sure about your design. Saving a reference to the player might make it very easy to log in as a different player, depending on how you identify them. It might be safer to have some kind of session management, and then to link a user session with some player.

If question one is true, why is it giving a error?

Because creating a player is asynchronous - you're hooking on a playerLoaded callback. That means res.render will be called immediately, before res.cookie will - and so the response body is already written (and the headers send) before you try to set the cookie header.

A: This fixed my initial problem of the headers sent. Also changed the code to use sessions instead.
if(!req.session.player) {
    var Player = new player();

    Player.on('playerLoaded', function(err, result) {
        if(result) {
            req.session.player = Player;
            res.render('index', { title: 'My Game' });
        }
    });
} else {
    console.log(req.session.player);
    res.render('index', { title: 'My Game' });
}


text:
Q: Create report of all fields within all feature classes/tables in ArcSDE database? I am looking to generate a report of all the fields for each feature class/table in an ArcSDE database. I'm using ArcGIS Desktop 10.2. I've written the following code, which gets the job done, but it isn't pretty code, or a pretty output .txt file.
The output is a text file, but what other format would be easy for non-GIS/non-techy users to access/view?
I thought about writing to excel and doing a tab for every FC, but that wouldn't be super user friendly. I am wondering if I could get some advice on how to pretty up the output, or if there is a previous question that covers this topic.
Also, it is important to note that I have some fields with aliases that are over 80 characters long, so the way I currently format the output .txt file results in a very long and unprintable file.
Here's my entire code:

import arcpy, os

#Write script that outputs the field name, alias, type, length, etc.
#For every feature class and table in my proposed tables
docPath = 'C://GIS//GDB_Summary.txt'
doc = open(docPath, 'w')

arcpy.env.workspace = 'Database Servers\NB2498_AARONGIS.gds\Equipment_Inventory (VERSION:dbo.DEFAULT)'
fcList = arcpy.ListFeatureClasses(feature_dataset='Equipment_Inventory.DBO.Inventory')
tableList = arcpy.ListTables()
message = ''

# Find the max length of any value that will appear in the output
lengthList = []
for fc in fcList:
    for field in arcpy.ListFields(arcpy.Describe(fc).name):
        lengthList.append(field.name)
        lengthList.append(field.aliasName)
        lengthList.append(field.type)
        lengthList.append(field.length)
        lengthList.append(field.domain)
for table in tableList:
    for field in arcpy.ListFields(arcpy.Describe(table).name):
        lengthList.append(field.name)
        lengthList.append(field.aliasName)
        lengthList.append(field.type)
        lengthList.append(field.length)
        lengthList.append(field.domain)

# Set the length of spaces between values and the length of the div lines
spaceLength = (max(len(str(s)) for s in lengthList))
divLine_Length = spaceLength*5
indent = ' ' *(spaceLength//3)
n = '\n'
message += '\n***** Feature Classes ' + '*'*(divLine_Length-23)

# Loop through feature classes and add their values to message
for fc in fcList:
    desc = arcpy.Describe(fc)
    name = desc.name
    header = n + name + n + '-'*divLine_Length + n
    message += header
    columnList = ['Field Name', 'Field Alias', 'Field Type', 'Field Length', 'Field Domain']
    for column in columnList:
        if column == 'Field Name':
            spacing = ' '*(spaceLength-int(len(column)))
            message += column + spacing
        else:
            spacing = ' '*(spaceLength-int(len(column)))
            message += indent + column + spacing
    message += n
    for field in arcpy.ListFields(name):
        # Field Name
        spacing = ' '*(spaceLength-int(len(field.name)))
        message += field.name + spacing
        # Field Alias
        spacing = ' '*(spaceLength-int(len(field.aliasName)))
        message += indent + field.aliasName + spacing
        # Field Type
        spacing = ' '*(spaceLength-int(len(field.type)))
        message += indent + field.type + spacing
        # Field Length
        spacing = ' '*(spaceLength-int(len(str(field.length))))
        message += indent + str(field.length) + spacing
        # Field Domain
        spacing = ' '*(spaceLength-int(len(field.domain)))
        message += indent + field.domain + spacing + n

# Loop through tables and add their values to message
message += '\n***** Tables ' + '*'*(divLine_Length-13)
for table in tableList:
    desc = arcpy.Describe(table)
    name = desc.name
    header = n + name + n + '-'*divLine_Length + n
    message += header
    columnList = ['Field Name', 'Field Alias', 'Field Type', 'Field Length', 'Field Domain']
    for column in columnList:
        if column == 'Field Name':
            spacing = ' '*(spaceLength-int(len(column)))
            message += column + spacing
        else:
            spacing = ' '*(spaceLength-int(len(column)))
            message += indent + column + spacing
    message += n
    for field in arcpy.ListFields(name):
        # Field Name
        spacing = ' '*(spaceLength-int(len(field.name)))
        message += field.name + spacing
        # Field Alias
        spacing = ' '*(spaceLength-int(len(field.aliasName)))
        message += indent + field.aliasName + spacing
        # Field Type
        spacing = ' '*(spaceLength-int(len(field.type)))
        message += indent + field.type + spacing
        # Field Length
        spacing = ' '*(spaceLength-int(len(str(field.length))))
        message += indent + str(field.length) + spacing
        # Field Domain
        spacing = ' '*(spaceLength-int(len(field.domain)))
        message += indent + field.domain + spacing + n

# Write to text file, save it, and open the file to view
#print(message)
doc.write(message)
doc.close()
os.startfile(docPath)


text:
Q: using irrlicht with mingw I'm using mingw-w64 (gcc 4.9.2)
I downloaded irrlicht
I tried an example

C:\dev\irrlicht-1.8.1\irrlicht-1.8.1\lib\Win32-gcc>x86_64-w64-mingw32-g++
  -I../ ../include/ -L. -lIrrlicht test.cpp  C:/Program Files (x86)/CodeBlocks/mingw-w64/mingw64/bin/../lib/gcc/x86_64-w64-mi
  ngw32/4.9.2/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping
  incompatible ./l ibIrrlicht.a when searching for -lIrrlicht
C:/Program Files
  (x86)/CodeBlocks/mingw-w64/mingw64/bin/../lib/gcc/x86_64-w64-mi
  ngw32/4.9.2/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping
  incompatible ./I rrlicht.dll when searching for -lIrrlicht
C:/Program Files
  (x86)/CodeBlocks/mingw-w64/mingw64/bin/../lib/gcc/x86_64-w64-mi
  ngw32/4.9.2/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping
  incompatible .\l ibIrrlicht.a when searching for -lIrrlicht
C:/Program Files
  (x86)/CodeBlocks/mingw-w64/mingw64/bin/../lib/gcc/x86_64-w64-mi
  ngw32/4.9.2/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping
  incompatible ./l ibIrrlicht.a when searching for -lIrrlicht
C:/Program Files
  (x86)/CodeBlocks/mingw-w64/mingw64/bin/../lib/gcc/x86_64-w64-mi
  ngw32/4.9.2/../../../../x86_64-w64-mingw32/bin/ld.exe: skipping
  incompatible ./I rrlicht.dll when searching for -lIrrlicht
C:/Program Files
  (x86)/CodeBlocks/mingw-w64/mingw64/bin/../lib/gcc/x86_64-w64-mi
  ngw32/4.9.2/../../../../x86_64-w64-mingw32/bin/ld.exe: cannot find
  -lIrrlicht collect2.exe: error: ld returned 1 exit status

it seems the library Irrlicht.a provided isn't compatible with my compiler.
so I tried to recompile the library
as indicated in the Makefile, I ran mingw32-make win32
and then I get another error :
<builtin>: recipe for target 'zlib/adler32.o' failed
mingw32-make: *** [zlib/adler32.o] Error 1

can anybody help (note that I don't want to use vc++)

A: the problem was the Irrlicht.a provided was a 32bit library where i was compiling for 64bits, so I had to use a 32bit compiler instead.


text:
Q: If $f $has a removable singularity $1/f$ has a removable singularity or a pole Let $f$ be analytic in $D_r(z_0)$ \ {$z_0$}. I am trying to prove that if $f$ has a removable singularity at $z_0$, then $1/f$ has either a removable singularity or a pole at $z_0$. My proof: Since $f$ has a removable singularity at $z_0$ it can be redefined at $z_0$ so that $f$ is analytic in $D_r(z_0). $ Suppose $f(z_0)=w$.
Case I: $w=0$
 Then $f$ has a zero of some finite order at $z_0$. Thus $1/f$ has a pole of the same order at $z_0$
Case II: $w\neq0$
Then $f(z)\neq0$ on some disk $D_R(z_0)$ where $0<R\leq r$. Thus $1/f$ is analytic in  $D_R(z_0)$. So $\lim_{z\rightarrow z_0}(1/f(z))$ exits. Thus, $1/f$ has a removable singularity at $z_0$.
This is my proof. If there are any mistakes please point them out I would much appreciate it. Thanks
Alternate way of proving there is a pole  Since $f(z_0)=0$ $$\lim_{z\rightarrow z_0}|1/f(z)|\rightarrow \infty$$. So $z_0$ is a pole of $1/f$

A: Another method:
If $f$ has a removable singularity at $z_0$ then in some punctured disk it can be represented uniquely in a Laurent series with all $b_k=0$. Say, $f=a_0+a_1(z-z_0)+O((z-z_0)^2)$. If $a_0\neq 0$ then $1/f=1/a_0(1+a_1/a_0 (z-z_0)+ O((z-z_0)^2)$ via a geometric expansion. If $a_0=0$ then $1/f= 1/a_j(z-z_0)^j (1+ a_{j+1}/a_j (z-z_0) +O((z-z_0)^2))$ so $1/f$ has a pole of order $j$ where $a_j$ is the first nonzero term in the Laurent expansion of $f$.


text:
Q: Linked List vs. Trees on the Heap I am told that linked lists must be implemented on the heap, but trees can be implemented on the stack? The case the the tree is implemented on the stack is one where there is no removal. If we were to implement the trees with removal, would we need to implement in on the heap?
I'm only familiar with dynamic memory in C++ (not sure if this gives any context to my question).


text:
Q: gitignore fails to ignore files/folders with whitespaces This is my .gitignore file:
Textfusion\ Pro/bin/Debug/
Textfusion\ Pro/bin/Release/
.gitignore
.vs/

But If I execute git status then the folder is still appearing.

I also tried it like this:

*

*Textfusion Pro/bin/Release/

*Textfusion*Pro/bin/Release/

*"Textfusion Pro"/bin/Release/

*"Textfusion Pro/bin/Release/"

A: Your files are already in the repository. You have to git rm them (note that you should specify the --cached option to git rm if you don't want them to be deleted). After that, they should be ignored if you write it like Textfusion Pro/bin/Release/ in the .gitignore file.
Note that even after you do that and commit, they will still be in the repository history, taking up space. There are questions on Stackoverflow that explain how to rewrite the git history.


text:
Q: IR tx/rx issues for YS-IRTM receiver/transmitter I've connected YS-IRTM v3.06 IR receiver/transmitter using softuart
like described in the project

For some reason with code below, IR is receiving one byte per single serial write.
I've tried to shield sensor from IR diode in case these two are interfering with each other but with no success.
How to avoid such unexpected behaviour?
s = softuart.setup(9600, 6, 5)

I_HANDLER = tmr.create()
I_HANDLER:register(900, tmr.ALARM_AUTO, function(t)
    s:write(encoder.fromHex("a1f1" .. "01fe40"))
end)
I_HANDLER:start()

s:on("data", 3, function(data)

    print("INPUT: "..encoder.toHex(data))
end)

Output
INPUT: f1f1f1
INPUT: f1f1f1
INPUT: f1f1f1
....

Nodemcu is
NodeMCU 3.0.0.0 built on nodemcu-build.com provided by frightanic.com
    branch: master
    commit: 8d091c476edf6ae2977a5f2a74bf5824d07d6183
    release: 3.0-master_20200610
    release DTS: 202006092026
    SSL: false
    build type: integer
    LFS: 0x0 bytes total capacity
    modules: encoder,file,gpio,http,mqtt,net,node,rfswitch,sjson,softuart,tmr,uart,wifi,wifi_monitor
 build 2020-08-12 12:12 powered by Lua 5.1.4 on SDK 3.0.1-dev(fce080e)


text:
Q: Passing JSON Values Into POST Request - Node I have the following index.js file;
var Lob = require('lob')('test_6afa806011ecd05b39535093f7e57757695');

var residence = require('./addresses.json');

console.log(residence.residence.length);

for (i = 0; i < residence.residence.length; i++) {
    console.log(residence.residence[i].name);

    Lob.addresses.create({
        name: 'residence.residence[i].name',
    }, function(err, res) {
        console.log(err, res);
    });
}

When I console.log( residence.residence[i].name ), the appropriate response "RESIDENT" appears.
However, I'm trying to pass in that same value as a value in the post request under Lob.addresses.create({ which isn't recognizing it.
How do I pass in that value into my key value pair as the value for "name:"?

A: It appears that you are passing in a literal String 'residence.residence[i].name' because of your use of quotes... Drop the quotes:
for (i = 0; i < residence.residence.length; i++) {
    console.log(residence.residence[i].name);

    Lob.addresses.create({
        name: residence.residence[i].name,
    }, function(err, res) {
        console.log(err, res);
    });

}


text:
Q: styling a bootstrap dropdown menu I'm not sure why my CSS is not hitting my HTML and styling it correctly.
HTML:

    Page 2

Page 2.0.0

Page 2.0.1

Page 2.0.2

CSS:
.dropdown-menu li:hover{
    background-color: green;
}

The class dropdown-menu should be hit and then when you hover over the li's inside it. I have tried adding an id as dropdown menu and changing the CSS to #dropdown-menu but it made no difference.
Also, is there an easy way to find out exactly how to hit the appropriate element as I find this is a frequent problem?

A: Ok here we go,
here is the working solution of your problem,
.dropdown-menu > li > a:focus,
.dropdown-menu > li > a:hover {
    clear: both;
   background-color: green !important;
   background-image:none !important;
    display: block;
    font-weight: 400;
    line-height: 1.42857;
    padding: 3px 20px;
    white-space: nowrap;
    color: black !important;
}

i have just edited your code
          http://jsfiddle.net/bf1cyptm/1/
:)

A: Try adding !important in CSS like:
.dropdown-menu li a:hover{
    background-color:green !important;
}

If it does not work it could possibly be some other CSS code that is not letting it happen. So the solution to it is to do an inspect element and see which element is affecting it.
If you are not expert in than a best solution for you.
Please add a new class just after dropdown-menu like:

and call CSS by it like:
.colorchange li a:hover{

    background-color: green;

}

It should work! You can use important here as well.

A: Try this
 .dropdown-menu li:hover .dropdown-menu li a{
        color: green;
    }


text:
Q: print "Enter a character " a = gets if (a == 'b') puts "b was pressed" end I am a new learner to Ruby. I also tried
print "Enter a character "
a = gets
if (a == "b")
  puts "b was pressed"
end

And this as well
print "Enter a character "
a = gets.to_s
if (a == 'b')
  puts "b was pressed"
end

A: You missed the method String#chomp. Change your code as below :
print "Enter a character "
a = gets.chomp
if (a == "b")
  puts "b was pressed"
end

Now run your code:
kirti@kirti-Aspire-5733Z:~/Ruby$ ruby so.rb
Enter a character b
b was pressed
kirti@kirti-Aspire-5733Z:~/Ruby$

Note: Your code was not working,as a = gets actually was assigning "b\n" to the variable a,which of course not equal to "b".But using #chomp will do remove the \n from the string,you just input from command prompt and will produce the expected output.


text:
Q: Siri-like Shadow on Scroll In Apple's siri for iOS, when Siri answers a question and it doesn't fit on the whole screen a user can scroll through the information. What is interesting about the scroll/table view in Siri is that when information extends beyond the bounds of the scroll/table view, a subtle gradient appears on the bottom of the view:

How does Siri detect that the information in the scroll / table view extend beyond its bounds? I know how easy it is to fade in an image with a shadow, but I don't understand how the detection of the content works?
Is there any kind of documentation or class that Apple provides that will let me detect this?
Thanks in advance!

A: It's probably just a matter of setting the content size according to the content that you load and then testing whether the scroll view height is less than the content view height.


text:
Q: R aggregate function unexpected NA When I use aggregate function on a data.frame which contains character and numeric columns, aggregate fails and returns only NAs for all. How can I solve this? My first idea was to check for value class but it did not work.
name <- rep(LETTERS[1:5],each=2)
feat <- paste0("Feat",name)
valuesA <- runif(10)*10
valuesB <- runif(10)*10

daf <- data.frame(ID=name,feature=feat,valueA=valuesA,valueB=valuesB, stringsAsFactors = FALSE)

 aggregate(.~ID, data=daf,FUN=mean)

 aggregate(.~ID, data=daf,FUN=function(x){
   if(is.character(x)){
     return(NA)
   }else{ return(mean(x))}
 })


text:
Q: Does Gym defending pokemons automatically get kicked out for a specific condition without getting invaded? I live in a small town where exists 6 Gyms and 18 Pokestops. Since a week I have been noticing that 2 of those 6 gyms are malfunctioning, or maybe I am wrong...
Now let's come to the main point...
So story of 5 days ago, I captured all of the 6 gyms. So today 4 of the 6 Pokemons got kicked out.
Out of the 4 gyms from which my pokemons got kicked, 2 of the gyms are being controlled by another team and the rest of the 2 gyms are empty. For the rest of the 2 empty gyms, I doubt that had someone invaded it, he would have left his pokemon in it, but the rest 2 gyms remained empty .
Today is not the first time when those 2 out of 6 gyms malfunctioned it happened to me a couple of times
(Both of the malfunctioning gyms are newly transformed).
So, is it a gym glitch or someone is secretly invading the gym without leaving a pokemon to defend?
Or
Is it some unknown condition being met, the Pokemons are getting kicked out ?
Thank You!

A: I can see if you are passing by in a bus you might just throw in a battle to kick the Pokemon out, but by the time it's done, they are too far to put one in. I just don't get why you would do so, waste the ressources without much benefit.
I went and checked and there is no 'upper time limit' on how much time a Pokemon can stay in a gym. There has been reports of gyms being held for up to 80-90 days. So it's not that.
Other option is that some Pokestops were added to the area and what is a Pokestop/gym has been reshuffled. So it's a gym that is at the same place, but is not the same exact point. But I think usually it will take a Pokestop and make it a gym, but not the other way around.


text:
Q: How can execute all of the Ranking STRUCTURE. USING recursive CREATE DATABASE TASKPERFORMANCE1

USE TASKPERFORMANCE1

DROP TABLE Students

CREATE TABLE Students
(
     ID VARCHAR(99),
     Name VARCHAR(99),
     LeaderID VARCHAR(99)
)

INSERT INTO Students (ID, Name, LeaderID)
VALUES (100, 'Baldo', null),
       (101, 'Cardo', 101),
       (102, 'Pedro', 101),
       (103, 'Luningning', 101),
       (104, 'Paolo', 102),
       (105, 'Roberto', 102),
       (106, 'Narciso', 102),
       (107, 'Jopay', 102),
       (108, 'Bernardo', 103),
       (109, 'Policarpio', 103),
       (110, 'Sisa', 103),
       (111, 'Reginaldo', 104)

;WITH RankingStructure (LeaderID,ID,Name,Ranking) AS
(
    SELECT LeaderID, ID, Name, 0 AS Ranking
    FROM Students
    WHERE LeaderID IS NULL

    UNION ALL

    SELECT S.LeaderID, S.ID, S.Name, R.Ranking + 1
    FROM Students S
    INNER JOIN RankingStructure R ON R.ID = S.LeaderID
)
SELECT LeaderID, ID, Name, Ranking
FROM RankingStructure


text:
Q: how to navigate(redirect) to another page in Angular? I'm trying to redirect to another page(Page-II) when a button clicked but unfortunately that another page component loads on the same page(Page-I). Here what I tried so far :
app.component.html
<button (click)="register()"
  mat-raised-button class="searchButton" type="button">Register</button>
  <button (click)="profile()"
  mat-raised-button class="searchButton" type="button">Profile</button>
 <router-outlet></router-outlet>

app-routing.module.ts
const routes: Routes = [{
  path : 'register',
  component : RegisterComponent
},
{
  path : 'profile',
  component : ProfileComponent
}];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})

export class AppRoutingModule { }

app.component.ts
import { Component , OnInit } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'app';
  constructor(private router: Router ) {}

    register = function () {
      location.pathname = ('/register');
    };
    profile = function(){
      this.router.navigateByUrl('/profile');
    };
  ngOnInit() {

  }
}

Note: I know that profile loads on same page but trying to redirect register.html when register button clicks on another page.

A: Can you try this:
register() {
    this.router.navigate(['/register']);
}


text:
Q: How to know when the effect is done within effect in ngrx component store (rxjs flow)? I'm currently implementing a feature that "open a dialog"(effect), after the dialog open the user hit save and then I want to close the dialog.
I made fake dialog and flow for the example.
I also split the flow into two effects: openDialogEffect and saveEffect to avoid "operator-hell" and code more readable and reuse save effect from another calls.
this works fine. until I want to close the dialog AFTER the save is successful.
The problem is how to "hook" into the pipeline of saveEffect?
I reproduce the problem here: stackblitz
readonly openDialogEffect = this.effect(($: Observable<any>) =>
    $.pipe(
      exhaustMap((dialogRef) =>
        dialogRef.open().pipe(
          tap({
            next: () => {
              this.saveEffect(); // <----- after that need to close the dialog... but how??
              // then: dialogRef.close();
            },
          })
        )
      )
    )
  );

  readonly saveEffect = this.effect(($) =>
    $.pipe(
      exhaustMap(() =>
        this.api.save().pipe(
          switchMap((res) =>
            this.api.updateFoo(res).pipe(
              tap({
                next: () => {
                  console.log('after save');
                  this.toast.success();
                },
                error: () => {
                  console.log('in error');
                  this.toast.error();
                },
              })
            )
          )
        )
      )
    )
  );

A: ngrx is able to handle pure side effects (effects that does not manipulate application state). Although you need to dispatch action from within an effect to achieve that, otherwise you can't be sure if it was successful or not.
@Component({
  // component metadata
})
export class MyComponent implements OnInit {
  constructor(
    private readonly actions$: Actions,
  ) {}

  ngOnInit() {
    this.actions$.pipe(
      ofType(someAction),
      takeUntil(this.destroy$), // remember to unsubscribe
    ).subscribe(({payload}) => {
      // show toast
      // close dialog
    });
  }
}

A: You can create a callback and passing to saveEffect through openDialogEffect:
the callback could be:

*

*function

*custom rxjs operator

1. using function callback
function callback
@Injectable()
export class AppService extends ComponentStore<State> {
  readonly openDialogEffect = this.effect<{
    // new code
    whenSaved: () => void;
    dialogRef;
  }>((arg$) =>
    arg$.pipe(
      exhaustMap(({ whenSaved, dialogRef }) =>
        dialogRef.open().pipe(
          tap({
            next: () => {
              this.saveEffect({
                whenSaved,
              });
              // then: dialogRef.close();
            },
          })
        )
      )
    )
  );

  readonly saveEffect = this.effect<{
    // new codes
    whenSaved: () => void;
  }>((arg$) =>
    arg$.pipe(
      exhaustMap((arg) =>
        this.api.save().pipe(
          switchMap((res) =>
            this.api.updateFoo(res).pipe(
              tap({
                next: () => {
                  console.log('after save');
                  arg.whenSaved();
                  this.toast.success();
                },
                error: () => {
                  console.log('in error');
                  this.toast.error();
                },
              })
            )
          )
        )
      )
    )
  );

  constructor(private api: ApiService, private toast: ToastrService) {
    super();

    this.openDialogEffect(
      of({
        dialogRef: dialog,
        whenSaved: () => {
          console.log('saved!!');
        },
      })
    );
  }
}

2. using custom rxjs operator
custom rxjs operator
@Injectable()
export class AppService extends ComponentStore<State> {
  readonly openDialogEffect = this.effect<{
    // new code
    whenSaved$: () => MonoTypeOperatorFunction<unknown>;
    dialogRef;
  }>((arg$) =>
    arg$.pipe(
      exhaustMap(({ whenSaved$, dialogRef }) =>
        dialogRef.open().pipe(
          tap({
            next: () => {
              this.saveEffect({
                whenSaved$,
              });
              // then: dialogRef.close();
            },
          })
        )
      )
    )
  );

  readonly saveEffect = this.effect<{
    // new codes
    whenSaved$: () => MonoTypeOperatorFunction<unknown>;
  }>((arg$) =>
    arg$.pipe(
      exhaustMap((arg) =>
        this.api.save().pipe(
          switchMap((res) =>
            this.api.updateFoo(res).pipe(
              tap({
                next: () => {
                  console.log('after save');
                  this.toast.success();
                },
                error: () => {
                  console.log('in error');
                  this.toast.error();
                },
              }),
              arg.whenSaved$()
            )
          )
        )
      )
    )
  );

  constructor(private api: ApiService, private toast: ToastrService) {
    super();

    this.openDialogEffect(
      of({
        dialogRef: dialog,
        whenSaved$: () => {
          return function <T>(source: Observable<T>): Observable<T> {
            return source.pipe(
              tap((isSaved) => console.log('save!', isSaved)),
              tap(() => console.log('do some thing...'))
            );
          };
        },
      })
    );
  }
}


text:
Q: how can i store other form fields with passport-local.js I am working on a node+passport.js authentication. I make a simple login/signup app. It's working fine but, it stores only username and password.
How can I store the other Form Fields like Phone number, email, hobbies, gender into database through a signup.html page with working login passport authentication? Can anybody have solution for that so I can store all the fields in the database....
//my schema is :--
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var userSchema = mongoose.Schema({
    local            : {
        username     : String,
        gender       : String,
        phone        : String,
        email        : String,
        password     : String
    }
 });
userSchema.methods.generateHash = function(password) {
    return bcrypt.hashSync(password, bcrypt.genSaltSync(8), null);
};
userSchema.methods.validPassword = function(password) {
    return bcrypt.compareSync(password, this.local.password);
};

var User = mongoose.model('user', userSchema);

module.exports = User;

In this code I use schema of email, username, password, gender phone and also given fields in signup.html page. but it stores only username and password fields only.........

A: Open passport.js file ( gernally inside config folder)
find this line of code.
    passport.use('local-signup', new LocalStrategy({   // 'login-signup' is optional here
    usernameField : 'email',
    passwordField : 'password',
    passReqToCallback : true },function(req, email, password, done) {
   var gender = req.body.gender;
  var username = req.body.username;
  var phone = req.body.phone;
 // Now you can access gender username and phone

}));

A: Add option passReqToCallback and you can access all request body data from req.body:
passport.use(new LocalStrategy({
  passReqToCallback: true
}, function (req, username, password, cb) {
  // Form fields are in req.body if using body-parser
  // ...
});

A: We can also try in this way.Its working in right way.In passport.js file write below code :
       module.exports = function(passport) {
              var criteria;
              passport.use(
               new LocalStrategy({ usernameField: 'username' }, (username, password, done) => {
               if(username.indexOf('@') > -1) {
               criteria = {
                    email: username,
                };
               } else {
                criteria = {
                    mobile: username,
                };
              }

                // Match user
                User.findOne(criteria).then(user => {
                  if (!user) {
                      return done(null, false, {
                        success: null,
                        errors: "User is not registered",
                        result:null
                    });
                }

                // Match password
                bcrypt.compare(password, user.password, (err, isMatch) => {
                    if (err) throw err;
                    if (isMatch) {
                        return done(null, user);
                    } else {
                        return done(null, false, {
                            success: null,
                            errors:'Password incorrect',
                            result: null
                         });
                    }
                });
            });
        })
    );
    enter code herepassport.serializeUser(function(user, done) {
        done(null, user.id);
    });

    passport.deserializeUser(function(id, done) {
        User.findById(id, function(err, user) {
            done(err, user);
        });
    });
};

A: Here is the simple to way to use passport module with passport-local strategy using passport-local-mongoose plugin to register and authenticate user with additional signup fields apart from username and password.
userModel.js  Defines the User Schema
(No need to add username, password fields as they will be added by 'passport-local-mongoose' plugin )
var mongoose = require('mongoose');
var passportLocalMongoose = require('passport-local-mongoose');
var Schema = mongoose.Schema;

var User = new Schema(
    {
        firstname:  { type: String},
        lastname:  {type: String},
        email:  {type: String},
        admin:   {type: Boolean, default: false}
    }
);

User.plugin(passportLocalMongoose);

module.exports = mongoose.model('User', User);

userRouter.js - handles all the requests with /signup and /login
var express = require('express');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var session = require('express-session');
var FileStore = require('session-file-store')(session);
var passport = require('passport');
var User = require('../models/userPassportModel');
var LocalStrategy = require('passport-local').Strategy;

var app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser('12345-67890-09876-54321'));

app.use(session({
    name: 'session-id',
    secret: '12345-67890-09876-54321',
   saveUninitialized: false,
   resave: false,
   store: new FileStore()
}));

passport.use(new LocalStrategy(User.authenticate()));
passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

var router = express.Router();
router.use(bodyParser.json());

// Handles Signup Request
router.post('/signup', (req, res, next) => {
        var usr =   new User({
                        username: req.body.username,
                        firstname:req.body.firstname,
                        lastname:req.body.lastname,
                        email:req.body.email
                    });
        var registerCallback =  (err, user) => {
            if(err) {
                res.statusCode = 500;
                res.setHeader('Content-Type', 'application/json');
                res.json({err: err});
            }
            else {
                passport.authenticate('local')(req, res, () => {
                    res.statusCode = 200;
                    res.setHeader('Content-Type', 'application/json');
                    var jsonResponse = {
                        success: true,
                        status: 'Registration Successful!',
                        user:user
                    };
                    res.json(jsonResponse);
                });
            }
        };
        User.register(usr, req.body.password, registerCallback );
});

// Handles Login Request
router.post('/login', passport.authenticate('local'), (req, res) => {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'application/json');
        res.json({success: true, status: 'You are successfully logged in!'});
});

There you go, '/signup' router will take are of registering user with addition fields and '/login' will take care of authenticating the user.
Here are is the /signup request sent using post method
{
  "username":"harrhys",
  "password":"stackoverflow",
  "firstname":"Harrhy",
  "lastname":"Saladagu",
  "email":"harrhy.saladagu@gmail.com"
}

Here is /signup the response
{
    "success": true,
    "status": "Registration Successful!",
    "user": {
        "admin": false,
        "_id": "5f2ae017ae44c31b5049a477",
        "username": "harrhys",
        "firstname": "Harrhy",
        "lastname": "Saladagu",
        "email": "harrhy.saladagu@gmail.com",
        "salt":
"6a6567e15575124e10f1046e55459ce0b8a3b496359b3a7b3201003a62471b06",
        "hash":
"cae72972632b5f62be7a978d660e1c205a9b6633748ec17d9f907619fd3e043532c29418a3853765e92dd453db5084135b4432dde5584ebe4b7db8d4c5651c75c3d5d506982d9a4aa6c5b7d1c1aaa39ef49a203849279352d48b2ae4da4dedd005179ee393e29c7cf03f363edb60b70defbc761fc9a461541710e64ab719f3412766be1382b9392d590383e0b24a3a3df890ca67d810ce44eef7ca2191424701544d94b0723c2b9acafec1a76f65e936670f1ca04034cf2e6e1c1e386ff21b987cabbcd6f3f8cf962943b4f7c0eafc140e99f3dc80ae5902588a8324f2ef91fa3639429767bd807257751df7f5a16b86dc181d906568d0f134430b825fa891fc74e55318937a11549d6352d24d42b4f4ddd44ccac1afe694a061976ae0fcf5d038207b9129e4c3592ecbffab48925abd9514a58aff9fd012241f280d93159c4f1eecbb5f7b87d2d7c027ee5fd75ecb05afee991507524395d4df5a047144fcef1fe418cdee39b8ae2ad8ca856854856a47b1d115b39631ff6e121bc6ac54961520ba0af2a1a2a4c7cd980e05956eeb18965f4931b7cd54a6dadab9a087b8275ca88b5654bda81c402720c0ec5b622a860b0ea2fc9da87e50659a829d5b3a5bd62801f74ab27f7eff234ac422caf68421d30b3a3534165df2c72a425e3170a3033a04f2f19e37710cbfa07e337969d62b6adee18dbfc9b4085e3fa2a778c25d45",
        "createdAt": "2020-08-05T16:36:40.610Z",
        "updatedAt": "2020-08-05T16:36:40.610Z",
        "__v": 0
    }
}

Here is the /login request  using post
{
  "username":"harrhys"
  "password":"stackoverflow"
}

And the /login response  along with the new cookie
{
    "success": true,
    "status": "You are successfully logged in!"
}


text:
Q: I am trying to create a sql table in phpmyadmin, I'm getting 4 errors. This code works in phpmyadmin on my pc at my work but not on the pc at home CREATE TABLE employees(
    employee_ID INT(11), PRIMARY KEY,
    name VARCHAR(200) NOT NULL,
    hourly_pay DECIMAL(10,2),
    position ENUM('Manager','Helper','Cashier','Cleaner') NOT NULL,
    employee_contact BIGINT(10) NOT NULL
    );

Here are the errors:

A comma or a closing bracket was expected. (near "NOT NULL" at position 86)
Unexpected beginning of statement. (near "10" at position 120)
Unexpected beginning of statement. (near "2" at position 123)
Unrecognized statement type. (near "position" at position 132)

A: Remove comma after INT(11)
CREATE TABLE employees(
    employee_ID INT(11) PRIMARY KEY,
    name VARCHAR(200) NOT NULL,
    hourly_pay DECIMAL(10,2),
     position ENUM('Manager','Helper','Cashier','Cleaner') NOT NULL,
    employee_contact BIGINT(10) NOT NULL
    );


text:
Q: Updating entity tree with deep nested entities My app deals with saving orders received from an external system. The order contains child items like line items, address, fulfillments, refunds > refund items etc.
Currently, I use an ugly looking code to detect what has changed in each entity by its External Id. Can someone recommend me a better way? :)
Following is a simplified entity model of Order
public class Order
{
    public long Id { get; set; }
    public string ExternalOrderId { get; set; }
    public List<LineItem> LineItems { get; set; }
    public List<Fulfillment> Fulfillments { get; set; }
    public ShippingAddress ShippingAddress { get; set; }
    public List<Refund> Refunds { get; set; }
    public string FinancialStatus { get; set; }
    public string FulfillmentStatus { get; set; }
}

public class LineItem
{
    public long Id { get; set; }
    public string ExternalLineItemId { get; set; }
    public string SKU { get; set; }
    public int Quantity { get; set; }
    public long OrderId { get; set; }
}

public class Fulfillment
{
    public long Id { get; set; }
    public string ExternalFulfillmentId { get; set; }
    public string Status { get; set; }
    public string TrackingUrl { get; set; }
    public long OrderId { get; set; }
}

public class ShippingAddress
{
    public long Id { get; set; }
    public string ExternalShippingAddressrId { get; set; }
    public string Addres { get; set; }
    public long OrderId { get; set; }
}

public class Refund
{
    public long Id { get; set; }
    public string ExternalRefundId { get; set; }
    public List<RefundedItem> LineItems { get; set; }
    public string CancelledReason { get; set; }
    public long OrderId { get; set; }
}

public class RefundedItem
{
    public long Id { get; set; }
    public string ExternalRefundedItemId { get; set; }
    public string SKU { get; set; }
    public int Quantity { get; set; }
}

My sample code:
private async Task ManageFulfillments(long orderId, Order order)
{
    if (order.Fulfillments == null || !order.Fulfillments.Any()) return;

    var newFulfillmentIds = order.Fulfillments.Select(c => c.ExternalFulfillmentId).ToList();
    var dbFulfillments = await _fulfillmentRepository.GetAll().IgnoreQueryFilters()
        .Where(c => c.OrderId == orderId)
        .Select(c => new { c.Id, c.ExternalFulfillmentId }).ToListAsync();
    var dbFulfillmentIds = dbFulfillments.Select(c => c.ExternalFulfillmentId).ToList();

    // Delete Fulfillments that are not present in new Fulfillments list
    var deletedFulfillments = dbFulfillmentIds.Except(newFulfillmentIds).ToList();
    if (deletedFulfillments.Any())
    {
        await _fulfillmentRepository.DeleteAsync(c =>
        deletedFulfillments.Contains(c.ExternalFulfillmentId) && c.ExternalOrderId == orderId);
    }

    // Update existing Fulfillments ids
    order.Fulfillments
        .Where(c => dbFulfillmentIds.Contains(c.ExternalFulfillmentId))
        .ToList()
        .ForEach(async c =>
        {
            c.Id = dbFulfillments.Where(p => p.ExternalFulfillmentId == c.ExternalFulfillmentId)
                .Select(p => p.Id).FirstOrDefault();
            await _fulfillmentRepository.UpdateAsync(c);
        });

    // New Fulfillments will automatically be added by EF
}

I have similar code in place to update other entites as well and I'm not proud of it!


text:
Q: What is the rating of a DVD laser diode I am making the "Pocket Laser Engraver" on instructables, but I need to find a replacement for the DVD drive's laser diode. (Already broke both of mine)
Online I might want to get the 12x20mm 5mW 650nm Laser diode and casing from AixiZ.
However, I need to know the rating of the laser diode in a 5.25 in DVD IDE drive so I can get one just like it. I've looked quite a bit for an accurate answer, with no luck so far. I'm sure somebody knows what the actual answer is, though!

A: The laser diode that you linked to is the read diode, not the write diode. Read diodes are (typically) Red, and are generally terrible for even low power laser pointers. It does, however have supreme consistency, and is a very clean beam.
Most DVD writers use a 405nm Violet laser to burn discs. 405nm lasers are excellent for engraving, as they are easily the most focus-able wavelength of laser you'll find on the market today.
Power is another concern. Especially with the 405nm lasers, you NEED eye protection. So long as you aren't looking at the dot directly, you will not damage your eyes (but accidentally looking at dot is possible). However, you will need the protection to focus the dot. Generally, you will want something that can be used consistently without overheating as far as power goes.

*

*At 120mW you can burn Items, and the engraving will easily come clean off.

*At 300mW you can start engraving non-black objects, and the engraving is somewhat texturable, and you can barely feel it.

*At 500mW you will need to put 3 INDEPENDENT safety mechanisms on your engraver for it to be legal in the UK and US. you'll have a wide range of things that you can engrave onto at this power level, you may want to have a fan running to cool the material.

*At 1000mW, you're at the higher end of the 405nm spectrum, and is probably your best bet for making a laser engraver. Just wear eye protection, for the love of all that is your eyes. This will engrave close to any material, including unpolished metals, but not glass. Exceptional cooling is needed for this type of diode.

Best of luck!