text:
Q: Is it normal to not pass variable as parameter in Javascript? I came across such code in Javascript and became quite puzzled as I come from C++/Python background:
const list = [
  {
    title: 'React',
    url: 'https://facebook.github.io/react/',
    author: 'Jordan Walke',
    num_comments: 3,
    points: 4,
    objectID: 0,
  },
  ...
];

class App extends Component {

  constructor(props) {
    super(props);

# leanpub-start-insert
    this.state = {
      list: list,
    };
# leanpub-end-insert
  }

  ...

}

It seems like you can just use variable that is outside of a function. I understand that that is how JS works but I am not sure if that is what people usually do, just use variable from outside and not pass as parameter. Is that a standard and normal practice?
The following looks quite impossible to pass variable as parameter to function:
import React, { Component } from 'react';
import './App.css';

const list = [
  {
    title: 'React',
    url: 'http://facebook.github.io/react',
    author: 'Jordan Walke',
    num_comments: 3,
    points: 4,
    objectID: 0,
  },
  {
    title: 'Redux',
    url: 'https://github.com/reactjs/redux',
    author: 'Dan Abramov, Andrew Clark',
    num_comments: 2,
    points: 5,
    objectID: 1,
  }
]

const isSearched = searchTerm => item =>
  item.title.toLowerCase().includes(searchTerm.toLowerCase());

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: list,
      searchTerm: '',
    }
    this.onDismiss = this.onDismiss.bind(this);
    this.onSearchChange = this.onSearchChange.bind(this);

  }
  onDismiss(id) {
    const isNotID = item => item.objectID !== id;
    const updatedList = this.state.list.filter(isNotID);
    this.setState({ list: updatedList });

  }

  onSearchChange(event) {
    this.setState({ searchTerm: event.target.value });
  }

  render() {
    return (

        <form>
          <input
            type="text"
            onChange={this.onSearchChange}
          />
        </form>
        {this.state.list.filter(isSearched(this.state.searchTerm)).map(item =>

                {item.title}

              {item.author}
              {item.num_comments}
              {item.points}

                <button onClick={() => this.onDismiss(item.objectID)} type="button">
                  Dismiss
                </button>

        )}

    )
  }
}

export default App;

A:
Is that a standard and normal practice?

Generally no, but there are exceptions. (for example having the entire state of the application in a variable).
Classes and functions are meant to be reused.
If your function (or class) relies on global variables then it will be hard to reuse and test.
Bottom line is: avoid it whenever possible.

A: In React it's definitely normal to have a list of fake data set in the state like in your example. You usually would import it from a different file though with the import syntax. But for better testability of your components, you are better off avoiding importing external libraries and instead passing it as parameters.

A: It's possible, but should be used with caution. As you can imagine, if everyone uses global variables, you can very easily end up with name collisions. Also, global variables are never garbage collected, so you risk littering the memory as well.
Generally, if you write a framework in JavaScript, you'll publish one global variable, which sort of serves as the "namespace" of your framework: Rx, d3, $, Handlebars, etc. These are usually the same as the name of the framework itself, so collisions are unlikely. Everything else is then defined within that object, e.g. Handlerbars.compile() and so on.


text:
Q: what happens when I configure a servlet before a filter in tomcat's web.xml? In tomcat for a certain url, I want to skip all the filters and execute a servlet and I thought placing the servlet before the filter will to as I expected but still the filters behind the servlet mappings are executing. Am I doing anything wrong?
For instance, this is my web.xml

  <servlet>
        <servlet-name>APIRedirection</servlet-name>
        <servlet-class>com.test.APIRedirection</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>APIRedirection</servlet-name>
        <url-pattern>/abc/*</url-pattern>
    </servlet-mapping>

<filter>
        <filter-name>filter</filter-name>
        <filter-class>com.test.filter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>filter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

So when the incoming url contains "/abc/" I want my servlet to execute and skip the filters. I placed my servlet before all the filters but still the filters are getting executed when the incoming url contains '/abc/'.

A: There is no concept of servlet before filter.
If servlets url mapping qualify filters url mapping then filter is executed before servlet.
I got your requirement you just don't want to hit Filters for certain urls.
a. If your application is still in starting phase, you can configure as given below
<servlet-mapping>
   <servlet-name>Servlet1</servlet-name>
   <url-pattern>/filtered/servlet1</url-pattern>
</servlet-mapping>

<servlet-mapping>
   <servlet-name>Servlet1</servlet-name>
   <url-pattern>/filtered/servlet2</url-pattern>
</servlet-mapping>

...
<filter-mapping>
    <filter-name>filter</filter-name>
    <url-pattern>/filtered/*</url-pattern>
</filter-mapping>

And the servlet url for which you want to bypass filter
<servlet-mapping>
   <servlet-name>Servlet1</servlet-name>
   <url-pattern>/unfiltered/servlet1</url-pattern>
</servlet-mapping>

2. If your application is already developed, and you configured a filter already with mapping /* then you can not skip that filter being executed. But you can add one more filter before that filter. Here filter order plays an important role,(reference for filter order) you can perform same functionality which you expected from a servlet. In your filter you just have to break filter chain and send response as given below
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,ServletException
{
    //your business logic
    // construct responseToSend
    response.getOutputStream().write(responseToSend);
    return;
}

For more information of breaking filter chain refer this question

redpajama_set_name: RedPajamaStackExchange


text:
Q: How does "if" work with registers in verilog? a = reg[3:0].
what values of "a" return true in: "if(a)"?.
which cell of the register a does the "if" check in the previous format?.
Does it return 0 only for a=0000 or are there other values for a that make if(a)=0?.

A: If a is reg [3:0], it evaluates to false inside if statement only when a == 4'b0000.


text:
Q: Connecting 50 Arduino slave devices to a single master Raspberry PI I am designing a automation system and need to have multiple slave devices(probabaly arduino UNO or NANO) communicating both ways with master device (Raspberry PI).
There is a server and database running on a raspbery PI and I need be constatly sending/reading data from individual arduinos that have sensors connected to it. Based on certain actions from the sensors on arduino boards, raspberry PI will be sending sql querys to the database.
My main concern is how do I talk to individual slave boards with a single master device. I only see 3 options here:

*

*Use RS485 modbus to connect all slaves in a daisy-chain

*Since I have 4 USB ports on my raspberry PI 3b+ and use only 1 for keyboard and mouse, i could use USB-HUB to expand the available USB ports and then connect to individual arduinos as such:

*Maybe use ETHERNET to connect all devices together? Not sure how would that work and look just an idea..
Any advice is appreciated! Thanks

A: Moving comments to an answer:

*

*Yes, any of these will work.

*RS485 is cheapest, and Ethernet is fastest.

*With USB you need hubs; with Ethernet you need switches. With RS485 you just connect all the devices to a single cable, but the speed is slower.

*Don't forget USB has a maximum distance of 5 metres between hubs, and a maximum of 5 hubs in a chain. The only advantage of USB is that you could use it to reprogram the Arduinos remotely.

Thnaks for the reply. Would you suggest how would the wiring look if I used ethernet to communicate with multiple slaves? Would I just add ethernet shield to arduino devices, connect all devices to the same network and use MQQT or simmilar to control slaves?

*

*Each Arduino would need an Ethernet shield

*Each Arduino, and the Pi, would need to be plugged into an Ethernet switch. Unlike USB, Ethernet switches can be chained together with no limit, and they can be up to 100 metres apart.

*You might be able to find some old (100Mbps only) professional-grade network switches on eBay, with maybe 24 ports each for only a couple of dollars per port. They should be cheaper because most people who use them upgraded to gigabit switches. You might even find 10Mbps hubs for cheaper still.

*I think it would be easiest to use a custom UDP protocol to control the slaves - unless you already know an MQTT library that you want to use.

Out of these three options, I would recommend RS485 if you don't need high speed.
Edit:

*

*"Justme"'s answer talks about some important limitations of RS485.

A: USB and Ethernet are pretty much out of the question here.
For connecting 50 devices and a host with Ethernet, you would need a 51-port switch, or several smaller switches distributed to have the total of 51 ports. Ethernet connections are point-to-point so you need 51 cables as well. Limit is 100m per span, or 90m inside the walls to allow 5m of patch cable at both ends. Power over Ethernet can power these, but that's even more expensive.
For USB, you also need a huge tree of USB hubs to provide 50 ports for 50 slaves.
USB has 5meter cable limitation, so that's not much. I don't know how much current one Arduino will draw, but assuming minimum of 1 unit load of 100mA, you can't provide more than 5 or 10 devices out of one USB port, unless hubs are powered.
So only real option from all of these is RS485 it still requires careful designing.
For instance, RS485 has a limit of 32 Unit Loads.
Connecting 50 devices means you need a tranceiver that is rated for half a Unit Load so you can have up to 64 of them on the same bus. The RS485 adapter you draw in the picture has a chip that has a rating of 1 unit load, so you can't connect more than 32 devices on a single bus, and you either need to use another tranceiver board, or split to use two buses with 25 devices plus host adapter on each.
The RS485 bus must be linear. The stubs from bus to a tranceiver must be relatively short, but don't do stubs if you don't have to. The bus must also be terminated to the characteristic impedance at both ends of the bus, with a 120 ohm resistor. The problem is that the tranceiver you draw in the picture has the termination built-in, so they must be modified so only the first and last device are terminated. Or remove termination from all of them, to allow the placement on the bus freely, and use external 120R resistors at suitable places where the bus ends. The bus simply does not work properly if it incorrectly terminated.
The tranceivers also have only two pins for connecting the bus, so there is no ground pin available for connecting a common bus ground reference. It means that with only two data wires, all the boards need to have a common ground reference via some other path. You can't use 2-prong wall warts to power them, but you must use a 3-prong power supplies that gives ground reference to the board. Or they must be powered centrally from one location so they share the same ground. RS485 allows for 7V difference between board ground references, but using ungrounded power supplies don't give a ground reference at all.

A: Interesting question. In any case, you're going to have some mess. What about wireless connection? Some ESP32 module is cheap, easy to setup with Arduino IDE, you can make individual addresses for your arduinos. They also don't take much space or power. You can have a local secure wifi-network uniting RaPi and all Arduinos.
Your host device raspberry can be connected to router that will unite all arduinos, router can support so many connections at once. Alternatively, RaPi can have several ESP32 as well (one ESP32 can support up to 10 connections with other devices). It's not the cheapest option, but it will make everything so much cleaner without 10km of wires. I would at least try to implement it with, say, 2 ESP32+arduinos and one ESP32 in raspberry as a host and I would just see if it works. All you'll need to do will be to provide power to all those arduinos, other than that, you'll have beautiful wireless net. Provided the signal reaches the RaPi.
Of course, there're many aspects of the project you need to take into account even to decide if it's viable at all to make such a thing, if you have serious distance between arduinos, you may want to invent something to make it work.


text:
Q: Get inline-style value even if element has the value also set in CSS? If you have the following element:

and the css is:
span {width:50px!important;}

Is there a way I can get the inline-style value and ignore the css value?
Thanks

A: To find the applied style:
var span = document.querySelector('span[style]'),
    actualWidth = window.getComputedStyle(span, null).width;

Note that this gets the style which won, which in this case will be the one with the !important modifier. If you must instead try and retrieve the in-line style, regardless of whether it was applied or not, you can simply use the style object of the element node:
inlineWidth = span.style.width;

JS Fiddle demo.
Do remember that, for width to be applied to a span element, it must be either display: block or display: inline-block.

A: use element.style.width
sample:
$(function(){
    alert($("span")[0].style.width);
});


text:
Q: Proof of exactness of Gaussian-Laguerre quadrature integration The Laguerre polynomials $a_{0}(x), a_{1}(x), a_{2}(x), \dots$ form an orthogonal set on $[0, ∞)$ and satisfy:
$\int_{0}^{\infty} e^{-x} a_{i}(x) a_{j}(x) d x=0, \quad i \neq j$
The polynomial $a_{n}(x)$ has n distinct zeros $x_{1}, x_{2}, \dots, x_{n} \text { on }[0, \infty)$. Construct a n-point quadrature formula
that evaluates:
$I=\int_{0}^{\infty} e^{-x} f(x) d x$
and has precision 2n − 1.
How do I prove the statement that the quadrature formula has precision 2n − 1?

A: You don't really need to write a specialized proof for this particular case, especially since they didn't give you a particular value of $n$. The general argument basically goes like this:

*

*the degree of exactness is at most $2n-1$: $a_n^2$ is a polynomial of degree $2n$ whose integral is obviously positive but which the rule integrates as zero

*the degree of exactness is at least $2n-1$: given a polynomial $p$ of degree at most $2n-1$, write $p=q a_n + r$ by polynomial long division. Then check that the $q a_n$ term doesn't contribute to the integration (because of how $a_n$ was chosen) nor to the quadrature rule (because of how the nodes were chosen). Thus the problem is reduced to choosing weights to exactly integrate a polynomial of degree at most $n-1$ (namely $r$) when the nodes are forced to be the zeros of $a_n$. From this point of view you can now follow the argument for deriving a quadrature rule "of interpolation type" to obtain the weights and thus to show that a rule with the desired properties exists. (This is a terrible way to obtain the weights to actually use in numerics, but it's fine for a proof.)


text:
Q: How do I implement routing in a basic Wordpress SPA using Vanilla JS I am new to Web Developement and Wordpress. I am somewhat confused about how to do basic SPA routing using Wordpress
I have a site that uses Wordpress as a CMS, and uses AJAX to load content into a Div depending on which link is clicked by the user.
Links are Home, News etc.
The Home page is the default Index.php page.
When someone clicks on News some other data is loaded into the 'content' div.
I will then use pushstate to update the address bar to www.mysite.com/news.
But I am not sure how to get back to this point if www.mysite.com/news is directly entered into the address bar.
Currently wordpress just shows a sample news item when I put the above in directly, redirecting to www.mysite.com/2019/05/02/news-item/
I know this is a basic question, but I have done a lot of reading and there doesnt seem to any simple explanation for this on the internet I can find easily. Most of the tutorials use some framework and seem more complex than I want to implement.
Thanks,
mubarak

A: It's very simple! Change your permalinks structure from the page:
yourdomain.com/wp-admin/options-permalink.php

to match your app's routing.


text:
Q: Iframe width does n't auto expand in new Facebook timeline view I have a facebook application which lists a list of categories in an iframe in facebook page. In the old facebook view, it is fit to the width where the iframe width is 520px. But when the page is opened in the new Timeline view, it's width is still 520px.
Since the function FB.Canvas.setAutoResize() is now deprecated by Facebook, I tried using FB.Canvas.setAutoGrow(). But still, it is not working.
Can any one please suggest a solution to auto adjust the canvas in both facebook page with timeline installed and without that??
Thanks...in advance..

A: You need to change this in the settings of application:


text:
Q: How can I get a list of all "likable" Facebook pages? I'm exploring the Facebook API for the first time - partially to research a web app idea I have and partially out of pure curiosity. The Explorer tool has been a great help with most things.
I'm trying to get a complete list of "Likable" pages on Facebook such as: Movies, Music, Books, TV Shows, etc. I understand how to get a list of pages that a user has liked, but I want the entire index of pages that exist.
All of the strings I've worked with so far start with /username. Is there another prefix for querying Facebook in general?

A: No, this is not possible and doesn't exist in the API.
A query like this is way too resource intensive.

A: You can use the
/search?q={query}&type=page&access_token={app_access_token}

with {query} as the search string, {app_access_token} as your App Access Token, as outlined at

*

*https://developers.facebook.com/docs/graph-api/using-graph-api/v2.2#search
It's not possible to retrieve or search for whole Page Categories.


text:
Q: Cannot visit Public IP of gitlab-aws-image I followed https://about.gitlab.com/aws/ and I could not visit the "Public IP" of the aws image. It said "This site can't be reached". So, then I ssh'd into the instance and found there was no /etc/gitlab/gitlab.rb file so I created one and simply pasted in the contents of https://gitlab.com/gitlab-org/omnibus-gitlab/blob/master/files/gitlab-config-template/gitlab.rb.template and replaced external_url 'GENERATED_EXTERNAL_URL' with the public IP. Still it doesn't work. Any tips?
Also on https://about.gitlab.com/aws/ it says you should use a c4.large instance but that sounds expensive -- can I just use a t2.micro?
I am used to using github so I was never worried about losing files but now that I'm hosting myself what is the professional way to backup (like what if the ec2 instance crashes) -- through s3 and by following http://docs.gitlab.com/omnibus/settings/backups.html?
Finally, The reason why I need to host my own gitlab is because I need to run pre-receive githooks. Is there any easier way to run pre-receive githooks without subscribing to an expensive enterprise service?

A: I believe https://about.gitlab.com/aws/ is broken. It's better to setup the default ubuntu instance given by amazon (you can pick t2.medium or c4.large) and then just follow the instructions for installation on gitlab.com for that version of ubuntu. It's just 4 steps (don't do the "from source").


text:
Q: Multiple ModificationForms in Sharepoint Workflow i am working on a Sharepoint Server 2007 Statemachine Workflow. Until now i have a few states and an custom Association/InitiationForm which i created with InfoPath 2007.
At the moment i have a Problem with Modification forms. The modification link in the state page of my workflow is shown and leads on click to my InfoPath form. If i click the "Submit" button the form is closed. Everything works fine.
Now i tried to add a second ModificationForm to my workflow. So i created a new InfoPath form and added it in the same way to the workflow as the first one. The workflow has no errors in the building or deploying-process.
But if i now try to click the second Modification link in the state page the form is not shown. Instead of my form the text: "The form has been closed." is shown.
I looked in the central administration and the InfoPath form is know under "Manage form templates". I gave every Modification in the Workflow.xml his own Guid. I used the following ModificationUrl: ModificationUrl="_layouts/ModWrkflIP.aspx"
Does anybody know step by step how to use two or more ModificationForms in my workflow?
Thank you in advance.

A: Thank you very much. I found the following Error Message in the Logfile:
"Form load failed with a validation error"
I searched in the web for solutions for this problem and fount this site:
http://social.msdn.microsoft.com/forums/en-US/sharepointworkflow/thread/83264f93-ebe3-49ec-bd6b-95ee02df4d8a/
I had two sceme files and i just schould use one for both forms. So i had to use the same data source. That was all. Thank you for the hint.

A: Look in your ULS logs for the error message. It will be listed there 100%. The category is "Forms Services" - the logs are located under the 12 hive in LOGS\


text:
Q: How can I move through images in trackBar scroll when clicking the right arrow key nonstop? If I click one by one click leave the arrow key then a click and leave again and so on the images are change good.
But if I keep pressing the right arrow key nonstop the images dosent change only when I leave the right arrowkey where it stopped so the image in this trackBar value loaded.
This is my scroll event:
private void trackBar1_Scroll(object sender, EventArgs e)
{
    currentFrameIndex = trackBar1.Value;
    textBox1.Text = "Frame Number : " + trackBar1.Value;
    wireObject1.woc.Set(wireObjectAnimation1.GetFrame(currentFrameIndex));
    LoadPictureAt(trackBar1.Value, sender);

    button1.Enabled = false;
    button2.Enabled = false;
    button3.Enabled = false;
    button4.Enabled = false;
    button8.Enabled = false;
    SaveFormPicutreBoxToBitMapIncludingDrawings();
    return;
}

I have no other events of the trackBar so far.
This is the LoadPictureAt function:
private bool LoadPictureAt(int nIndex, object c)
{
    bool bRet = false;
    if (nIndex >= 0 && nIndex < fi.Length)
    {
        if (c.Equals(trackBar1))
            pictureBox1.Load(fi[nIndex].FullName);
        bRet = true;
    }
    return bRet;
}

I SOLVED IT :
I added a new function before my scroll event:
private void setpicture(int indx)
        {
            if (fi == null)
            {

            }
            else
            {
                if (indx >= 0 && indx <= trackBar1.Maximum && fi.Length > indx)
                {
                    try
                    {
                        label19.ForeColor = Color.Red;
                        fileToolStripMenuItem.Enabled = true;
                        label19.Visible = false;
                        label20.Visible = false;
                        label14.Visible = true;
                        label15.Visible = true;
                        label8.Visible = true;
                        label9.Visible = true;

                        trackBar1.Enabled = true;
                        using (FileStream fs = new FileStream(fi[indx].FullName, FileMode.Open))
                        {
                            this.label8.Visible = true;
                            this.label9.Visible = true;
                            this.label9.Text = fi[indx].Name;
                            Image img = null;
                            Bitmap bmp = null;
                            Image imgOLd = null;

                            try
                            {

                                img = Image.FromStream(fs);
                                bmp = new Bitmap(img);

                                imgOLd = this.pictureBox1.Image;
                                this.pictureBox1.Image = bmp;
                                if (imgOLd != null)
                                    imgOLd.Dispose();

                                img.Dispose();
                                img = null;
                            }
                            catch
                            {
                                if (img != null)
                                    img.Dispose();
                                if (bmp != null)
                                    bmp.Dispose();
                                if (imgOLd != null)
                                    imgOLd.Dispose();
                            }
                        }
                    }
                    catch
                    {

                    }
                }
                else
                {
                    Image imgOLd = this.pictureBox1.Image;

                    if (imgOLd != null)
                    {
                        imgOLd.Dispose();
                        imgOLd = null;
                    }

                    Application.DoEvents();
                }
            }
        }

And changed the scroll event to:
private void trackBar1_Scroll(object sender, EventArgs e)
        {

            currentFrameIndex = trackBar1.Value;
            textBox1.Text = "Frame Number : " + trackBar1.Value;
            wireObject1.woc.Set(wireObjectAnimation1.GetFrame(currentFrameIndex));

            trackBar1.Minimum = 0;
            trackBar1.Maximum = fi.Length - 1;
            setpicture(trackBar1.Value);
            pictureBox1.Refresh();

            button1.Enabled = false;
            button2.Enabled = false;
            button3.Enabled = false;
            button4.Enabled = false;
            button8.Enabled = false;
            SaveFormPicutreBoxToBitMapIncludingDrawings();
            return;

        }

A: There's no such thing as "non-stop" when you hold down a cursor key or slam it repeatedly as fast as you can.  The KeyDown event for it is generated at a glacial pace to modern cpus.  You can't do much better than about 20 hits per second, 50 milliseconds between each hit.  A modern core can easily execute a hundred million instructions between keystrokes.
What matters however is what you do with that enormous resource.  Unfortunately you don't do much, you are hitting this disk in the Scroll event.  You call Image.Load() and, what looks like, Image.Save().  Those are methods that can only execute as fast as the disk rotates, the cpu isn't doing anything useful while it waits for the disk to do its job.  A hundred million cpu cycles wasted waiting for a mechanical event to happen.
It actually gets worse from there.  The next thing that happens is that Winforms needs to paint the window with the image retrieved from the disk.  Painting is a low priority operation, it is only done when nothing more important needs to be done.
Problem is, there is something more important that needs to be done.  Waiting for the disk to retrieve/save the image took so long that the next thing that the Winforms message loop encounters is something more important than painting.  An input event, the next keystroke.
Which gets properly executed, your picture box actually gets its Image assigned.  You just can't see it because it didn't get painted to the screen.  Stop hitting the cursor key and bam, it now has time and paints.
This is all very much by design.  You can force a repaint by calling the picture box' Update() method, the user will now definitely see the image.  But that doesn't actually work very well either, your program starts to lag.  The keystrokes are buffered in the message queue and your program will keep updating the image long after you released the key.
Pick your poison.


text:
Q: Bluetooth Issues on PopOS 21.04 I am on PopOS 21.04. Until recently, everything was working perfectly, but after some updates, I could not enable bluetooth from the Settings panel. I tried enabling bluetooth from the command line with bluetoothctl scan on and got an error saying the following:
$ bluetoothctl scan on
Connection ":1.116" is not allowed to own the service "org.bluez" due to security policies in the configuration file

I added the -d flag to the bluetooth.service's ExecStart parameter and got the following debug logs after a coldboot:
$ journalctl --unit=bluetooth -f
May 20 10:25:08 nilanjan-mitra bluetoothd[915]: src/profile.c:ext_adapter_probe() ":1.124/org/bluez/obex/00005005_0000_1000_8000_0002ee000001/00005005-0000-1000-8000-0002ee000001" probed
May 20 10:25:08 nilanjan-mitra bluetoothd[915]: src/adapter.c:adapter_service_add() /org/bluez/hci0
May 20 10:25:08 nilanjan-mitra bluetoothd[915]: src/sdpd-service.c:add_record_to_server() Adding record with handle 0x10010
May 20 10:25:08 nilanjan-mitra bluetoothd[915]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00000003-0000-1000-8000-00805f9
May 20 10:25:08 nilanjan-mitra bluetoothd[915]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00000008-0000-1000-8000-00805f9
May 20 10:25:08 nilanjan-mitra bluetoothd[915]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00000100-0000-1000-8000-00805f9
May 20 10:25:08 nilanjan-mitra bluetoothd[915]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00001002-0000-1000-8000-00805f9
May 20 10:25:08 nilanjan-mitra bluetoothd[915]: src/sdpd-service.c:add_record_to_server() Record pattern UUID 00005005-0000-1000-8000-0002ee0
May 20 10:25:08 nilanjan-mitra bluetoothd[915]: src/adapter.c:adapter_service_insert() /org/bluez/hci0
May 20 10:25:08 nilanjan-mitra bluetoothd[915]: src/adapter.c:add_uuid() sending add uuid command for index 0

These are the dmesg logs:
$ dmesg | grep Bluetooth
[    6.558671] Bluetooth: Core ver 2.22
[    6.558691] Bluetooth: HCI device and connection manager initialized
[    6.558694] Bluetooth: HCI socket layer initialized
[    6.558696] Bluetooth: L2CAP socket layer initialized
[    6.558699] Bluetooth: SCO socket layer initialized
[    6.704062] Bluetooth: hci0: Firmware revision 0.1 build 6 week 12 2021
[    7.781114] Bluetooth: BNEP (Ethernet Emulation) ver 1.3
[    7.781117] Bluetooth: BNEP filters: protocol multicast
[    7.781121] Bluetooth: BNEP socket layer initialized
[  285.103971] Bluetooth: RFCOMM TTY layer initialized
[  285.103979] Bluetooth: RFCOMM socket layer initialized
[  285.103985] Bluetooth: RFCOMM ver 1.11

Also, this is the output of bluetoothd:
$ bluetoothd
D-Bus setup failed: Connection ":1.126" is not allowed to own the service "org.bluez" due to security policies in the configuration file

When I run systemctl restart bluetooth, bluetooth is switched on but when I turn it off from the Settings panel, I have to restart the service again for bluetooth to turn back on. The BlueZ version is 5.55.
I also rebooted into the recovery partition and performed a clean install, everything was working perfectly up until I ran upgraded the packages with apt update && apt upgrade.
Any ideas on how to fix this, or why this is happening? I tried searching for Connection ":1.126" is not allowed to own the service "org.bluez" due to security policies error but couldn't find anything.


text:
Q: How can I resize the resolution so the display isn't clipped? so I have a RCA tv that I use as a monitor, it has no option to adjust the resolution since I connect through HDMI so it greys out "PC Settings", I downloaded Nvidia Xserver settings and it helped a bit, although I wasn't able to make the resolution fit properly, I've been trying by adjusting it through XServer but the end results are always clipped, here's an approximate of how my screen looks like, I'd really appreciate if you could help me figure out why does this happen.

A: I found a solution, I'm using Underscan in Nvidia Xserver settings, while not perfect, at least it minimizes the stuff cut from the display to an acceptable minimum.


text:
Q: Changing texture on ActionScript 2/3 Does anybody knows if there is a simple way to change this
var colorTransform:NewColorTransform;
colorTransform = new NewColorTransform();
colorTransform.color = Config.ARRAY_COLOURS[1];
color.transform.colorTransform = colorTransform;

That is changing colors (the ARRAY_COLOURS have [ 0xFF0000, 0x0000FF, 0xFFFF00 ])
I would like to have instead of that something like ARRAY_COLOURS[ IMAGE1, IMAGE2, IMAGE3 ]

A: We would need more info in order to give you a more accurate answer.
In any case, you probably could do something like this

private var bitmaps:Array = [image1 , image2 , image3];
private var colours:Array = [colour1 , colour2 , colour3];
private var textureTransform:String;
private var selectedBitmap:Bitmap;

private function init():void
{
  switch ( textureTransform )
  {
    case 'bitmap':
      selectedBitmap = bitmaps[1];
      bitmapChange();
      break;

    case 'colour':
      //the example in your question
      colourTransform();
      break;
  }
}

private function bitmapChange():void
{
    this.addChild( selectedBitmap );
}


text:
Q: overriding a function implementation I have the following files:
t.py:
def foo():
    print("foo")

folder/t.py:
def foo():
    print("bar")

folder/main.py:

import t
if __name__ == "__main__":
  t.foo()

when I run it on the command line with python -m folder.main it prints "foo" but I actually want to import folder/t.py so that it prints "bar" instead. How can I do that?

A: You can import as, so like import folder.t as ft then run ft.foo()

A: Use the following code in main.py and run the command python -m folder.main.
sys.path.append() will add the folder to the system path so that it can find the module t in that folder.
import sys
sys.path.append('.\\folder\\')

from folder import t
if __name__ == "__main__":
  t.foo()


text:
Q: is it possible to generate uml or jdl model from existing jhipster project after generating j hipster project is it possible generate JDL model or uml diagram from the generated code in order to see how the application is build and relations between classes.

A: run the following command jhipster export-jdl <<FILE_NAME_PATH>>

A: Yes, just run yo jhipster:export-jdl to generate a JDL file of your current project.

A: As you can't import the user entity again it makes no sense to me to have it exported to a jdl file.

A: Invoking jHipster from Yeoman has been deprecated. Please use JHipster CLI. jhipster export-jdl <<FILENAME.jdl>>.


text:
Q: Google Analytics w/ Android: Programmatically set ga_reportUncaughtExceptions? tl;dr
Is there a way to programatically enable reportUncaughtExceptions for Google Analytics (v4) without using the xml config in Android?
Longer explanation
I'm using Google Analytics v4 in an Android app, and I need a way to set two different tracking ids by build flavor. I was using a general global_tracker.xml configuration (see below), though I need a way to "dynamically inject" the tracking id based on flavor.
<resources xmlns:tools="http://schemas.android.com/tools"
           tools:ignore="TypographyDashes">
    <integer name="ga_sessionTimeout">300</integer>
    <bool name="ga_autoActivityTracking">true</bool>
    <bool name="ga_reportUncaughtExceptions">true</bool>

    <!--  The following value should be replaced with correct property id. -->
    <string name="ga_trackingId">UA-xxxxxx-xx</string>
</resources>

In order to avoid having duplicate xml configs in the build flavor source folders, I initialize a tracker directly using the trackingId and set the attributes programatically.
mGATracker = analytics.newTracker(R.string.ga_code); // this is dynamic depending on flavor
mGATracker.setSessionTimeout(300);
mGATracker.enableAutoActivityTracking(true);

Is there a way to enable reportUncaughtExceptions without using the xml config?

A: If i have not misunderstand your question, the solution is below:
mGATracker is your own tracker.
mGATracker.enableExceptionReporting(true);

Hope it helps, thank you.
Reference: https://developers.google.com/android/reference/com/google/android/gms/analytics/Tracker#enableExceptionReporting(boolean)

A: No There is no way to do it in the current version of the APIs. Thanks for pointing it out though. We'll look into it and possibly add it in one of the upcoming versions of the sdk.

A: I think the best you'll be able to do programmatically is have two different tracker xml configuration files, both with the same ga_trackingId but different values for ga_reportUncaughtExceptions.  Use the GoogleAnalytics.newTracker() method with the xml resource for the correct configuration file instead of the trackingId.
if (buildFlavor == 1)
    mGATracker = analytics.newTracker(R.xml.tracker_config_1)
else
    mGATracker = analytics.newTracker(R.xml.tracker_config_2)

See http://developer.android.com/reference/com/google/android/gms/analytics/GoogleAnalytics.html#newTracker(int)

A: You can set the Analytics exception handler programaticly.
UncaughtExceptionHandler myHandler = new ExceptionReporter(
    myTracker,                                        // Currently used Tracker.
    Thread.getDefaultUncaughtExceptionHandler(),      // Current default uncaught exception handler.
    context);                                         // Context of the application.

// Make myHandler the new default uncaught exception handler.
Thread.setDefaultUncaughtExceptionHandler(myHandler);

See more at https://developer.android.com/reference/com/google/android/gms/analytics/ExceptionReporter.html


text:
Q: call JS function from external file on tab index change by user i have in my .ascx file Image button that calls a Function from C# behind code
Image button Code :
<asp:ImageButton ID="ImageItemThumb" runat="server" Width="75px" OnClick="switchTab_imgeClick" />

and the Behind C# Function is
`
 protected void switchTab_imgeClick(object sender, EventArgs e)
           {
             TCArtistDetails.ActiveTabIndex = 2;
             ShowProjectDetails();
 //this.Page.ClientScript.RegisterClientScriptInclude(this.GetType(),"showFunction","JScript1.js" );
         //Button imageFire = (Button)DataListCollection.FindControl("ImageClick");
         //imageFire.Attributes.Add("OnClick", "show");

         // Page.ClientScript.RegisterClientScriptBlock(this.GetType(), key, "<script type=\"text/javascript\">jQuery(window).load();</script>", true);
         // Dumy.Attributes.Add("OnClick", "Show");
         // string jScriptValidator;
         //jScriptValidator = "JQuery.switchTab_imgeClick";
         //Page.ClientScript.RegisterStartupScript(this.GetType(), "showFunction", jScriptValidator);
     }

`
and also there is the JS file that contain this Function
`
function show()
{
        alert("Hey Show ");
                    $('div.navigation').css({'width' : '200px', 'float' : 'right'});
                $('div.content').css('display', 'block');

                // Initially set opacity on thumbs and add
                // additional styling for hover effect on thumbs
                var onMouseOutOpacity = 0.67;
                $('#thumbs ul.thumbs li').opacityrollover({
                    mouseOutOpacity:   onMouseOutOpacity,
                    mouseOverOpacity:  1.0,
                    fadeSpeed:         'fast',
                    exemptionSelector: '.selected'
                });

                // Initialize Advanced Galleriffic Gallery
                var gallery = $('#thumbs').galleriffic({
                    delay:                     2500,
                    numThumbs:                 15,
                    preloadAhead:              10,
                    enableTopPager:            true,
                    enableBottomPager:         true,
                    maxPagesToShow:            7,
                    imageContainerSel:         '#slideshow',
                    controlsContainerSel:      '#controls',
                    captionContainerSel:       '#caption',
                    loadingContainerSel:       '#loading',
                    renderSSControls:          true,
                    renderNavControls:         true,
                    playLinkText:              'Play Slideshow',
                    pauseLinkText:             'Pause Slideshow',
                    prevLinkText:              '‹ previous ',
                    nextLinkText:              'next ›',
                    nextPageLinkText:          'Next ›',
                    prevPageLinkText:          '‹ Prev',
                    enableHistory:             false,
                    autoStart:                 false,
                    syncTransitions:           true,
                    defaultTransitionDuration: 0, // OMM , START , 8/1/2012 , Change From 900 to 0
                    onSlideChange:             function(prevIndex, nextIndex) {
                        // 'this' refers to the gallery, which is an extension of $('#thumbs')
                        this.find('ul.thumbs').children()
                            .eq(prevIndex).fadeTo('fast', onMouseOutOpacity).end()
                            .eq(nextIndex).fadeTo('fast', 1.0);

                    },
                    onPageTransitionOut:       function(callback) {
                        this.fadeTo('fast', 0.0, callback);
                    },
                    onPageTransitionIn:        function() {
                        this.fadeTo('fast', 1.0);
                    }
                });
            };`

i wanna make this code run on the user click to the image the tab switch and run this JS script ??
all hashed lines i have tried but the page wont load
Tip : Page refresh is not an Option :(

A: You can put a hidden field in the page and on your code behind update this hidden field value by "1" for example to specify that the user did clicked on the tab then update your js code to be to run at the document ready event and check if the hidden field vale contains 1 or not and if it contains 1, then call your function.


text:
Q: Component Services Error Log - SQL Server Distributed Replay Client I am getting the following error on a Windows Server 2008 x64 R2 Virtual Machine install:
Log Name: System
Source: Distributed COM
Event ID: 10016
Level: Error
Date: 2/20/2013 8:22:14 AM

The application-specific permission settings do not grant Local Activation permission for the COM Server application with CLSID
{6DF8CB71-153B-4C66-8FC4-E59301B8011B}
 and APPID
{961AD749-64E9-4BD5-BCC8-ECE8BA0E241F}
 to the user NT SERVICE\SQL Server Distributed Replay Client SID (S-1-5-80-3249811479-2167633679-2115734285-1138413726-166979568) from address LocalHost (Using LRPC). This security permission can be modified using the Component Services administrative tool.

The server in question does have SQL Server 2012 installed.
So here is what I have tried so far..
As the error log states, the SQL Server Distributed Relay Client user does not have Local Activation permissions to the COM server with the ID specified in the error log.

*

*I opened Component Services via Start > search for Component Services.

*I browse to DCOM Config and find the APPID {961AD749-64E9-4BD5-BCC8-ECE8BA0E241F}, which happens  to be DReplayController.

*Right click on DReplayController and select Properties

*Go to the Security Tab

*Change Launch and Activation Permissions to Customize and select Edit.

Here is a screenshot of the permissions for this object

*I click OK and close the Component Services window, but the issue is not resolved.

What am I missing here?   I have to admit this is my first time messing with any of the stuff in Component Services in Windows.
I should also mention that this error is being generated approx every 3 seconds in the system event log.   Obviously, by the end of the day I have thousands of event logs for this event.
When I look at Services on this machine, I do see a SQL Server Distributed Replay Client service that is started automatically when windows boots.   What exactly does this service do in the first place?   Is this used to cluster SQL servers (I am just guessing from the name)?   Would it be OK for me to turn off this service?   Do you think turning this service off would cause any issues?   The SQL server installed on this server is a standalone database, and the data is only being acccessed locally via a web application.
If anyone has any suggestions as to why I am getting this error and how to stop it, let me know.  Am I on the right track in terms of attempting to troubleshoot this problem?
Let me know if you need any further details.

A: Credit for answering this goes to Microsoft Support.
So the issue was due to the fact that the NT Service\SQL Server Distributed Replay Client user did not have local activation permissions in the Component Services dialog.   The original error message clearly stated that I needed to give local activation permissions to the SQL Server Distributed Replay Client, but it seems that I gave permissions to SQL Server Distributed Replay CONTROLLER instead.

A: *

*Click Start -> Run -> Type -> DCOMCNFG, expand Component Services -> Computers -> My Computer -> DCOM Config.

*Click View -> Detail -> Now you will get Application Name and Application ID in right side.

*Scroll down and find the application ID {961AD749-64E9-4BD5-BCC8-ECE8BA0E241F} -> Right Click -> Properties and select the Security tab. [DREPLAYCONTROLLER]

*Click Customize under "Launch & Activation Permission" -> click Edit -> Add in the account NT Service\SQL Server Distributed Replay Client and set local launch and local activation.

*Restart the application Service linked to this Application ID or restart the server and monitor


text:
Q: SQLAlchemy session is not adding some of my objects I created some mapped objects using the declarative style in SQLAlchemy. I have a mapping called ThermafuserReading which has a composed primary key made up of the Time_stamp column which is DateTime and ThermafuserId column which is an Integer and also acts as a Foreign Key to another table called Thermafuser. This is the definition of the class
class ThermafuserReading(Base):
"""Class to map to the Thermafuser Readings table in the HVAC DB"""

__tablename__ = 'Thermafuser_Reading'

_timestamp = Column('Time_stamp', DateTime, primary_key = True)
_thermafuserId = Column('ThermafuserId', Integer, ForeignKey("Thermafuser.ThermafuserId"), primary_key = True)
_roomOccupied = Column('RoomOccupied', Boolean)
_zoneTemperature = Column('ZoneTemperature', Float)
_supplyAir = Column('SupplyAir', Float, nullable=True)
_airflowFeedback = Column('AirflowFeedback', Float, nullable=True)
_CO2Input = Column('CO2Input', Float, nullable=True)
_maxAirflow = Column('MaxAirflow', Float, nullable=True)
_minAirflow = Column('MinAirflow', Float, nullable=True)
_unoccupiedHeatingSetpoint = Column('UnoccupiedHeatingSetpoint', Float, nullable=True)
_unoccupiedCoolingSetpoint = Column('UnoccupiedCoolingSetpoint', Float, nullable=True)
_occupiedCoolingSetpoint = Column('OccupiedCoolingSetpoint', Float, nullable=True)
_occupiedHeatingSetpoint = Column('OccupiedHeatingSetpoint', Float, nullable=True)
_terminalLoad = Column('TerminalLoad', Float, nullable=True)

#Relationship between Thermafuser Reading and Thermafuser
_thermafuser = relationship("Thermafuser", back_populates = "_thermafuserReadings",  cascade = "all, delete-orphan", single_parent = True)

I am creating a session in the following way
sqlengine = sqlalchemy.create_engine("mysql+mysqldb://user:password@localhost:3306/HVAC")
    Session = sessionmaker(bind=sqlengine)
    session = Session()

At some point in my code I am creating a list called readings of Thermafuser Readings and adding such list the session via session.add_all(readings)
This are some example elements printed from the list readings:
<ThermafuserReading(thermafuserId = '21', timestamp = '2016-12-31 23:30:00')>
<ThermafuserReading(thermafuserId = '21', timestamp = '2016-12-31 23:35:00')>
<ThermafuserReading(thermafuserId = '21', timestamp = '2016-12-31 23:40:00')>
<ThermafuserReading(thermafuserId = '21', timestamp = '2016-12-31 23:45:00')>
<ThermafuserReading(thermafuserId = '21', timestamp = '2016-12-31 23:50:00')>
<ThermafuserReading(thermafuserId = '21', timestamp = '2016-12-31 23:55:00')>
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-01 00:00:00')>

The problem is that the session is only keeping the last item in this list, eventhough I did session.add_all(readings) e.g. This is what the session has inside:
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-01 00:00:00')>

I know the session keeps track of objects which have the same primary key and thus inserts only one instance of such objects in the sesssion but in this case the primary key (thermafuserId, timestamp) is different at each instance. I dont know why the session is only adding the last element of my list while neglecting the other elements.
Any idea?
EDIT:
I kept doing some tests and found out the reason why only the last element of the list is being added to the session. The problem lies in the identity_key for each of the objects in my list readings. This is the code I used for my tests:
for reading in readings:
    print(reading, mapper.identity_key_from_instance(reading))

and this are some of the results
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-14 23:15:00')> (<class 'hvacDBMapping.ThermafuserReading'>, (datetime.datetime(2017, 1, 15, 0, 0), 21))
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-14 23:20:00')> (<class 'hvacDBMapping.ThermafuserReading'>, (datetime.datetime(2017, 1, 15, 0, 0), 21))
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-14 23:25:00')> (<class 'hvacDBMapping.ThermafuserReading'>, (datetime.datetime(2017, 1, 15, 0, 0), 21))
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-14 23:30:00')> (<class 'hvacDBMapping.ThermafuserReading'>, (datetime.datetime(2017, 1, 15, 0, 0), 21))
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-14 23:35:00')> (<class 'hvacDBMapping.ThermafuserReading'>, (datetime.datetime(2017, 1, 15, 0, 0), 21))
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-14 23:40:00')> (<class 'hvacDBMapping.ThermafuserReading'>, (datetime.datetime(2017, 1, 15, 0, 0), 21))
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-14 23:45:00')> (<class 'hvacDBMapping.ThermafuserReading'>, (datetime.datetime(2017, 1, 15, 0, 0), 21))
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-14 23:50:00')> (<class 'hvacDBMapping.ThermafuserReading'>, (datetime.datetime(2017, 1, 15, 0, 0), 21))
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-14 23:55:00')> (<class 'hvacDBMapping.ThermafuserReading'>, (datetime.datetime(2017, 1, 15, 0, 0), 21))
<ThermafuserReading(thermafuserId = '21', timestamp = '2017-01-15 00:00:00')> (<class 'hvacDBMapping.ThermafuserReading'>, (datetime.datetime(2017, 1, 15, 0, 0), 21))

As you can observe, the function sqlalchemy.orm.util.identity_key_from_instance() is not creating the identity keys correctly for my datetime objects.
Can somebody help me clarify why?
EDIT
This is a simplified code that illustrates the problem. No connection to the database in this code. The code where this problem first appeared is much more involved and posting it will only create confusion, but this code reproduces the error.
Session = sessionmaker()
session = Session()

mapper = inspect(ThermafuserReading)

#Open the csv file
csvFilePath = "/Users/davidlaredorazo/Box Sync/Data/Zone4/1C1A/1C1A 2016-12-31.csv"
with open(csvFilePath, 'r') as csvfile:

    reader = csv.reader(csvfile)
    componentId = 1
    count = 0

    reading = ThermafuserReading(None, componentId)

    for row in reader:

        if count == 0:
            count += 1
            continue

        #print(row)
        timestamp = parse(row[0], None, ignoretz = True)

        reading.timestamp = timestamp
        new_object = copy.copy(reading)
        new_object.timestamp = timestamp

        print(new_object, mapper.identity_key_from_instance(new_object))
        session.add(new_object)

print("new elements")
for new in session.new:
    print(new, mapper.identity_key_from_instance(new_object))

A: As univerio mentioned in the comments. What I was doing wrong was using copy.copy to copy instances of my mapped objects, this was messing with _sa_instance_state. The solution was to create an "ad hoc" copy function for my instances. Here is the copy function I used, this, indeed solved the problem.
def copy_sqla_object(obj, omit_fk=True):
    """Given an SQLAlchemy object, creates a new object (FOR WHICH THE OBJECT
    MUST SUPPORT CREATION USING __init__() WITH NO PARAMETERS), and copies
    across all attributes, omitting PKs, FKs (by default), and relationship
    attributes."""
    cls = type(obj)
    mapper = class_mapper(cls)
    newobj = cls()  # not: cls.__new__(cls)
    pk_keys = set([c.key for c in mapper.primary_key])
    rel_keys = set([c.key for c in mapper.relationships])
    prohibited = pk_keys | rel_keys
    if omit_fk:
        fk_keys = set([c.key for c in mapper.columns if c.foreign_keys])
        prohibited = prohibited | fk_keys
    for k in [p.key for p in mapper.iterate_properties if p.key not in prohibited]:
        try:
            value = getattr(obj, k)
            setattr(newobj, k, value)
        except AttributeError:
            pass
    return newobj

You can see a more detailed discussion of this issue in
https://groups.google.com/forum/#!topic/sqlalchemy/HVSxndh23m0


text:
Q: python open() how to change set files name/title If I open a file (image) in python with
f = open('/path/to/file.jpg', 'r+')
I have a function f.title() and I get the full path of the file back.  How can I change the opened files name/repr/title to something else?

A: You don't change filenames using open, that's for sure. You'll want to use os.rename.
But if you're trying to change the name the file has within your program but NOT the actual filename, why are you trying to do that/what would be the point in that? I guess you could detach the buffer from the file object and assign it to a new object with the title you want, if you're working with Python 3 (thought you could do it in Python 2(.6) as well, but don't see any mention of the detach method in the documentation of the Python 2.6 file object or its io module), but really, I don't quite see the point...
Oh wait, if you just want the filename for use elsewhere and don't necessarily need to change the name itself:
import os.path

f = open('/path/to/file.jpg', 'r+')

print(os.path.basename(f.name))  #don't include the parentheses if you're working in Python 2.6 and not using the right __future__ imports or working in something prior to 2.6

This will output 'file.jpg'. Not sure if it helps you if blob.filename is an automatic assignment, though, unless you're willing to subclass whatever class blob is...

A: It doesn't work for me (Python 2.6, on Windows); I have to use the "name" attribute:
>>> f = open(r'C:\test.txt', 'r+')
>>> f.title()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'file' object has no attribute 'title'
>>> f.name
'C:\\test.txt'

According to the documentation, "name" is read-only.  And unfortunately, you can't set arbitrary attributes on file objects:
>>> f.title = f.name
Traceback (most recent call last):
  File "<console>", line 1, in <module>
AttributeError: 'file' object has no attribute 'title'


text:
Q: Binormal and Tangent with Normal Mapping I'm trying to make a normal mapping shader for my DirectX meshes, and while following some notes from my school, it tells me that I need my vertex structure to contain a Vec3 for Pos and a 3x3 Martix for the normal, binormal and the tangent, but I can't figure out how to get the binormal and the tangent. I referenced my book, which told me to use the D3DXComputeTangentFrameEx function, however all my meshes are D3DXFRAME objects, not an ID3DXMesh*..
Can anyone help me out?
I also want to add, I have the pos and the normal vectors already.

A: If you look at D3DXFRAME, you could find pMeshContainer member, which is D3DXMESHCONTAINER* type, which have MeshData member of D3DXMESHDATA type, which have pMesh member of ID3DXMesh* type, but it is valid only if Type == D3DXMESHTYPE_MESH.
Example:
{
    D3DXFRAME Frame;

    ID3DXMesh* pMesh;

    if( Frame.pMeshContainer->MeshData.Type == D3DXMESHTYPE_MESH )
        pMesh = Frame.pMeshContainer->MeshData.pMesh;
    else
        pMesh = 0;  // model is ID3DXPatchMesh type
}


text:
Q: c++ get milliseconds since some date I need some way in c++ to keep track of the number of milliseconds since program execution.  And I need the precision to be in milliseconds. (In my googling, I've found lots of folks that said to include time.h and then multiply the output of time() by 1000 ... this won't work.)

A: clock has been suggested a number of times. This has two problems. First of all, it often doesn't have a resolution even close to a millisecond (10-20 ms is probably more common). Second, some implementations of it (e.g., Unix and similar) return CPU time, while others (E.g., Windows) return wall time.
You haven't really said whether you want wall time or CPU time, which makes it hard to give a really good answer. On Windows, you could use GetProcessTimes. That will give you the kernel and user CPU times directly. It will also tell you when the process was created, so if you want milliseconds of wall time since process creation, you can subtract the process creation time from the current time (GetSystemTime). QueryPerformanceCounter has also been mentioned. This has a few oddities of its own -- for example, in some implementations it retrieves time from the CPUs cycle counter, so its frequency varies when/if the CPU speed changes. Other implementations read from the motherboard's 1.024 MHz timer, which does not vary with the CPU speed (and the conditions under which each are used aren't entirely obvious).
On Unix, you can use GetTimeOfDay to just get the wall time with (at least the possibility of) relatively high precision. If you want time for a process, you can use times or getrusage (the latter is newer and gives more complete information that may also be more precise).
Bottom line: as I said in my comment, there's no way to get what you want portably. Since you haven't said whether you want CPU time or wall time, even for a specific system, there's not one right answer. The one you've "accepted" (clock()) has the virtue of being available on essentially any system, but what it returns also varies just about the most widely.

A: See std::clock()

A: Include time.h, and then use the clock() function. It returns the number of clock ticks elapsed since the program was launched. Just divide it by "CLOCKS_PER_SEC" to obtain the number of seconds, you can then multiply by 1000 to obtain the number of milliseconds.

A: Some cross platform solution. This code was used for some kind of benchmarking:
#ifdef WIN32
  LARGE_INTEGER g_llFrequency = {0};
  BOOL g_bQueryResult = QueryPerformanceFrequency(&g_llFrequency);
#endif

//...

long long osQueryPerfomance()
{
#ifdef WIN32
  LARGE_INTEGER llPerf = {0};
  QueryPerformanceCounter(&llPerf);
  return llPerf.QuadPart * 1000ll / ( g_llFrequency.QuadPart / 1000ll);
#else
  struct timeval stTimeVal;
  gettimeofday(&stTimeVal, NULL);
  return stTimeVal.tv_sec * 1000000ll + stTimeVal.tv_usec;
#endif
}

A: The most portable way is using the  clock function.It usually reports the time that your program has been using the processor, or an approximation thereof. Note however the following:

*

*The resolution is not very good for GNU systems. That's really a pity.

*Take care of casting everything to double before doing divisions and assignations.

*The counter is held as a 32 bit number in GNU 32 bits, which can be pretty annoying for long-running programs.
There are alternatives using "wall time" which give better resolution, both in Windows and Linux. But as the libc manual states: If you're trying to optimize your program or measure its efficiency, it's very useful to know how much processor time it uses. For that, calendar time and elapsed times are useless because a process may spend time waiting for I/O or for other processes to use the CPU.

A: Here is a C++0x solution and an example why clock() might not do what you think it does.
#include <chrono>
#include <iostream>
#include <cstdlib>
#include <ctime>

int main()
{
   auto start1 = std::chrono::monotonic_clock::now();
   auto start2 = std::clock();

   sleep(1);

   for( int i=0; i<100000000; ++i);

   auto end1 = std::chrono::monotonic_clock::now();
   auto end2 = std::clock();

   auto delta1 = end1-start1;
   auto delta2 = end2-start2;

   std::cout << "chrono: " << std::chrono::duration_cast<std::chrono::duration<float>>(delta1).count() << std::endl;

   std::cout << "clock: " << static_cast<float>(delta2)/CLOCKS_PER_SEC << std::endl;
}

On my system this outputs:
chrono: 1.36839
clock: 0.36

You'll notice the clock() method is missing a second.  An astute observer might also notice that clock() looks to have less resolution.  On my system it's ticking by in 12 millisecond increments, terrible resolution.
If you are unable or unwilling to use C++0x, take a look at Boost.DateTime's ptime microsec_clock::universal_time().

A: This isn't C++ specific (nor portable), but you can do:
SYSTEMTIME systemDT;

In Windows.
From there, you can access each member of the systemDT struct.
You can record the time when the program started and compare the current time to the recorded time (systemDT versus systemDTtemp, for instance).
To refresh, you can call GetLocalTime(&systemDT);
To access each member, you would do systemDT.wHour, systemDT.wMinute, systemDT.wMilliseconds.
To get more information on SYSTEMTIME.

A: Do you want wall clock time, CPU time, or some other measurement?  Also, what platform is this?  There is no universally portable way to get more precision than time() and clock() give you, but...

*

*on most Unix systems, you can use gettimeofday() and/or clock_gettime(), which give at least microsecond precision and access to a variety of timers;

*I'm not nearly as familiar with Windows, but one of these functions probably does what you want.

A: You can try this code (get from StockFish chess engine source code (GPL)):
#include <iostream>
#include <stdio>

#if !defined(_WIN32) && !defined(_WIN64) // Linux - Unix
    #  include <sys/time.h>
    typedef timeval sys_time_t;
    inline void system_time(sys_time_t* t) {
        gettimeofday(t, NULL);
    }
    inline long long time_to_msec(const sys_time_t& t) {
        return t.tv_sec * 1000LL + t.tv_usec / 1000;
    }
    #else // Windows and MinGW
    #  include <sys/timeb.h>
    typedef _timeb sys_time_t;
    inline void system_time(sys_time_t* t) { _ftime(t); }
    inline long long time_to_msec(const sys_time_t& t) {
        return t.time * 1000LL + t.millitm;
    }
#endif

struct Time {
    void restart() { system_time(&t); }
    uint64_t msec() const { return time_to_msec(t); }
    long long elapsed() const {
        return long long(current_time().msec() - time_to_msec(t));
    }
    static Time current_time() { Time t; t.restart(); return t; }
private:
    sys_time_t t;
};

int main() {
    sys_time_t t;
    system_time(&t);
    long long currentTimeMs = time_to_msec(t);
    std::cout << "currentTimeMs:" << currentTimeMs << std::endl;

    Time time = Time::current_time();
    for (int i = 0; i < 1000000; i++) {
        //Do something
    }
    long long e = time.elapsed();
    std::cout << "time elapsed:" << e << std::endl;

    getchar();  // wait for keyboard input
}


text:
Q: How do I retrieve implemented objects from an array of interface from ASP.NET Core Web API ? And not just the properties that are in the interface I am trying to retrieve data from my MongoDb database using an ASP.NET Core Web API.
The object I'm trying to retrieve has an array of IPanel. And after retrieving it I want to access the Text property in the TextPanel,
or the ImageUrl in the ImagePanel.
Unfortunately the API only returns the properties defined in the interface.
TextPanel:
[BsonDiscriminator("TextPanel")]
public class TextPanel : IPanel
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; } = ObjectId.GenerateNewId().ToString();

    [BsonRepresentation(BsonType.ObjectId)]
    public string PageId { get; set; } = "Invalid PageId";

    public string Title { get; set; }

    public string Text { get; set; } = "Text here";

    public TextPanel(string title = "Title")
    {
        Title = title;
    }
}

ImagePanel:
[BsonDiscriminator("ImagePanel")]
public class ImagePanel : IPanel
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; } = ObjectId.GenerateNewId().ToString();

    [BsonRepresentation(BsonType.ObjectId)]
    public string PageId { get; set; } = "Invalid PageId";

    public string Title { get; set; }

    public List<string> ImageUrls { get; set; } = new();
    public List<string> ImageCaptions { get; set; } = new();

    public bool Cropping { get; set; }

    public ImagePanel(string title = "Title")
    {
        Title = title;
    }
}

IPanel:
public interface IPanel
{
    string Id { get; set; }
    string PageId { get; set; }
    string Title { get; set; }
}

ApiReturn:
{
  "id": "guid",
  "panels": [
    {
      "id": "guid",
      "pageId": "guid",
      "title": "TextPanel"
    },
    {
      "id": "guid",
      "pageId": "guid",
      "title": "TextPanel"
    }
  ]
}

PanelController:
[HttpPost]
[Route("AddTextPanel")]
public async Task<ActionResult> AddTextPanel(string pageId, string? title)
{
    await panelService.AddTextPanel(pageId, title!);
    return Ok("Text Panel Added");
}

panelService.AddTextPanel:
public async Task AddTextPanel(string pageId, string title = "Title")
{
    BasePage page = pageService.GetPageById(pageId);
    TextPanel newPanel = new(title);
    page.AddPanel(newPanel);
    await pageService.UpdatePage(page);
}

page.AddPanel:
public void AddPanel(IPanel panel)
{
    panel.PageId = Id;
    Panels.Add(panel);
}


text:
Q: Удаление объекта из массива в NodeJS или неправленый скрипт? Суть проблемы такова, что скрипт работает немного не правильно... Не могу самостоятельно разобраться.
Есть массив объектов :
var routes = [
    { path: '/login', methods: [ 'GET' ] },
    { path: '/login', methods: [ 'POST' ] },
    { path: '/admin', methods: [ 'GET' ] },
    { path: '/admin', methods: [ 'POST' ] },
    { path: '/admin', methods: [ 'PUT' ] },
    { path: '/admin/mylogin', methods: [ 'GET' ] },
    { path: '/admin/mylogin', methods: [ 'POST' ] },
    { path: '/admin/mylogin/:user', methods: [ 'GET' ] },
    { path: '/admin/mylogin/:user', methods: [ 'POST' ] },
    { path: '/client', methods: [ 'GET' ] },
    { path: '/client', methods: [ 'POST' ] },
    { path: '/client/123', methods: [ 'GET' ] },
    { path: '/client/123', methods: [ 'POST' ] },
    { path: '/client/123', methods: [ 'DELETE' ] },
    { path: '/client/123', methods: [ 'PUT' ] },
    { path: '/', methods: [ 'GET' ] }
];

Нужно выбрать все совпадения path и запушить из совпавших в искомый methods и удалить совпавший.
Скрипт:
routes.forEach((element, i) => {
    j = 0;
    while(j < routes.length) {
        if (routes[j].path === element.path && routes[j].methods !== element.methods) {
            element.methods.push(routes[j].methods[0]);
            routes.splice(j,1)
        }
        j++
    }
});

В итоге у меня там где 4 и более совпавших элемента примерно такое:
  { path: '/client/123', methods: [ 'POST', 'GET', 'DELETE' ] },
  { path: '/client/123', methods: [ 'PUT' ] }

А должно быть :
{ path: '/client/123', methods: [ 'POST', 'GET', 'DELETE', 'PUT' ] }

Пробовал и delete routes[j], но там удаление срабатывает вообще раньше чем выполняется условие и NodeJS ругается, что routes[j].path не определено.

A: В качестве альтернативного варианта, можно использовать метод reduce для группировки по полю path
var routeByPaths = routes.reduce((acc,cur)=>{
    if(!acc[cur.path]){
        acc[cur.path] = cur;
    }else{
        acc[cur.path].push(...cur.methods)
    }
    return acc;
},{});

Получится объект, в котором ключами будут пути, а значениями объекты начального массива с измененным полем methods
Для получения массива значений можно воспользоваться методом Object.values
routes = Object.values(routeByPaths);

Если в повторяемых путях в массиве methods могут повторяться методы, например:
{ path: '/client', methods: [ 'GET' ] },
{ path: '/client', methods: [ 'POST' ] },
{ path: '/client', methods: [ 'GET' ] },
{ path: '/client', methods: [ 'POST' ] },

То в промежуточных расчетах лучше использовать Set вместо массива, так как он не допускает повторения элементов.
Например:
var routeByPaths = routes.reduce((acc,cur)=>{
    if(!acc[cur.path]){
        acc[cur.path] = { path:[cur.path], methods: new Set() };
    }
    cur.methods.reduce((set,method)=>{
        set.add(method);
        return set;
    }, acc[cur.path].methods)
    return acc;
},{});

И далее, при получении, если нужен именно массив. то можно преобразовать Set в массив, например так:
routes = Object.values(routeByPaths).map(el=>({path:el.path, methods:[...el.methods]}));

A: Вот что у меня получилось, и оно даже работает))))
routes.forEach((element, i, arr) => {
    j = arr.length-1;
    while(j >=0) {
        if (j !== i && element.path === arr[j].path) {
            element.methods.push(arr[j].methods[0])
            arr.splice(j, 1)
        }
        j--
    }
});

А вот такое решение мне предложили на тостере:
    const groupedRoutes = Object.values(routes.reduce((map, { path, methods }) => {
    map[path] =  map[path] ?
     { path, methods: [ ...map[path].methods, ...methods ] } :
     { path, methods };

    return map;
  },{}));

A: У вас ошибка из-за работы с  j. Вы делаете routes.splice(j,1), а потом j++. В итоге пропускаете один элемент. После routes.splice(j,1) нужно делать j--.
И кстати, routes[j].methods !== element.methods не работает, т.к. нельзя массивы таким образом сравнивать.
К тому же, плохая практика обращаться к routes из forEach.
Что-то типо такого должно быть:
routes.forEach((element, index, object) => {
    var j = 0;
    while (j < object.length) {
        // нет смысла с самим собой работать
        if(object[j] !== element){
            if (object[j].path === element.path) {
                for(var mIndex = 0; mIndex < object[j].methods.length; ++mIndex){
                    if(element.methods.indexOf(object[j].methods[mIndex]) === -1){
                        element.methods.push(object[j].methods[mIndex]);
                    }
                }
                object.splice(j, 1);
                j--;
            }
        }

        j++;
    }
});


text:
Q: Вертикальный Slick slider на весь экран. Как сделать чтобы после слайда показывался футер? Прошу помочь с реализацией вертикального slick слайдера на весь экран, после которого есть футер высотой 300 px.
Цели - каждый слайд на весь экран, листание слайдов с помощью mouse scroll, чтобы футер был виден при скроле и нормальной ширины(300px);
В тот момент когда футер виден - кнопка должна пропасть.
Спасибо каждому кто не пройдет мимо!
Посоветуйте какой использовать слайдер, если считаете что слик не очень.
Мой код - codepen.io/Rainspistols/pen/dyPYmEV


text:
Q: In Android app i am getting computed font-size as 2.90909px In android application i am opening a web site.
In this website i am using rem as unit for width.
For html tag i have added font-size as 1px.

html{   font-size:1px !important; }

But if i see computed styles,i see font-size as 2.90909px
I have checked whether this css is getting overriden somewhere,but it is not.Attaching the screen-shot for the same.
Please let me know what is the issue and what can be workaround as i want html font size equal to 1px.
please see the highligted part,any known issue ?

A: You need to go deep, this should do it:
* { font-size: 1px !important; }

Using it on HTML tag will not affect some jQuery Mobile elements, like, for example, buttons.


text:
Q: Calling parent attribute and functions in javascript? How do I call parent object attribute and functions in javascript? For example, if I had an object gen0 with a child object gen1 which had a child object gen2. How would gen1 call its parents names and functions? How would gen2 call its parents and grandparents functions (without using prototypes)?
gen0 = {
    name: "gen0",
    gen0Func: function() {
        console.log("gen0Func");
        console.log("My name is " + this.name);
    },
    gen1: {
        name: "gen1",
        gen1Func: function() {
            console.log("gen1Func");
            console.log("My name is " + this.name);
            console.log("My parents name is " + this.parent.name); // Doesn't work.
        },
        gen2: {
            name: "gen2",
            gen2Func: function() {
                console.log("gen2Func");
                console.log("My name is " + this.name);
                console.log("My parents name is " + this.parent.name); // Doesn't work.
                console.log("My grandparents name is " + this.parent.parent.name); // Doesn't work.

            }
        }
    }
}

A: There's nothing that automatically links objects back to the objects that contain references to them. If you want that, you need to do it explicitly in your code.

gen0 = {
    name: "gen0",
    gen0Func: function() {
        console.log("gen0Func");
        console.log("My name is " + this.name);
    },
    gen1: {
        name: "gen1",
        gen1Func: function() {
            console.log("gen1Func");
            console.log("My name is " + this.name);
            console.log("My parents name is " + this.parent.name); // Doesn't work.
        },
        gen2: {
            name: "gen2",
            gen2Func: function() {
                console.log("gen2Func");
                console.log("My name is " + this.name);
                console.log("My parents name is " + this.parent.name); // Doesn't work.
                console.log("My grandparents name is " + this.parent.parent.name); // Doesn't work.

            }
        }
    }
}

gen0.gen1.parent = gen0;
gen0.gen1.gen2.parent = gen0.gen1;

gen0.gen1.gen2.gen2Func();

A: You should approach this in a different way. One way I would do this, is to use classes and objects with relations (parent, children, etc)..

class Gen {
 constructor(name,parent) {
  this.name = name;
  this.parent = parent;
 }

 sayHi() {
  console.log('Hi!.. I am ' + this.name);
 }

}

var gen0 = new Gen('gen0');
var gen1 = new Gen('gen1',gen0);
var gen2 = new Gen('gen2',gen1);

gen0.sayHi(); // Hi!.. I am gen0
gen1.sayHi(); // Hi!.. I am gen1
gen1.parent.sayHi(); // Hi!.. I am gen0
gen2.parent.parent.sayHi(); // Hi!.. I am gen0

A:

var gen0 = {
    name: "gen0",
    gen0Func: function() {
        console.log("gen0Func");
        console.log("My name is " + this.name);
    },
    gen1: {
        name: "gen1",
        gen1Func: function() {
            console.log("gen1Func");
            console.log("My name is " + this.name);
            console.log("My parents name is " + this.parent.name);
        },
        gen2: {
            name: "gen2",
            gen2Func: function() {
                console.log("gen2Func");
                console.log("My name is " + this.name);
                console.log("My parents name is " + this.parent.name); // Doesn't work.
                console.log("My grandparents name is " + this.parent.parent.name);

            }
        }
    },
    init: function() {
       this.gen1.parent = this;
       this.gen1.gen2.parent = this.gen1;
       return this;
    }
}.init();

gen0.gen1.gen1Func();
gen0.gen1.gen2.gen2Func();

A:

gen0 = {
    name: "gen0",
    gen0Func: function() {
        console.log("gen0Func");
        console.log("My name is " + this.name);
    },
    gen1: {
        name: "gen1",
        gen1Func: function() {
            console.log("gen1Func");
            console.log("My name is " + this.name);
            console.log("My parents name is " + gen0.name); // Doesn't work.
        },
        gen2: {
            name: "gen2",
            gen2Func: function() {
                console.log("gen2Func");
                console.log("My name is " + this.name);
                console.log("My parents name is " + gen0.gen1.name); // Doesn't work.
                console.log("My grandparents name is " + gen0.name); // Doesn't work.

            }
        }
    }
}

gen0.gen1.gen2.gen2Func();


text:
Q: CouchDB count all documents and return a number? We have a college project in CouchDB and I'm using node, I want to create a view that returns a number of all my documents by email.
I cannot find anything that works and I'm not sure what I'm missing, I tried a lot of different reduce functions and emit methods.
Thanks for any answers.
The documents have 2 fields, name and email

A: Do not use the db endpoint because the response field doc_count includes design documents along with other documents that may not have an email field.
A straight forward way to do this is with a view. The code snippet demonstrates the difference between db info doc_count and a view's total_rows using PouchDB.  I'd guess there's probably more interesting uses for the index.
The design doc is trivial
{
 _id: '_design/my_index',
   views: {
     email: {
       map: function(doc) {
         if (doc.email) emit(doc.email);
       }.toString()
    }
  }
}

And the view query is very efficient and simple.
db.query('my_index/email', {
        include_docs: false,
        limit: 0
      })

const gel = id => document.getElementById(id);
let db;

function setJsonToText(elId, json) {
  gel(elId).innerText = JSON.stringify(json, undefined, 3);
}
async function view() {
  // display db info
  setJsonToText('info', await db.info());
  // display total number or rows in the email index
  const result = await db.query('my_index/email', {
    include_docs: false,
    limit: 0
  });
  setJsonToText('view', result);

}

// canned test documents
function getDocsToInstall() {
  return [{
      email: 'jerry@garcia.com',
    },
    {
      email: 'bob@weir.com',
    },
    {
      email: 'phil@lesh.com'
    },
    {
      email: 'wavy@gravy.com'
    },
    {
      email: 'samson@delilah.com'
    },
    {
      email: 'cosmic@charlie.com'
    },
    // design doc
    {
      _id: '_design/my_index',
      views: {
        email: {
          map: function(doc) {
            if (doc.email) emit(doc.email);
          }.toString()
        }
      }
    }
  ]
}

// init example db instance
async function initDb() {
  db = new PouchDB('test', {
    adapter: 'memory'
  });

  await db.bulkDocs(getDocsToInstall());

};

(async() => {
  await initDb();
  await view();
})();

Info

email view

A: You can use GET /{db}, which returns information about the specified database. This is a JSON object that contains the property doc_count.

doc_count (number) – A count of the documents in the specified database.

With Angular for example, this could be done with the following method:
async countDocuments(database: string): Promise<number> {
  return this.http.get<any>(this.url('GET', database), this.httpOptions).toPromise()
    .then(info => info['doc_count']);
}

A: Assumption:
Assuming that following documents are  present in the Customers database:
[
{
  "_id": "93512c6c8585ab360dc7f535ff00bdfa",
  "_rev": "1-299289ee89275a8618cd9470733035f4",
  "name": "Tom",
  "email": "tom@domain.com"
 },
{
  "_id": "93512c6c8585ab360dc7f535ff00c930",
  "_rev": "1-a676883d6f1b5bce3b0a9ece92da6964",
  "name": "Tom Doe",
  "email": "tom@domain.com"
 },
{
  "_id": "93512c6c8585ab360dc7f535ff00edc0",
  "_rev": "1-09b5bf64cfe66af7e1134448e1a328c3",
  "name": "John",
  "email": "john@domain.com"
 },
{
  "_id": "93512c6c8585ab360dc7f535ff010988",
  "_rev": "1-88e347af11cfd1e40e63920fa5806fd2",
  "name": "Alan",
  "email": "alan@domain.com"
 }

]

If I understand your query correctly, then based on above data, You need below given result set.
{
"tom@domain.com": 2,
"alan@domain.com": 1,
"john@domain.com": 1
}

Solution:
In order to achieve above, Consider following design document containing a View which has Map and Reduce functions.
{
  "_id": "_design/Customers",
  "views": {
    "by-email": {

      "map": "function (doc) {
         if(doc.email){
              emit(doc.email, doc._id);
         }
       }",
      "reduce": "_count"
    }
  },
  "language": "javascript"
}

The above view function emits value of the key email of the document if the key exists in the document.
The reduce function _count is a built in reducer (provided by CouchDB) that does the counting logic.
Executing View Query:
In order to query this view, you need to: select the view function, mark reduce to be executed (as it is optional to run reduce) and set 1 as group level.
Here is  how you can do it through the UI:

Result:
Here is the result given by above query:
[![result of map reduce query
Hope this helped.
For more details about other reduce functions and group level, please refer CouchDB documentation.
Cheers.


text:
Q: Ignore generation of declarations for specific files src/
    user.ts
    department.ts

using above as a context structure, if i do tsc is it possible to ignore/prevent generaton of declaration files for department.ts within tsconfig or webpack while bulding the app?
Currently its generating declaration for all the files within src directory

A: Yes, you can use the exclude key in the tsconfig.json file.
{
   // ...other config options
   "exclude": ["src/user.ts", "src/department.ts"]
}

See the TypeScript documentation for more details


text:
Q: pm3d in gnuplot with binary data I have some data files with content
a1 b1 c1 d1
a1 b2 c2 d2
...
[blank line]
a2 b1 c1 d1
a2 b2 c2 d2
...

I plot this with gnuplot using
splot 'file' u 1:2:3:4 w pm3d.

Now, I want to use a binary file. I created the file with Fortran using unformatted stream-access (direct or sequential access did not work directly). By using gnuplot with
splot 'file' binary format='%float%float%float%float' u 1:2:3

I get a normal 3D-plot. However, the pm3d-command does not work as I don't have the blank lines in the binary file. I get the error message:
>splot 'file' binary format='%float%float%float%float' u 1:2:3:4 w pm3d
Warning: Single isoline (scan) is not enough for a pm3d plot.
Hint: Missing blank lines in the data file? See 'help pm3d' and FAQ.

According to the demo script in http://gnuplot.sourceforge.net/demo/image2.html, I have to specify the record length (which I still don't understand right). However, using this script from the demo page and the command with pm3d obtains the same error message:
splot 'scatter2.bin' binary record=30:30:29:26 u 1:2:3  w pm3d

So how is it possible to plot this four dimensional data from a binary file correctly?
Edit: Thanks, mgilson. Now it works fine. Just for the record: My fortran code-snippet:
 open(unit=83,file=fname,action='write',status='replace',access='stream',form='unformatted')
 a= 0.d0
 b= 0.d0
 do i=1,200
    do j=1,100
       write(83)real(a),real(b),c(i,j),d(i,j)
       b = b + db
    end do
    a = a + da
    b = 0.d0
 end do
close(83)

The gnuplot commands:
 set pm3d map
 set contour
 set cntrparam levels 20
 set cntrparam bspline
 unset clabel
splot 'fname' binary record=(100,-1) format='%float' u 1:2:3:4 t 'd as pm3d-projection, c as contour'

A: Great question, and thanks for posting it.  This is a corner of gnuplot I hadn't spent much time with before.  First, I need to generate a little test data -- I used python, but you could use fortran just as easily:
Note that my input array (b) is just a 10x10 array.  The first two "columns" in the datafile are just the index (i,j), but you could use anything.
>>> import numpy as np
>>> a = np.arange(10)
>>> b = a[None,:]+a[:,None]
>>> b
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10],
       [ 2,  3,  4,  5,  6,  7,  8,  9, 10, 11],
       [ 3,  4,  5,  6,  7,  8,  9, 10, 11, 12],
       [ 4,  5,  6,  7,  8,  9, 10, 11, 12, 13],
       [ 5,  6,  7,  8,  9, 10, 11, 12, 13, 14],
       [ 6,  7,  8,  9, 10, 11, 12, 13, 14, 15],
       [ 7,  8,  9, 10, 11, 12, 13, 14, 15, 16],
       [ 8,  9, 10, 11, 12, 13, 14, 15, 16, 17],
       [ 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]])
>>> with open('foo.dat','wb') as foo:
...     for (i,j),dat in np.ndenumerate(b):
...         s = struct.pack('4f',i,j,dat,dat)
...         foo.write(s)
...

So here I just write 4-floating point values to the file for each data-point.  Again, this is what you've already done using fortran.  Now for plotting it:
splot 'foo.dat' binary record=(10,-1) format='%float' u 1:2:3:4 w pm3d

I believe that this specifies that each "scan" is a "record".  Since I know that each scan will be 10 floats long, that becomes the first index in the record list.  The -1 indicates that gnuplot should keep reading records until it finds the end of the file.


text:
Q: how to fix "Module 'cv2' has no ---- member pylint(no-member? I am trying to start a project to learn how to use opencv and the first problem I encountered is this : "Module 'cv2' has no  ---- member  pylint(no-member) as posted in the picture.

I have found some information here in Stack Overflow but I'm afraid, I might not be proficient enough to understand what is going on. Could someone point me in the right direction to solve my problem?
Thanks!

A: One possible reason is that you might have a file named cv2.py somewhere on your machine other than the original cv2 module and now python is importing that file rather than the cv2 module.
Or perhaps you could've downloaded a wrong cv2 module, other than that i don't see anything that could've gone wrong as you don't have a complex code. Try reinstalling the module and/or removing a file named cv2.py (if you've accidentaly created one).
You can check the module by importing the module in the terminal and check for dir, on python console type import cv2 and then dir(cv2), now you should see all the classes contained in the cv2 module.

A: If the program runs correctly then I guess you are facing linting issue which is answer in this [https://stackoverflow.com/questions/26657265/hide-some-maybe-no-member-pylint-errors] question.
Solution is to turn off no-member linting error using below command
pylint disable=maybe-no-member

OR
pylint --disable=E1101


text:
Q: Truncated "Recent Items" Label in OS X Mavericks General Preferences I've just upgraded to OS X Mavericks (Build 13A603) and discovered a truncated label in General Preferences. You can see the that the Recent Items can't be read at all.

I've tried to overwrite the prefpane in, but the problem still remains:
/System/Library/PreferencePanes/Appearance.prefPane.
Do anyone else have the same problem?

A: I had the same problem, and figured out the solution.
Apparently, for whatever reason, 3rd party hacks or something else, the font size in the preference pane was incorrect. Since there's no way to change the size of System Fonts in the GUI, I used the TinkerTool utility to reset to defaults.
It was the fixed-pitch font that was incorrect, and TinkerTool had it highlighted. I just hit the Set to default button in TinkerTool's Fonts tab and that fixed it.
I'm glad I sorted this out and didn't have to re-download the 5+ GB Mavericks Installer!


text:
Q: NVIDIA card fan spins faster when not in use In my system I have an NVIDIA video card (GeForce 450 GTS) as an extra card (video output via motherboard ATI) for bitcoin mining.
If I start mining, the fan speeds up a little, but the weird thing is, if I stop mining the fan starts to spin much much faster (generating lots of noise). And it doesn't stop doing that.
What could be the cause? And how can I fix that?


text:
Q: Is possible add class for last post of Custom Post Type? I need to add a different class for last post of a Custom Post Type. Is it possible?
I have found this code, but it works only in posts
function wpc_last_post_class( $classes ) {
    global $wp_query;
    if(($wp_query->current_post+1) == $wp_query->post_count) $classes[] = 'last'; // change the class name  you would like to add here
    return $classes;
}
add_filter('post_class', 'wpc_last_post_class');

A: Not exactly what you asked for, but given that classes are primarily used for styling, might you consider using CSS pseudo-class ":last-child" instead of PHP code?
Here's some information on how to style using :last-child
https://css-tricks.com/almanac/selectors/l/last-child/


text:
Q: Как внедрить файлы в ресурсы программы Внедрил три текстовых файла в проект. Думал они все время будут в проекте, однако они ссылаются на файлы в папке debug, что не есть хорошо, так как если этих файлов нет на диске - то и при компиляции возникают ошибки.

A: Ознакомьтесь со статьей на MSDN: Добавление и редактирование ресурсов (Visual C#)
Для добавления ресурсов в проект необходимо щелкнуть правой кнопкой мыши узел Свойства в проекте в Обозревателе решений, щелкнуть Открыть, а затем на странице Ресурсы в Конструкторе проектов нажать кнопку
Добавить ресурс. Ресурсы можно добавить в проект в качестве связанных ресурсов (внешние файлы) или как внедренные ресурсы (внедренные непосредственно в файл RESX).

*

*При добавлении связанного ресурса в файле RESX со сведениями о    ресурсах проекта будет указан только относительный путь на файл    ресурса на диске. Если в качестве связанных ресурсов добавить    изображения, видео или другие сложные файлы, их можно будет изменять   в редакторе по умолчанию, сопоставленном с соответствующим типом    файла в конструкторе ресурсов.

*В случае внедренных ресурсов, данные хранятся непосредственно в файле    ресурсов проекта (RESX). Строки могут храниться только как внедренные    ресурсы.

После добавления файлов в ресурсы, добавленные файлы помещаются в папку Resources, находящуюся в корне проекта.
Также можно задать действие при построении:

*

*None — файл не включается в выходную группу проекта и не
компилируется в процессе построения. Примером такого файла является
текстовый файл документации, например файл Readme.

*Compile — файл компилируется в выходные файлы построения. Эта
настройка используется для файлов кода.

*Content — файл не компилируется, но включается в выходную группу
"Содержимое". Этот вариант используется по умолчанию для файлов HTM и
других веб-файлов.

*Embedded Resource — файл внедряется в основные выходные файлы
построения проекта в виде DLL или исполняемого файла. Обычно это
значение используется для файлов ресурсов.

Для задания свойства Действие при построении (Build Action) или свойства Копировать в выходной каталог(Copy to Output Directory) необходимо зайти в свойства у файла ресурсов и изменить необходимое свойство.
Собственно говоря, Вас интересует свойство Действие при построении (Build Action) - которое необходимо указать под Ваши нужды.
Полезные ссылки для изучения:

*

*Свойства файла

*Связанные и внедренные ресурсы

*Ресурсы в файле формата .Resx

*Ресурсы в приложениях

*Упаковка и развертывание ресурсов


text:
Q: Compute anomaly temperature trends in R I would like to perform an anomaly temperature trends analysis in R. I have temperature data from 1901 to 2012. My idea to compute anomaly temperature trends was as follows:
1. Compute temperature means per month over this time period
2. Subtract temperature means from actual data, to get an anomaly in temperature per month.
3. Perform a linear regression on this anomaly values to get the anomaly temperature trends.
However, I am not quite sure about the approach. Anyone has done this before and could give me some hints?


text:
Q: Is it possible to get results for one way trips using Sabre's Destination Finder? I am working on a flights planning app and considering using Sabre to handle my backend.
My app requires an "Explore Destionations" functionallity, something simillar to Google Flights' Explore Destionations featrue.
In theory, Destination Finder would have been perfect for the job.
The problem is, Destination Finder doesn't seem to provide a way to search for one way trips. In other words, you have to provide a return date.
Does anyone know if there is a way to achive this, Either by using Destination Finder or using a different API?

A: At the moment Destination Finder will only provide Round Trip Lead Fares as part of the Inspirational Shop request.
For One Way Shopping, you can look at the Bargain Finder Max API under Search for Air, available in both REST and SOAP.
https://developer.sabre.com/docs/read/rest_apis/air/search/bargain_finder_max
Best

A: You need to use Bargain Finder Max APi
https://developer.sabre.com/docs/read/rest_apis/air/search/bargain_finder_max
Set
OTA_AirLowFareSearchRQ.TravelPreferences.TPA_Extensions.TripType.Value="OneWay"

I tired with DXB=>LHR but it returned connecting airports but for LAX=>JFK direct results I guess sabre is not strong in europe may be thats the reason


text:
Q: MS access after DB check form wont open I have a access DB and at startup I want to check if the link DB is avalible so I did
the following:
cDBPath = Application.CurrentProject.Path
Set db = CurrentDb
Dim Relink_Tables
Dim rsCheckLink As Recordset
Relink_Tables = False

For Each tdf In db.TableDefs
     If Len(tdf.Connect) > 0 Then
        'Linked table - test link is current
            DoCmd.Echo False, "Checking link for table " & tdf.Name
            On Error Resume Next 'Do not stop script on error
            Set rsCheckLink = db.OpenRecordset(tdf.Name) ' OPEN TABLE
            If Err.Number <> 0 Then ' COULD NOT OPEN TABLE
                On Error GoTo 0
                Relink_Tables = True
                'GoTo Relink_Tables ' RECONNECT TO APPROPIATE DATABASE
            Else
                On Error GoTo 0
                rsCheckLink.Close ' CLOSE TABLE THAT DID OPEN
                Set rsCheckLink = Nothing
            End If
    End If
Next

If Relink_Tables = True Then
   Reling_DB...
End If

that part works just fine, the problem is that after that I try to open my main form like: DoCmd.OpenForm "MyForm", but it wont open (if I opened the DB by double-clicking the file) nly if I close the DB from the Access's main menu and then re-open it from the 'recent files list' then it will work properly why is that???

A: My guess is that the form does open, but it doesn't show, because of this line:
DoCmd.Echo False, "Checking link for table " & tdf.Name

If you turn screen output off, you must be 100% sure that your code works, and that you turn it back on under all circumstances (including error cases).
Actually I don't see a reason to turn Echo off here at all.
To show a status message, and turn the hourglass cursor on, I have a function like this in a public module:
' Show (strStatus <> "") or remove (strStatus = "") a statusbar message
Public Sub StatusMsg(strStatus As String, Optional bHourglass As Boolean = False)

    On Error Resume Next

    If strStatus = "" Then
        SysCmd acSysCmdClearStatus
    Else
        SysCmd acSysCmdSetStatus, strStatus
    End If

    DoCmd.Hourglass bHourglass
    DoEvents

End Sub

and call it like
StatusMsg "Doing some lengthy stuff", True
' some lengthy stuff here
StatusMsg "", False


text:
Q: AWS Lambda timeout issue with spring boot application I have a spring boot application which I am trying to deploy on AWS lambda .
I added StreamLambdaHandler as the handler class
public class StreamLambdaHandler implements RequestStreamHandler {
private static SpringBootLambdaContainerHandler<AwsProxyRequest, AwsProxyResponse> handler;

static {
    try {
        //handler = SpringBootLambdaContainerHandler.getAwsProxyHandler(SituationalFlexibilityApp.class);

        // For applications that take longer than 10 seconds to start, use the async builder:

         handler = new SpringBootProxyHandlerBuilder<AwsProxyRequest>()
                            .defaultProxy()
                            .asyncInit()
                            .springBootApplication(SituationalFlexibilityApp.class)
                            .buildAndInitialize();

        // we use the onStartup method of the handler to register our custom filter
        handler.onStartup(servletContext -> {
            FilterRegistration.Dynamic registration = servletContext.addFilter("CognitoIdentityFilter",CognitoIdentityFilter.class);
            registration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
        });
    } catch (ContainerInitializationException e) {
        // if we fail here. We re-throw the exception to force another cold start
        e.printStackTrace();
        throw new RuntimeException("Could not initialize Spring Boot application", e);
    }
}

public StreamLambdaHandler() {
    Timer.enable();
}

/*
 * public StreamLambdaHandler() throws ContainerInitializationException {
 *
 * handler = new SpringBootProxyHandlerBuilder() .defaultProxy() .asyncInit()
 * .springBootApplication(SlowApplication.class) .buildAndInitialize(); }
 */

@Override
public void handleRequest(InputStream input, OutputStream output, Context context) throws IOException {
    handler.proxyStream(input, output, context);

}

When I test it on AWS lambda I get below exception
com.amazonaws.serverless.exceptions.ContainerInitializationException: Could not initialize framework within the 20000ms timeout
so I updated the lambda configuration for a timeout of 5 mins and added below line in the static block of the StreamLambdaHandler class
LambdaContainerHandler.getContainerConfig().setInitializationTimeout(2000000);
Now, I am seeing below exception
Exception in thread "Thread-0" java.lang.IllegalArgumentException: Could not find timer SPRINGBOOT2_COLD_START
Can someone please point me in the correct direction as I a noob in AWS services and lambda

A: I am not seeing this error after commenting out the below code in StreamLambdaHandler method
// Timer.enable();