text:
Q: Why don't I see proper time? Say we have my friend blasting off in a spaceship to Planet Physics and I'm sitting here on earth. I think it's quite obvious that I will measure the proper length between the planets (because I could use a meter ruler and measure it all)  and that he will measure the contracted length (because his length is squished).
What I don't understand is why does he measure the proper time of the journey and I don't. I can appreciate that my friend should measure proper time because "he is stationary relative to both events (launch and touchdown)" but when I sit on earth I think I'm stationary to the launch and touch down too. So, why can I not measure the proper time it takes to reach planet physics? Can you explain why I am not stationary relative to touch down (I always see the planet staying still in the sky!)

A: The proper time is by definition the time as measured by an inertial observer who is present at both events.  That's your friend and not you.

A: Assuming flat spacetime for simplicity, there is a proper time $\Delta\tau$, associated with two events with time-like interval, related to the Lorentz invariant interval $\Delta s^2 = (c\Delta t)^2 - (\Delta r)^2$:
$$c\Delta\tau = \sqrt{\Delta s^2}$$
This proper time is equal to the elapsed time (between the events) given by an inertial clock with world line through both events. Put another way, an unaccelerated clock co-located with both events, will measure the proper time associated with the events.
But in general, there is the proper time $\tau$ along the world line of an accelerated observer through two events (which will always be less than the proper time associated with the two events). This proper time is defined as the elapsed time between the events given by a clock with a world line through both events.
The clock on the spacecraft records the proper time along the accelerated world line from the launch event to the landing event. While the world line of your clock is through the launch event, it is not through the landing event.

A: As other have pointed out, the concept of "proper time" is what Einstein discarded in special relatively. You each experience time and distance differently but in a mutually consistent way and reconcilable way.
You scenario is however not covered by special relativty.
If your friend was making a fly-by Earth follwed by a fly-by of Plant Physics having maintained a constant course and speed, (e.g. without accelerating and decelerating) then you would bot be in "inertial frames" with a constant relative velocity between you and him, which is what special relativity covers.
Because you and your friend start and end with no or little relative velocity but he has had undergone high and sustained acceleration on the space ship while you have not, then your experiences are not symmetrical, there is no "paradox" with him having aged less than you and when he sends you a message to say he arrived, you may be long dead of old age.

A: Special relativity is not special. It is simply a process where an observer A measures observer B when they are in relative motion. There is no preferred frame of reference. Thus observer A cannot say they are stationary (preferred frame) while observing B. They both move away from each other. That is what relativity is.
Both observers see each other's "clocks" run slower. When they return their clocks are identical. This is the result of using a method of observation with a particle or wave that has a finite speed.
Special relativity also applies to sound waves. In fact any wave.
Submarines that use sonar actually observe the other moving submarine shorter than its length when both are stationary or moving in tandem. It is the result of the finite speed of the sound wave.
Lengths do not physically shrink. The just appear to shrink. It is an optical illusion only.


text:
Q: Docker containers gone after a while in CoreOS I have a couple of small projects running on CoreOS beta (899.5.0)
This has happened to me a second time now, that I have 3 containers running. All fine and dandy. Then after a few days of not looking at my websites on that server, I notice that the pages are down when I try to visit them.
And when I log into my CoreOS machine on Digital Ocean and type docker ps, I notice all my containers are gone! This is insane.
I even have a systemd service set up for a couple of them so that if they terminate for whatever reason, that they should run again. But they don't.
I do see this though greeting me when I log in; I'm not sure if it has something to do with it:
Last login: Sun Jan 17 23:42:37 2016 from 81.106.109.70
CoreOS beta (899.5.0)
Failed Units: 13
  sshd@1509-178.62.0.199:22-219.219.114.120:14536.service
  sshd@1541-178.62.0.199:22-219.219.114.120:30158.service
  sshd@1581-178.62.0.199:22-219.219.114.120:17539.service
  sshd@1995-178.62.0.199:22-122.224.34.168:1397.service
  sshd@1996-178.62.0.199:22-122.224.34.168:3789.service
  sshd@2002-178.62.0.199:22-122.224.34.168:2983.service
  sshd@230-178.62.0.199:22-219.219.114.120:51826.service
  sshd@259-178.62.0.199:22-219.219.114.120:38882.service
  sshd@309-178.62.0.199:22-219.219.114.120:34654.service
  sshd@326-178.62.0.199:22-219.219.114.120:21256.service
  sshd@346-178.62.0.199:22-219.219.114.120:39645.service
  sshd@364-178.62.0.199:22-219.219.114.120:63277.service
  sshd@791-178.62.0.199:22-219.219.114.120:37294.service

I couldn't find out any information about this happening on CoreOS whatsoever on Google. Please, any help is appreciated!
P.S. my systemd config looks like this:
szeremi.service
[Unit]
Description=Run %p
Requires=docker.service
After=docker.service

[Service]
Restart=always
ExecStartPre=-/usr/bin/docker kill %p
ExecStartPre=-/usr/bin/docker rm -f %p
ExecStart=/usr/bin/docker run -t --rm --name %p \
  -p 80:8080 \
  amcsi/szeremi
ExecStop=/usr/bin/docker stop %p

[Install]
WantedBy=multi-user.target

EDIT: The latest page of the logfile (journalctl -u szeremi.service) is: https://gist.github.com/amcsi/95c8b0eb71de2f44c16b#file-journalctl-u-szeremi-service

A: The failed sshd units reported at login are the result of failed login attempts against the systemd socket-activated sshd on CoreOS. They're not related to the missing docker containers.
It seems likely that the containers are "disappearing" after the system reboots to perform an automatic update. This is the default setting for updates, and those updates happen with some frequency on the beta channel. You can check how recently the system was rebooted with uptime or some similar command.
If the system has been rebooted and the containers have not been restarted afterward, you can focus troubleshooting on the systemd unit file and service startup. If it hasn't rebooted, the container logs (e.g., docker logs szeremi) and the service's logs (e.g., systemctl status -l szeremi.service) are possible places to begin. #coreos on freenode or the coreos-users mailing list will both have folks ready to help in either case.

A: CoreOS uses systemd to define processes on the host. The service file you have exemplified is a service unit which defines how a docker container will be run. If you are using systemd directly by logging into the CoreOS node directly you must enable the service in order for it to persist across a boot.
The enable sub command of the systemctl program takes a unit as a parameter and creates a symlink within the systemd target file structure. When systemd is booting it starts any service within a given target. This ensures a given service starts at boot.
systemctl enable szeremi.service   # Creates a symlink within systemd
systemctl start szeremi.service    # Starts the service => runs container

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# Write to console slowly I am making a simple game and I want the text to be outputted in the console word by word. The only method I could find is using the Thread.Sleep() function but this only works for each line. How would I make it write word byword instead?

A: You can make helper method as following.
using System.Threading.Tasks;
public static async Task WriteSlowly(string word, TimeSpan delay = default)
{
    if(delay == default) delay = TimeSpan.FromSeconds(1);

    Console.Write(word);
    await Task.Delay(delay);
}

then use it like that
public class Program {
    public async Task Main() {
        while(true)
        {
            await WriteSlowly("amazing");
        }
    }
}

and whenever you need new line simply use it like that:
await WriteSlowly(word + Environment.NewLine);

Of course this is the simplest solution with default delay time, but you get the idea hopefully.


text:
Q: Simulating a network video transfer using my home devices Working on my thesis I need to create a simulation for video transmission in a normal WLAN to detect how much the quality is reduced depending on the number of devices or quality of originating transmission.
I was using NS-3 for this when someone proposed to me to use my home devices (I have a number of computers, tablets, E-readers, video game consoles etc).
It seemed to me like a good idea since I have a fast enough WiFi I can just use my Mac as the hotspot and connect all devices through it then sniff the packets with wireshark and limit the speed of the transfer using "Network Link Conditioner" my question is, would limiting the speed of transfer with the network link conditioner affect the devices using my computer as a hotspot? or does it only affect my personal computer and I need to figure another way of limiting the speed to successfully simulate what I need?

A: I am not 100% sure what you are after, but seeing you mentioned limiting bandwidth on your Mac, this may be in use:
Basically, you'll need a PC that can run FreeBSD and two network interfaces (e.g. a built in NIC plus one other card). You then setup the box to bridge those two cards.
Check out this tutorial to see how Network Bandwidth Latency and Delay Simulation Tutorial
Once setup you can then control the parameters of that bridge using the ipfw command in FreeBSD, allowing you to change bit rates, latency and simulate packet loss.
With this box in between your video sources (the internet?) and with a wifi router on the other side to connect your devices to, you'd be able to simulate a variety of conditions.
[Note: credit for digging this out this link needs to go to a colleague of mine, but I used this on a project once he'd set it up and it was very powerful]


text:
Q: INSERT with GROUP BY in VALUE SELECT Statement - ERROR 1111 (HY000): Invalid use of group function I am trying to count distinct values after Grouping by id then inserting them into another table with the following query:
INSERT INTO table_aggregate
  (id_aggregate, aggregate_column)
(SELECT id_detail, COUNT(DISTINCT(detail_column))
  FROM table_detail
  GROUP BY id_detail)
ON DUPLICATE KEY UPDATE
  aggregate_column = COUNT(DISTINCT(detail_column));

When run I get the error:

ERROR 1111 (HY000): Invalid use of group function

If I run the SELECT statement portion of the query it works fine. Why is it throwing this error?

A: You can not use COUNT in the UPDATE part. Use VALUES(aggregate_column) instead:
INSERT INTO table_aggregate
  (id_aggregate, aggregate_column)
(SELECT id_detail, COUNT(DISTINCT(detail_column))
  FROM table_detail
  GROUP BY id_detail)
ON DUPLICATE KEY UPDATE
  aggregate_column = VALUES(aggregate_column);

http://rextester.com/KTEDM89215

A: You can put the aggregation inside a subquery. Then you can refer to the computed value in the update
INSERT INTO
    table_aggregate (id_aggregate, aggregate_column)
    SELECT
        *
    FROM
        (
            SELECT
                id_detail,
                COUNT(DISTINCT(detail_column)) AS count
            FROM
                table_detail
            GROUP BY
                id_detail
        ) AS aggr
ON DUPLICATE KEY
UPDATE
    aggregate_column = aggr.count


text:
Q: Symfony2, How to create a Drop Down menu based on Class Constants? I have one class with some constant value like below :
class MyClass
{
    const ACCESS_NONE = 0;

    const ACCESS_SUBMIT = 1;

    const ACCESS_VIEW = 2;

    const ACCESS_APPROVE = 3;
}

How can I create something like below in my twig file with Symfony2 :
        <select name="someName">
            <option value="ACCESS_NONE">None</option>
            <option value="ACCESS_VIEW">View</option>
            <option value="ACCESS_SUBMIT">Submit</option>
            <option value="ACCESS_APPROVE">Approve</option>
        </select>

A: As drupality said you can write a method like that:
public static function getConstantsChoices()
{
    return array(
        self::ACCESS_NONE => 'None', //or 'ACCESS_NONE' => 'None' if you want the string
        self::ACCESS_VIEW => 'View',
        self::ACCESS_SUBMIT => 'Submit',
        self::ACCESS_APPROVE => 'Approve',
    );
}

and if you use a form, you can use a choice:
->add('name', 'choice', array(
      'choices' => MyClass::getConstantsChoices()
))

A: You need to create class with proper interface:
http://symfony.com/doc/current/reference/forms/types/choice.html#choice-list
Interface API
You can always create array by hand, but if you want to get constant names in PHP, the only way is reflection:
How to get name of the constant?


text:
Q: Transaction complete, but NFT not transferred I created a smart contract, minted an nft, and now trying to transfer it.
My problem is that transaction completes fine- I can see it in etherscan etc, but nft is not transferred. What are the possible root causes?
async function transferNFT() {
    const nonce = await web3.eth.getTransactionCount(PUBLIC_KEY, 'latest'); //get latest nonce

  //the transaction
    const tx = {
      'from': sender,
      'to': receiver,
      'nonce': nonce,
      'gas': 500000,
      'data': myContract.methods.transferFrom(sender,receiver, 1).encodeABI()
    }

    const signPromise = web3.eth.accounts.signTransaction(tx, PRIVATE_KEY)
    signPromise
    .then((signedTx) => {
        web3.eth.sendSignedTransaction(
        signedTx.rawTransaction,
        function (err, hash) {
            if (!err) {
            console.log(
                "The hash of your transaction is: ",
                hash,
                "\nCheck Alchemy's Mempool to view the status of your transaction!"
            )
            } else {
            console.log(
                "Something went wrong when submitting your transaction:",
                err
            )
            }
        }
        )
    })
    .catch((err) => {
        console.log(" Promise failed:", err)
    })

}
transferNFT()

And the contract. I actually don't call the transfer function as I was expecting to use the openzeppelin transferFrom function. But if I use the transfer function from the contract - the result is the same:

*

*transaction is executed

*NFT is not transferred.
 contract MyNFTv2 is ERC721URIStorage, Ownable {
     using Counters for Counters.Counter;
     Counters.Counter private _tokenIds;
     event NftBought(address _seller, address _buyer, uint256 _price);
     event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);

 mapping (uint256 => uint256) public tokenIdToPrice;
 mapping(uint256 => address) internal idToOwner;

 constructor() public ERC721("MyNFTv2", "NFT") {}

 function mintNFT(address recipient, string memory tokenURI)
     public onlyOwner
     returns (uint256)
 {
     _tokenIds.increment();

     uint256 newItemId = _tokenIds.current();
     _mint(recipient, newItemId);
     _setTokenURI(newItemId, tokenURI);

     return newItemId;
 }

 function allowBuy(uint256 _tokenId, uint256 _price) external {
     require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');
     require(_price > 0, 'Price zero');
     tokenIdToPrice[_tokenId] = _price;
 }

 function disallowBuy(uint256 _tokenId) external {
     require(msg.sender == ownerOf(_tokenId), 'Not owner of this token');
     tokenIdToPrice[_tokenId] = 0;
 }

 function buy(uint256 _tokenId) external payable {
     uint256 price = tokenIdToPrice[_tokenId];
     require(price > 0, 'This token is not for sale');
     require(msg.value == price, 'Incorrect value');

     address seller = ownerOf(_tokenId);
     _transfer(seller, msg.sender, _tokenId);
     tokenIdToPrice[_tokenId] = 0; // not for sale anymore
     payable(seller).transfer(msg.value); // send the ETH to the seller

     emit NftBought(seller, msg.sender, msg.value);
 }

 function transfer(address _to, uint256 _tokenId) public {
     require(msg.sender == idToOwner[_tokenId]);
     idToOwner[_tokenId] = _to;
     emit Transfer(msg.sender, _to, _tokenId);
 }

}

A: const tx = {
    'from': sender,
    'to': receiver,

You're sending the transaction to the token receiver, which is a regular address that doesn't hold any smart contract.
So when you pass them the data field, there's no contract to process it and the transaction just passes through ignoring the data field.
Solution: Set the to field of the transaction to the NFT collection contract. Then it will be able to process the tranferFrom() function and its arguments passed in the data field. Note that the receiver is already passed in the 2nd argument of the function.


text:
Q: Why is HTML5 video timestamp in hours:min:sec for a 50 second video? I have a basic HTML5 video player with a video from my server. The problem is the timestamp. It's displaying as
470:58:14 / 470:58:21
I've never seen this before and I can't find documentation as to why it might happen.
HTML
<video controls controlsList="nodownload" poster="img/wallpaper.jpg" preload="none">
  <source src="videos/title.webm" type="video/webm" />
  <source src="video/title.ogg" type="video/ogg" />
  <source src="video/title.mp4" type="video/mp4" />

Your browser does not support HTML5 video. Please use Chrome, Firefox, Edge or Safari to view this content.

</video>

Timestamp


text:
Q: Using QGIS Atlas outside of Print Composer? I wonder if it is already possible to use the Atlas Panel outside of Print Composer like it would be in ArcGIS with Data Driven Pages. I often use Data Driven Pages to screen through an entire area in order to edit/fix the results of a vectorized classification. Basically I use an index table to check every box of my classification. However, since I'd like to migrate to a free software, I would love to be able to do the same on QGIS.
I wonder if this is already possible of if there is any plugin that would make it possible to use an index table as an auxiliary file to do the screening of an entire raster.

A: QGIS does not have an exact equivalent to the ArcGIS feature "Data Driven Pages."
Here are some QGIS features that allow you to quickly pan from one location to another:
Built-in features

*

*View extent in map canvas
In an atlas in the Print Layout, you can select a map and click "View extent in map canvas" in the item properties. This will zoom and pan the map canvas to the extent shown in the map item.

I mention this method because it's the closest direct equivalent to the feature you asked for, but it's not the most convenient way of panning the map between features, because you have to keep switching between windows. I think you'll find one of these other methods more useful.

*Spatial Bookmarks

Spatial Bookmarks allow you to "bookmark" a geographic location and return to it later. (see the user manual for additional information)

Once a spatial bookmark is created you can zoom to it by clicking on it in the list of bookmarks in the same panel. You can create bookmarks manually by zooming to an area of interest and clicking "Add Bookmark" in the Bookmark Panel. You can also create a list of bookmarks by creating a text file with the extension XML, in this format:
<!DOCTYPE qgis_bookmarks>
<qgis_bookmarks>
  <bookmark>
    <id>1</id>
    <name>New bookmark</name>
    <project></project>
    <xmin>...</xmin>
    <ymin>...</ymin>
    <xmax>...</xmax>
    <ymax>...</ymax>
    <sr_id>...</sr_id>
  </bookmark>
</qgis_bookmarks>

Duplicate the section between the <bookmark> and </bookmark>tags as many times as you want to create spatial bookmarks. Substitute xmin/xmax/ymin/ymax/srid values for each spatial extent between the corresponding tags. The easiest way to do this is to create a couple of bookmarks manually, export them as an xml file, edit the xml file to include your additional bookmarks, and import the edited file.

*Zoom to Feature
Open the attribute table for the "index" layer. Dock the attribute table. Select the first feature in the table, and click the "zoom to feature" button. Repeat with the next feature.

Plugins
If the built-in features of QGIS are not adequate, try some of the many plugins that other QGIS users have developed to supplement the built-in features of QGIS.
To install a plugin, go to the Plugins menu > Manage and install plugins... > find the plugin (eg by typing the name of the plugin into the search bar) > Install plugin.

*

*Power Pan plugin

PowerPan lets you explore an area inch by inch.
PowerPan gives you four buttons to pan around in the four cardinal directions, with the option of setting the horizontal and vertical overlap amounts between consequent views.

*zoomtopaste plugin

Zoom to a specified point on the map from the Clipboard comma delimited Example: copy "5744021,3503546" (without quotes) out of any other program with "Crtl C" to the clipboard and Qgis zooms to the xy coordinates
Zoom to a specified point on the map from the Clipboard comma delimited

*Lat Lon Tools plugin

Tools to capture and zoom to coordinates using decimal, DMS, WKT, GeoJSON, MGRS, and Plus Codes notation. Provides external map support, MGRS & Plus Codes conversion and point digitizing tools. ... The plugin has the following tools.
  ...
  6) Use a list of points for rapid zooming created from a file, direct input, or captured from the map.

*Feature Iterator plugin (This plugin is not currently available for QGIS 3, but I mention it in case you're using QGIS 2.x, or in case the plugin developer updates it for QGIS 3.)

This plugin's purpose is to iterate over a vector layer's features, having the possibility to remove each feature during a step-by-step iteration. One can also define a pair attribute-value that will filter the features to be iterated. During iteration, viewport will be panned to where the feature is, using the same zoom level defined by user.

A: I had also been looking for this feature and found a nice plugin to move between features in a certain layer in your map window:
"Go 2 next feature"

This plugin allows to select a layer and jump from a feature to another. It's possible to select an attribute of the the layer (usually an ID) and follow it. Press "F8" to go to the next feature. It's possibile to use a PAN function or a Zoom function(usefull for poligons and lines). The plugin was created for checking the position of every single feature of a layer without using the attribute table.


text:
Q: How to test with Jasmine a checkbox that shows an html element I'm pretty newbie on Angular test, and I think I have a stupid question, but despite a lot of tutorials and guides I can't find out a valid solution.
I have a checkbox that when it's checked it should show a div, and I want to test it with Jasmine.
This is my HTML:

  Check this! <input #cb type="checkbox" (change)="1" id="checkboxToTest"/>

Hello!

And this is the code in spec file:
  it('should test checkbox', () => {
    const dElement = fixture.debugElement;
    const nElement = dElement.nativeElement;
    const checkBoxElement = nElement.querySelector('#checkboxToTest');
    const box = nElement.querySelector('#divRevealed');

    checkBoxElement.click();

    expect(checkBoxElement.checked);

    fixture.detectChanges();

    expect(box).toBeTruthy();
  });

Obviously the test passes without any problem if I remove the *ngIf statement in HTML...
But why it's not working?
Thanks for any help!

A: The component must be setected after clicking the checkboxElement:

it('should test checkbox', waitForAsync(() => {
    const dElement = fixture.debugElement;
    const nElement = dElement.nativeElement;
    const checkBoxElement = nElement.querySelector('#checkboxToTest');

    checkBoxElement.click();
    fixture.detectChanges();

    expect(checkBoxElement.checked);

    fixture.detectChanges();

    const box = nElement.querySelector('#divRevealed');

    expect(box).toBeDefined();
  }));


text:
Q: Python class methods: when is self not needed I'm trying to rewrite some code using classes. At some point what I want is assign a member function a particular definition using a parameter value for each instance of an object.
Coming from other languages (JavaScript, C++, Haskell, Fortran, ...) I am struggling to understand a few things on Python. One thing is the following distinction of self in class methods.
For instance, the following code obviously won't work:
class fdf:
    def f(x):
        return 666

class gdg(fdf):
    def sq():
        return 7*7

hg = gdg()
hf = fdf()
print(hf.f(),hg.f(),hg.sq())

which gives the error that "sq() takes 0 positional arguments but 1 was given".
The reason, as I understand it, is that at execution time the function is passed a reference to the calling object (the instance calling sq) as first argument before any other parameter/argument we may have defined/called sq with. So the solution is simple: change the code of sq to def sq(self):. Indeed, the Python tutorial 1 seems to suggest that object methods should always be defined with self as first parameter. Doing so we get as expected 666 666 49. So far so good.
However, when I try to implement my class like this:
class Activation:
    def nonLinearBipolarStep(self,x,string=None):
        if not string: return (-1 if x<0 else 1 )
        else: return ('-' if x<0 else '1')

    default='bipolar'
    activationFunctions = {
        'bipolar': nonLinearBipolarStep ,
    }
    def _getActivation(self,func=default):
        return self.activationFunctions.get(func,self.activationFunctions.get(self.default))

    def __init__(self,func=None):
        if func == None: func=self.default
        self.run = self._getActivation(func)

ag = Activation()
print(ag.run(4))

I get the error
nonLinearBipolarStep() missing 1 required positional argument: 'x'

Yet, a workaround ( solution??) is defining the the step function without the parameter self (!) as
def nonLinearBipolarStep(x,string=None):

Then I get the expected behavior (at least for this trivial test) of 1. So, not only is self not needed here, but it even is incorrect an use here!
But according to the tutorial mentioned above, or to the answers in threads like this 2 or this 3, it seems to me this code shouldn't work...or should have some unexpected consequences at some point(?). Indeed, if I remove all references to self in the definition of _getActivation I get the error message _getActivation() takes from 0 to 1 positional arguments but 2 were given which I can understand according to that rule.
The thread "Why is self not used in this method" 4 does not provide a clear answer to me: What syntax detail of the code above tells me that self is not needed? For instance, how is that code different from this tutorial example
class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

? Instantiating this class works as expected, but it complains about missing parameter (I know it could be any label) if defined with none.
This makes me question whether my code is not hiding a time bomb somehow: is self passed as the value for x? It works as expected so I'd say no, but then I'm facing this conundrum.
I guess I'm missing some key ideas of the language. I admit I also struggle with the question the OP of reference 3 is asking^.
[^]: In JS one just uses this in the function body, and the function itself is defined either as member of the object's prototype or as an instance member which then gets assigned correctly using...this.
EDIT:
The thread is long. For those browsing for some help, if you are new to Python, then you may want to check the selected solution and its comments. However, if you already know about bound/unbound methods in Python, you just want to check directly the use of descriptor as described in Blckknght's answer. I finally opted for this way in my code using __get__ in the assignment to run.

A: You're running into one of the more subtle parts of Python's method implementation. It comes down to how the self argument for normal method calls (e.g. some_instance.method()) is bound. It uses the "descriptor" protocol, which is not very well documented (at least, it's not made obvious to new Python programmers).
A descriptor is an object that has a __get__ method (and optionally __set__ and/or __delete__ method, but I'm only going to talk about __get__ here). When such an object is stored in a class variable, Python will call its __get__ method whenever the corresponding name is looked up on an instance. Note that this special behavior does not happen for descriptor objects stored in instance variables, only those that are class variables.
Functions are descriptors. That means that when you save a function as a class variable, its __get__ method will be called when you look it up on an instance. That method will return a "bound method" object which will pass along the self argument to the function automatically.
If you store a function somewhere other than a top-level class variable (such as in a dictionary or in an instance variable), you won't get this binding behavior, since the descriptor protocol won't be invoked when the object is looked up. This usually means you either need to pass self manually, or you should omit the self argument from the function definition in the first place (in which case I'd suggest moving the function out of the class to make it clear it's not intended to be used as a method).
But you can also construct bound methods by hand if you want to. The type is exposed in the types module, as types.MethodType. So you could change your code like this and it should work:
def __init__(self,func=None):
    if func == None: func=self.default
    self.run = types.MethodType(self._getActivation(func), self) # be sure to import types

A: I think what has confused you here is that you're accessing the method via the class attribute activationFunctions, rather than (as an instance would normally be accessed) on the instance itself. For example, given:
class Class:

    def method(self, foo, bar):
        print(self, foo, bar)

    methods = {'method': method}

When we call the method directly from the dictionary:
>>> Class.methods['method'](1, 2, 3)
1 2 3

You can see that we're passing 1 as the self parameter; the method isn't being called on an instance, so no instance is being injected. By contrast, when we call it on an instance:
>>> instance = Class()
>>> instance.method(1, 2)
<__main__.Class object at 0x...> 1 2

Now our arguments are foo and bar, and the instance is self. That's why you think a different number of parameters seem to be required.

In this case, as you don't actually need the instance state in your method, just make it a regular function (note minor revisions for PEP-8 compliance):
def non_linear_bipolar_step(x, string=None):
    if string is not None:
        return -1 if x < 0 else 1
    return '-' if x < 0 else '1'

class Activation:

    activation_functions = {
        'bipolar': non_linear_bipolar_step,
    }

    ...

This is likely less confusing.

A: What is self?
In Python, every normal method is forced to accept a parameter commonly named self. This is an instance of class - an object. This is how Python methods interact with a class's state.
You are allowed to rename this parameter whatever you please. but it will always have the same value:
>>> class Class:
    def method(foo): #
        print(foo)

>>> cls = Class()
>>> cls.method()
<__main__.F object at 0x03E41D90>
>>>

But then why does my example work?
However, what you are probably confused about is how this code works differently:
>>> class Class:
    def method(foo):
        print(foo)

    methods = {'method': method}

    def __init__(self):
        self.run = self.methods['method']

>>> cls = Class()
>>> cls.run(3)
3
>>>

This is because of the distinction between bound, and unbound methods in Python.
When we do this in __init__():
self.run = self.methods['method']

We are referring to the unbound method method. That means that our reference to method is not bound to any specific instance of Class, and thus, Python will not force method to accept an object instance.  because it does not have one to give.
The above code would be the same as doing this:
>>> class Class:
    def method(foo):
        print(foo)

>>> Class.method(3)
3
>>>

In both examples, we are calling the method method of the class object Class , and not an instance of the Class object.
We can further see this distinction by examining the repr for a bound and unbound method:
>>> class Class:
    def method(foo):
        print(foo)

>>> Class.method
<function Class.method at 0x03E43D68>
>>> cls = Class()
>>> cls.method
<bound method Class.method of <__main__.Class object at 0x03BD2FB0>>
>>>

As you can see, in the first example when we do Class.method, Python shows:
<function Class.method at 0x03E43D68>. I've lied to you a little bit. When we have an unbound method of a class, Python treats them as plain functions. So method is simply a function that is not bound to any instance of `Class.
However in the second example, when we create an instance of Class, and then access the method object of it, we see printed: <bound method Class.method of <__main__.Class object at 0x03BD2FB0>>.
The key part to notice is bound method Class.method. That means method is **bound** to cls - a specfic an instance of Class.
General remarks
As @jonshapre mentioned, writing code like in your example leads to confusion (as proof by this question), and bugs. It would be a better idea if you simply defined nonLinearBipolarStep() outside of Activation, and reference that from inside of Activation.activation_functions:
def nonLinearBipolarStep(self,x,string=None):
        if not string: return (-1 if x<0 else 1 )
        else: return ('-' if x<0 else '1')

class Activation:

    activation_functions = {
        'bipolar': nonLinearBipolarStep,
    }

    ...

I guess a more specific question would be: what should I pay attention to on that code in order to become evident that ag.run(x) would be a call to an unbound function?

If you'd still like to let nonLinearBipolarStep be unbound, then I recommend simply being carefully. If you think your method would make for the cleanest code then go for it, but make sure you know what you are doing and the behavior your code will have.
If you still wanted to make is clear to users of your class that ag.run() would be static, you could document it in a docstring somewhere, but that is something the user really shouldn't even have to be concerned with at all.

A: You're using unbound method (nonLinearBipolarStep) in this code:
activationFunctions = {
    'bipolar': nonLinearBipolarStep ,
}

Longer answer: methods are functions defined within class body and always take at least one argument, so called self (unless you use @staticfunction and turn them into normal functions). Self is an object of a given class, on which method is called (like this in C++). In python there's almost nothing special about this argument, it doesnt have to be named self. Now when you call unbound method, then first argument you've given will be interpreted as self and consumed. If you call bound methods, then this consumption doesnt happen (the method already has its self object). For example:
class A:
  def foo(self, x): print(x)
a = A()
a.foo(1) # a.foo is bound method, a is self, prints 1
A.foo(a, 2) # A.foo is unbound method, first argument becomes self, prints 2

UPDATE:
Why it works at all. Short answer: because dot (.) operator will update unbound method to bound when it can.
Consider, what happens, when you write a.foo(1). First python check object a for foo and finds nothing (foo is not a value assigned to a). So it goes to a class (named A) and lo and behold - foo is there and is used. But here is a trick. Python will bind object a to unbound method A.foo (details escape me now, so imagine dragon did it) and make it into bound method. So a.foo is bound and doesnt need self anymore from arguments, thus 1 goes into argument x and everything works.
Now to your code: you use 'bipolar': nonLinearBipolarStep in map, which is unbound method. Then in constructor (init) you set self.run to value returned from _getActivation, which is taken from activationFunctions map. In given example you return nonLinearBipolarStep unbound method and assign it to self.run. Now you call ag.run. Going by the logic from the previous paragraph ag.run is first looked inside ag object. And here is your error - its found. As python found ag.run value inside ag object, it never consulted ag type (Activation) for run object and never had a chance to bind it. So ag.run is unbound method and expect self argument as first.
You've in general two options. Either do ag.run(ag, 4), which will work, but its ugly, or manually bind method to self in constructor. The latter you can do like this:
self.run = self._getActivation(func).__get__(self)


text:
Q: How does the Get-ChildItem -Exclude Parameter work? How does the Get-ChildItem -Exclude parameter work?  What rules does it follow?
The Get-Help for Get-ChildItem isn't detailed at all:

Omits the specified items. The value of this parameter qualifies the
  Path parameter. Enter a path element or pattern, such as "*.txt".
  Wildcards are permitted.

And on Stackoverflow and elsewhere the general consensus seems to be it's too difficult to use and we should all just pipe the output of Get-ChildItem to Where-Object instead.
While I'm willing to use Where-Object I'm curious as to the rules -Exclude follows.
For example, I have a folder with the following sub-folders:
HsacFixtures
HsacFixturesBuild
RestFixture
RestFixtureBuild

If I execute the following command:
Get-ChildItem $rootFolderPath -Exclude HsacFixturesBuild -Directory

it returns the results expected:
HsacFixtures
RestFixture
RestFixtureBuild

However, if I add a -Recurse parameter:
Get-ChildItem $rootFolderPath -Exclude HsacFixturesBuild -Directory -Recurse

Then it returns sub-folders in the HsacFixturesBuild folder.
I've also tried HsacFixturesBuild\ and HsacFixturesBuild\*, which have the same results.
So does -Exclude only apply to immediate children, and not to grand-children or deeper sub-folders?

A: With respect to Get-ChildItem,-exclude parameter works on the objects name
It could be understood better from the following example:
Consider the following folder structure

First we use -exclude parameter without recurse.

As we could see in the above image, based on objects name , folder was excluded
Now we add recurse parameter to the above statement as follows

Now we see  could see that sub-folders of folder is still present, because the exclusion was applied at objects name
Hope this HElps.

A: Exclude omits child objects based on the Name,

For files, gets the name of the file. For directories, gets the name
  of the last directory in the hierarchy if a hierarchy exists.
  Otherwise, the Name property gets the name of the directory

not the FullName,

which gets the full path of the directory or file

So even though the object is a grandchild in a recursive call, the exclude only looks at the object's Name, not the FullName so the exclude wont affect omission unless the child objects share a common substring of the name that happens to be part of the exclude parameter
Source Get-ChildItem

Example 3: Get all child items using an inclusion and exclusion
This command lists the .txt files in the Logs subdirectory, except for
  those whose names start with the letter A. It uses the wildcard
  character (*) to indicate the contents of the Logs subdirectory, not
  the directory container. Because the command does not include the
  Recurse parameter, the command does not include the content of
  directory automatically; you need to specify it.
Windows PowerShell
PS C:\> Get-ChildItem –Path "C:\Windows\Logs\*" -Include "*.txt" -Exclude "A*"


text:
Q: Object in Kotlin/Singleton -> different instance (?) I have an app with a bottom navigation and a toolbar.
The bottom navigation opens different fragments and the toolbar is suppose to change depending on the fragment (not implemented yet).
The toolbar is initialized in the main activity and depending on which fragment will be opened the menu of the toolbar will be inflated differently. There are different methods in the main activity which inflate the menu and set up the onClickListeners.
Inside OnCreate in MainActivity
        if (savedInstanceState == null) {
            supportFragmentManager
                .beginTransaction()
                .replace(R.id.main_container, QuickNPangFragment.QuickNPangFragment.newInstance(), "activitySelection")
                .addToBackStack("navigation_quick")
                .commit()
            supportFragmentManager.executePendingTransactions()
        }
[...]

        val toolbar: Toolbar = findViewById(R.id.toolbarNew)
        when (supportFragmentManager.getBackStackEntryAt(supportFragmentManager.backStackEntryCount-1).name) {
            "navigation_quick" -> setQuickMenu(toolbar)
            "navigation_location" -> setLocationMenu(toolbar)
            "navigation_friends" -> setFriendsMenu(toolbar)
        }

[...]

    private fun setQuickMenu(toolbar: Toolbar) {
        toolbar.inflateMenu(R.menu.menu_main)
        toolbar.setOnMenuItemClickListener {
            QuickNPangFragment.QuickNPangFragment.newInstance().setQuickMenuItemClickListener(it.itemId)
            true
        }
    }

Inside QuickNPangFragment
    object QuickNPangFragment {
        fun newInstance() = QuickNPangFragment()
    }

There is something wrong in my understanding of this concept of the singleton: I think that only ONE instance of this fragment will be created, so whenever I call the newInstance() method of the fragment, it will return the same instance.
When running the debugger though it shows that the reference to the QuickNPangFragment object that is added when calling onCreate (this = {QuickNPangFragment@10915}... << this is the address, correct?) is different from the one when setting up the onClickListener in the setQuickMenu method (this = {QuickNPangFragment@11154}).
1) What am making wrong? and/or Where is the misunderstanding of that concept?
2) Is it ok to change the toolbar menu depending on the fragment?


text:
Q: Habilitar/deshabilitar boton en datatable server-side Utilizo datatables server-side primero para traerlo de la bd y despues agregar ese producto seleccionado a una clase para irse agregando los productos que se deseen. Esto ya lo pude hacer, mi problema es que ahora quiero deshabilitar el boton que agrega el producto seleccionado y lo que e conseguido es que me deshabilita todos los botones de todos los productos. Les comparto el codigo que tengo hasta ahora:
var tablaCreapedidos = $(".tablaCreapedidos").DataTable({
responsive: true,
deferRender: true,
processing: true,
serverSide: true,
ajax: "ajax/serversideCreapedido.php",
columnDefs: [{
    "targets": 4,
    "data": null,
    "render": function (data, type, row){
        'use strict';
        return '
<button class="btn btn-info btn-sm btnAgregarProducto" id="' + row[0] + '"></button>
';
    }
},
{
 "targets": 3,
 "render": function (data, type, row) {
    'use strict';
    if (data === "") {
        return '';
    } else {return ''; }
 }
}],
language: {
    url: 'plugins/datatables/Spanish.json'
}
});

Lo anterior es para iniciar la tabla, ahora les muestro donde traigo el producto:
i$(document).on("click", ".btnAgregarProducto", function () {
'use strict';
var idProdpe = $(this).attr("id");
var datos = new FormData();
datos.append("idProduct", idProdpe);
$.ajax({
    url: 'controlador/traerProducto.php',
    method: "POST",
    data: datos,
    cache: false,
    contentType: false,
    processData: false,
    dataType: "json",
    success: function (respuesta) {
        tablaCreapedidos.on('draw', function(){
            $(".btnAgregarProducto").removeClass("btn-info");
            $(".btnAgregarProducto").addClass("btn-outline-info disabled");
        }).ajax.reload(null, false);
        var nombre = respuesta.nombre_producto;
        var costo = respuesta.precio_venta;
        $(".nuevoPropedido").append(
            '
'+
             '
'+
              '
'+
               '
'+
                '<button type="button" class="btn btn-danger btnQuitarProducto" idProdpe="'+idProdpe+'"></button>'+
               '
'+
               '<input type="text" class="form-control" id="agregarPropedido" name="agregarPropedido" value="'+nombre+'" readonly>'+
              '
'+
             '
'+
             '
'+
              '<input type="number" class="form-control" id="agregarProcantidad" name="agregarProcantidad" min="1" step="1" value="1">'+
             '
'+
             '
'+
              '
'+
               '
'+
                ''+
               '
'+
               '<input type="text" class="form-control" id="agregarProprecio" name="agregarProprecio" value="'+costo+'" readonly>'+
              '
'+
             '
'+
            '
'
         );
    }
});
});

Con este codigo solo consigo que todos los botones se deshabiliten:

Y con el siguiente codigo todos se vuelven a habilitar:
$(".formCreapedido").on("click", ".btnQuitarProducto", function () {
'use strict';
$(this).parent().parent().parent().parent().remove();
var idProdpe = $(this).attr("idProdpe");
tablaCreapedidos.on('draw', function(){
    $(".btnAgregarProducto").removeClass("btn-outline-info disabled");
    $(".btnAgregarProducto").addClass("btn-info");
}).ajax.reload(null, false);
});

como puedo hacer para que solo se deshabilite el boton del producto que se selecciona?

A: Antes de empezar, un error importante es asignar eventos dentro de otros eventos, porque se encadenan, por ejemplo:
$(document).on("click", ".btnAgregarProducto", function () {
    tablaCreapedidos.on('draw', function() {
        // ¿Cuántas alertas se muestran en cada clic?
        alert('Producto agregado');

        $(".btnAgregarProducto").removeClass("btn-info");
        $(".btnAgregarProducto").addClass("btn-outline-info disabled");
    }).ajax.reload(null, false);
});

Lo más seguro es que con cada clic en botones para agregar productos se vayan incrementando las alertas.
Posible solución:
El problema es que $(selector).removeClass(clase); quita la clase especificada a todos los elementos que coincidan con el selector, no solo a uno. Cuando asignas evento a un selector, dentro de la función puedes acceder al elemento que disparó el evento con $(this) y aplicar los cambios solo ahí.
Cambia la función tablaCreapedidos.on('draw', function() { ... }).ajax.reload(null, false); por las siguientes tres líneas para desactivar solo el botón correspondiente.
            // Deshabilitar solo el botón que recibió clic
            $(this).removeClass("btn-info");
            $(this).addClass("btn-outline-info disabled");

Esto resuelve solo el botón del producto actual, pero todavía falta que se desactive otra vez cuando la tabla obtenga nuevos datos y vuelva a aparecer el mismo producto. Para eso se necesita identificar fácilmente qué productos están agregados y, lo más sencillo, es agregar id de producto como atributo de datos en el contenedor:
$(document).on("click", ".btnAgregarProducto", function () {
    'use strict';
    var idProdpe = $(this).attr("id");
    var datos = new FormData();
    datos.append("idProduct", idProdpe);
    $.ajax({
        url: 'controlador/traerProducto.php',
        method: "POST",
        data: datos,
        cache: false,
        contentType: false,
        processData: false,
        dataType: "json",
        success: function (respuesta) {
            // Deshabilitar solo el botón que recibió clic
            $(this).removeClass("btn-info");
            $(this).addClass("btn-outline-info disabled");

            var nombre = respuesta.nombre_producto;
            var costo = respuesta.precio_venta;
            $(".nuevoPropedido").append(
                // Agregar ID de producto como atributo de datos
                '
'+
                 '
'+
                  '
'+
                   '
'+
                    '<button type="button" class="btn btn-danger btnQuitarProducto" idProdpe="'+idProdpe+'"></button>'+
                   '
'+
                   '<input type="text" class="form-control" id="agregarPropedido" name="agregarPropedido" value="'+nombre+'" readonly>'+
                  '
'+
                 '
'+
                 '
'+
                  '<input type="number" class="form-control" id="agregarProcantidad" name="agregarProcantidad" min="1" step="1" value="1">'+
                 '
'+
                 '
'+
                  '
'+
                   '
'+
                    ''+
                   '
'+
                   '<input type="text" class="form-control" id="agregarProprecio" name="agregarProprecio" value="'+costo+'" readonly>'+
                  '
'+
                 '
'+
                '
'
             );
        }
    });
});

Ahora se necesita una función para activar y desactivar botones, recorriendo cada uno y revisando si el producto ya está agregado.
function checarBotones() {
    // Recorrer botones
    $(".btnAgregarProducto").each(function() {
        // Obtener id de producto
        let idProdpe = $(this).attr('id');
        // Verificar si el producto ya se agregó a pedido
        // Buscando por contenedor, clase y atributo de datos
        if($(`.nuevoPedido .row[data-prodpe="${idProdpe}"]`).length > 0) {
            // El producto está agregado, desactivar botón
            $(this).removeClass("btn-info");
            $(this).addClass("btn-outline-info disabled");
        } else {
            // No está agregado, activar botón
            $(this).addClass("btn-info");
            $(this).removeClass("btn-outline-info disabled");
        }
    });
}

Cuando la tabla se actualice debes ejecutar esa función para activar o desactivar cada botón, dependiendo de si está agregado al pedido o no. Recuerda poner esta línea fuera de cualquier función, no debe depender de otros eventos.
tablaCreapedidos.on('draw', checarBotones);

Finalmente, cuando eliminas un producto del pedido solo necesitas volver a ejecutar la función para actualizar botones:
$(".formCreapedido").on("click", ".btnQuitarProducto", function () {
    'use strict';
    // En lugar de usar tantos parent() llega al padre con closest()
    $(this).closest('div.row').remove();
    // Actualizar botones
    checarBotones();
});

Referencias:

*

*.length devuelve la cantidad de elementos que jQuery encontró para el selector especificado

*.parent() devuelve el padre inmediato y, a veces, es necesario usar varios para llegar al que realmente se desea seleccionar

*.closest() devuelve el ancestro que coincide con el selector, sin necesidad de hacerlo en varios pasos

Importante: Si el identificador de producto es numérico, entonces también es un error asignarlo como atributo ID del botón:
return '
<button class="btn btn-info btn-sm btnAgregarProducto" id="' + row[0] + '"></button>
';

Según la documentación:

Nota: El uso de caracteres a excepción de letras en ASCII, dígitos, '_', '-' y '.' pueden ocasionar problemas de compatibilidad, por no ser permitidos en HTML 4. A pesar de que esta limitación ha sido removida en HTML 5, un ID debe iniciar con una letra para asegurar la compatibilidad.

A: Bien, la solución que encontré para que en la tabla me mostrara los botones habilitados/deshabilitados al darle clic a los botones de paginación y a la opción de mostrar x registros por pagina, es la siguiente:
En la parte de inicializar la tabla la deje de este modo:
"targets": 4,
    "data": null,
    "render": function (data, type, row){
        'use strict';
        /*dejo 2 clases: bntAgregarProducto - recuperarBoton*/
        /*capturo el id del producto*/
        return '
<button class="btn btn-info btn-sm btnAgregarProducto recuperarBoton" idProducto="' + row[0] + '"></button>
';
    }

Ahora dentro donde traigo al producto lo deje así:
tablaCreapedidos.on('draw', function(){
    /*aqui le quito la clase btnAgregarProducto para que no se vuelva */
    /*a disparar nuevamente la función, agrego la clase para cambiar el*/
    /*aspecto del boton y deshabilitarlo, todo esto donde*/
    /*idProducto sea igual al boton donde di clic y redibujo la tabla*/
    $(".recuperarBoton[idProducto='" + idProdpe + "']").removeClass("btn-info btnAgregarProducto");
    $(".recuperarBoton[idProducto='" + idProdpe + "']").addClass("btn-outline-info disabled");
}).ajax.reload(null, false);

Finalmente para habilitar nuevamente el botón lo deje de esta manera:
$(".formCreapedido").on("click", ".btnQuitarProducto", function () {
'use strict';
$(this).closest('div.row').remove();
var idProdpe = $(this).attr("idProdpe");
tablaCreapedidos.on('draw', function(){
    /*lo inverso a cuando deshabilite el boton*/
    $(".recuperarBoton[idProducto='" + idProdpe + "']").removeClass("btn-outline-info disabled");
    $(".recuperarBoton[idProducto='" + idProdpe + "']").addClass("btn-info btnAgregarProducto");
}).ajax.reload(null, false);
});

Con esto ya navego en toda la tabla y me respeta los botones habilitados/deshabilitados. A como yo lo entiendo (desde ya me pueden corregir, esto que hice es solo una solución), cada que se da clic en un botón habilitado se tiene que "dibujar" la tabla nuevamente mostrando ahora el mismo botón pero deshabilitado, igual a la inversa, es decir, al habilitar nuevamente el botón volver a "dibujar" la tabla. Aquí dejo un ejemplo donde mi problema inicial probablemente sirviera de solución al igual que se hace mención de draw().


text:
Q: Using Libgdx seek behaviour with box2d? I'm trying to implement the seek behaviour of Libgdx using Box2d to actually move the body onscreen.
I understand how the seek behaviour works and have my two object classes which implement the Steerable interface. I have looked at the Seek class and I don't quite understand how SteeringAcceleration works with it.
At the moment I have(these are the relevant bits):
In my game/rendering/main world class:
//fields
Seek<Vector2> s;
Object a;
Object b;

//constructer
s = new Seek<Vector2>(b,a);
    s.setEnabled(true);

//run
s.calculateSteering(//not sure what to put here for SteeringAcceleration param?);

In my Object classes:
public float getMaxAngularAcceleration() {
    return 5;//not sure what to put here yet
}

@Override
public Vector2 getPosition() {
    return new Vector2(sprite.getX(), sprite.getY());
}

^^These seem to be the only methods of Steerable I need to change for Seek.
I have read the libgdx tutorial on behaviours and I understand them in theory but I can't for the life of me figure out how to put it all together in code. I know I must need to apply a force or impulse to the body to get it to actually go where calculateSteering tells it but I don't know where to perform that and what exactly to put in the parameter of calculate steering. Any help would be greatly appreciated.

A: SteeringAcceleration is just a class that holds the linear and angular acceleration that the seek behavior has calculated.
SteeringAcceleration<Vector2> steerAcc = new SteeringAcceleration<Vector2>();
s.calculateSteering(steerAcc);

Then in your update method you apply the acceleration values that is in SteeringAcceleration to the box2d body.
body.applyLinearImpulse(steerAcc.linear.scl(deltaTime), pos, true);
body.applyAngularImpulse(steerAcc.angular * deltaTime, true);


text:
Q: When to use phrase in Prolog? I'm trying to learn more about DCGs in Prolog and while reading through different sources, I noticed that in some cases phrase wasn't being used ?
From the Learn Prolog Now website, it presents this example:
s   -->  np,vp.
np  -->  det,n.
vp  -->  v,np.
vp  -->  v.
det -->  [the].
det -->  [a].
n   -->  [woman].
n   -->  [man].
v   -->  [shoots].

They then use the query s(X,[]) to generate all the sentences in the grammar.
I tried phrase(s,L) and it also generates all the sentences described by the grammar.
What's the difference in using s(X,[]) and phrase(s,L)? When should phrase be used?

A: Actually, SWI-Prolog performs type checking (arguments must proper lists), then exhibits a performance penalty when using phrase/3.
Also, to allow for using a DCG and perform 'state threading', that is handing off to hidden parameters the state propagation, a call_dcg/3 has been introduced.
But for normal usage - lexical parsing and generation - phrase is the way to go.

A: Grammar rules should always be accessed using the phrase/2-3 predicates. When the first argument is instantiated, the Prolog compiler should be expected to convert the phrase/2-3 call to a call to the predicate generated by the compilation of called grammar rule. Thus, there should be no overhead by using the phrase/2-3 predicates.


text:
Q: Subtracting current time from deadline time in C I want to write a code as a subproblem of a project that takes input the deadline time of anything in Hours,minutes,seconds and subtracts the current local time and shows it.
I can use the clock() function to get the current time but i don't know how to subtract the input from it because I don't know what's going on inside the clock function, can anybody help?


text:
Q: unable to get request.body in express I am playing with express and trying to understand the basic work of form submission and I am unable to get data on req.body(gives empty object).Here is the html and js file I am using.
HTML File
         <form class="form-horizontal" id="form" action="/action" method="post" role="form">

Registration Form

                Full Name

                    <input type="text" id="firstName" placeholder="Full Name" class="form-control" autofocus="">
                    Last Name, First Name, eg.: Smith, Harry

                Email

                    <input type="email" id="email" placeholder="Email" class="form-control">

        </form>

and
Javascript File
var express = require('express');
var bodyParser = require('body-parser');
var app     = express();

app.use(bodyParser.urlencoded({ extended: true }));

var MongoClient = require('mongodb').MongoClient;
var myCollection;

app.post('/action', function (req, res) {
    console.log("----------------------",req.body);
    res.send("done");
});

app.get('/', function (req, res) {
  res.sendFile(__dirname+"/signup.html");
});

 app.listen(3000, function () {
 console.log('Example app listening on port 3000!');
 var db = MongoClient.connect('mongodb://127.0.0.1:27017/test',
   function(err, db) {
       if(err)
        throw err;
      else{
        console.log("connected to the mongoDB !");
        myCollection = db.collection('test_collection');
      }
  });
});

A: Form inputs need to have a name for bodyparser to build req.body
Add name to firstname and email input fields.
<input type="email" id="email" placeholder="Email" class="form-control" name="email">
<input type="text" id="firstName" placeholder="Full Name" class="form-control" autofocus="" name="firstName">

A: I had a similar issue, but there is no key (not json), it was xml body
The solution is here: https://stackoverflow.com/a/45709414/984471


text:
Q: NSCollectionView - custom view item either isn't wired or won't select Here's how I create the collection view item:
func collectionView(collectionView: NSCollectionView, itemForRepresentedObjectAtIndexPath indexPath: NSIndexPath) -> NSCollectionViewItem {
    let item = collectionView.makeItemWithIdentifier("ViewItem", forIndexPath: indexPath)
    guard let collectionViewItem = item as? ViewItem else {
        return item
    }
    return collectionViewItem
}

If I don't register the custom class ViewItem, selection works! As expected, IBOutlets are nil and I can't modify the object.
Before reloadData in viewDidLoad, if I use self.collectionView.registerClass(ViewItem.self, forItemWithIdentifier: "ViewItem"), then IBOutlets are wired, and I can change the object, but no selection seems to work.
func collectionView(collectionView: NSCollectionView, didSelectItemsAtIndexPaths indexPaths: Set<NSIndexPath>) {
    print("Select")
}

Never gets called. ViewItem is a xib with base class NSCollectionViewItem. It has a single label (for now, to test this to get it working), and I've changed no default options.
What am I missing?

A: Try adding
collectionView.selectable = YES

Hope it works for you.


text:
Q: d3.js arrow directed graph: adding nodes/links on the fly I've tried to use this this arrow-head force directed graph example (based on d3.js)
And I want to dynamically add nodes/links to the graph, without restarting the animation.
I'm no expert of javascript, and indeed no expert of d3.js, but no matter what I tried to do, I couldn't manage to create an AddLinks(links) method, that add dynamically more links.
The best I managed to do is adding links dynamically, but those were not aware of the existence of the rest of the graph.
Of course I know what is my problem. I used the "force" method twice, separately, but i couldn't find how to interface with the already existing "force"...

A: The documentation for force.start() explicitly says

In addition, it should be called again whenever the nodes or links change.

So the way to do what you want would be to add the links to the original force layout and then restart the simulation. If you don't restart, those links won't be taken into account and the results of the simulation will look weird.
You could of course try to make seem like the simulation isn't restarted by setting the positions of the nodes to the positions at the end of the current simulation before restarting it.


text:
Q: Достать информацию DMI/SMBIOS из дампа bios(.bin файл) на c# Требуется достать информацию DMI/SMBIOS из дампа bios(.bin файла). Не удалось не где найти способ сделать, ходил достать DMI самого ПК, но из дампа биоса(.bin) не где нету. Надеюсь, кто-то сможет подсказать способ.
С# .netFramework

A: На сайте dmtf.org имеется спецификация SMBIOS, а на гитхабе сишный хидер с описанием структур. Кроме того имеет смысл скачать утилиту "Read & Write Utility", которая может спарсить в читаемый лог весь SMBIOS-дамп. Так можно будет сравнить реальные поля, с описанием из спеки. Теперь есть все составляющие, и написать из них программу не составит особого труда:


text:
Q: How to recognize an IP filter with nmap from two different locations? I am using a VPN (PPTP) connection in Windows to connect to a company. I can do this inside my own company, I cannot connect from home.
I did an nmap from my own company onto this IP address, PPTP 1723 shows as open.
I did an nmap from home onto this IP address, PPTP 1723 shows as filtered.
Question: Why?
Is there an IP filter?


text:
Q: Is there any difference between the notations in case of Markov Chains?
A Markov Chain $(X_n)_n$ has the following transition matrix:
$$P = \begin{bmatrix}
 0.1 & 0.3 & 0.6\\
 0 & 0.4 & 0.6\\
 0.3&0.2&0.5
 \end{bmatrix}$$
  with initial distribution $\alpha = (0.2, 0.3, 0.5)$.

Do the following notations mean different things w.r.t. the above information?

*

*$P(X_1 = 3|X_0 = 1)$

*$P(X_0 = 3|X_1 = 1)$
If Yes, what is that?
Also what does the following mean in case of Markov Chains?

*

*$P(X_0 = 3, X_1 = 1)$

*$P(X_1 = 3, X_0 = 1)$

A: These are standard notations from probability theory. Read a comma as "and" and the vertical bar as "given that." The latter indicates conditional probability; the former a compound event. In particular, $\Pr(X_0=3\mid X_1=1)$ will generally not have the same value as $\Pr(X_0=3,X_1=1)$.


text:
Q: Downloading a file from HTTP connection which redirect to HTTPS connection I am using Dropbox in my project to get tiny url from dropbox which is like http://www.db.tt/xyzabc.
When I try to download the file in HTC My touch my code works fine, but if I try in Motorola Atrix it throws exception unknown host db.tt.
Actually first I have url like http://www.db.tt/xyzabc which is HTTP url I open it than I get exception and in exception I get actual url to file which contain file and is HTTPS url in exception. I start downloading file here is my code which work for me:
public static void fileUrl(String fAddress, String localFileName,
        String destinationDir) {
    OutputStream outStream = null;
    URLConnection uCon = null;

    InputStream is = null;
    try {
        URL url;
        byte[] buf;
        int ByteRead, ByteWritten = 0;
        url = new URL(fAddress);
        outStream = new BufferedOutputStream(new FileOutputStream(
                destinationDir + localFileName));

        try {
            // Here i have "http://www.db.tt/xyzabc"
                       // after i hit url i get exception and in exception that
                       // FileNotFoundException at https://www.dropbox.com/abcxyz
                     // i get actual actual url i parse that exception and
                     //retrive https://www.dropbox.com/xyzabc(actual url)
                      // but in motorolla atrix instead of that url i get
                     // unknownhost exception "db.tt"

            uCon = url.openConnection();
        //  uCon.connect();

            is = uCon.getInputStream();
        } catch (Exception e) {
            url = new URL(e.getMessage().substring(
                    e.getMessage().indexOf("https"),
                    e.getMessage().length()));
            outStream = new BufferedOutputStream(new FileOutputStream(
                    destinationDir + localFileName));

            uCon = url.openConnection();
            is = uCon.getInputStream();
        }

        buf = new byte[size];
        while ((ByteRead = is.read(buf)) != -1) {
            outStream.write(buf, 0, ByteRead);
            ByteWritten += ByteRead;
        }
        System.out.println("Downloaded Successfully.");
        System.out.println("File name:\"" + localFileName
                + "\"\nNo ofbytes :" + ByteWritten);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

A: ok after few attempt i made it solve my self and here is the solution will be helpfull if someone got same problem it requires some error handling and modification according to need
After seeing class heirarchy of Connection i found that HttpsURLConnection is child of HttpURLConnection and HttpURLConnection  is child of UrlConnection  so i i used HTTPConnection instead of UrlConnection and as HttpsUrlConnection is concrete for HttpsUrlConnection it solved my problem
i continue iterating till i get Https url after redirect
public static void fileUrl(String fAddress, String localFileName,
        String destinationDir) {
    OutputStream outStream = null;
    URLConnection uCon = null;
    HttpURLConnection mHttpCon;

    InputStream is = null;
    try {

        URL url;
        byte[] buf;
        int ByteRead, ByteWritten = 0;
        url = new URL(fAddress);
        outStream = new BufferedOutputStream(new FileOutputStream(
                destinationDir + localFileName));

        try {

            mHttpCon = (HttpURLConnection) url.openConnection();

            while (!url.toString().startsWith("https")) {
                mHttpCon.getResponseCode();
                url = mHttpCon.getURL();
                mHttpCon = (HttpURLConnection) url.openConnection();

            }

            is = mHttpCon.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
            // url = new URL(e.getMessage().substring(
            // e.getMessage().indexOf("https"),
            // e.getMessage().length()));
            // outStream = new BufferedOutputStream(new FileOutputStream(
            // destinationDir + localFileName));
            //
            // uCon = url.openConnection();
            // is = uCon.getInputStream();
        }

        buf = new byte[size];
        while ((ByteRead = is.read(buf)) != -1) {
            outStream.write(buf, 0, ByteRead);
            ByteWritten += ByteRead;
        }
        System.out.println("Downloaded Successfully.");
        System.out.println("File name:\"" + localFileName
                + "\"\nNo ofbytes :" + ByteWritten);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

public static void fileDownload(String fAddress, String destinationDir) {

    int slashIndex = fAddress.lastIndexOf('/');
    int periodIndex = fAddress.lastIndexOf('.');

    String fileName = fAddress.substring(slashIndex + 1);

    if (periodIndex >= 1 && slashIndex >= 0
            && slashIndex < fAddress.length() - 1) {
        fileUrl(fAddress, fileName, destinationDir);
    } else {
        System.err.println("path or file name.");
    }
}

A: This answer works - to an extent. I have a similar solution here
There is still a problem with Dropbox short hyperlinks on Atrix. They redirect from http to https but NOT to the required file, instead I get a whole lot of html from inside Dropbox.


text:
Q: Error while passing NULL value to procedure using iBatis We have a Oracle procedure call done using iBatis. One of the IN parameters to the procedure is a VARCHAR2 datatype in procedure and is java.lang.String in Service/DAO layers.
The procedure fails whenever this input parameter is passed with NULL value. When a value is passed, then the procedure gets called without any errors.
For this procedure parameter (which is nullable) within the parametermap, we set the attribute as jdbctype="java.sql.Types.NULL" and it started working.
Is this the correct solution ?
The database connection is established using connection pool (dbcp) created in Tomcat6 server.

A: Ibatis for sure have problems with NULL values passed as parameters.
In our insert query we use such wrapper:
insert into table (column1) values (<isNull property="column1">NULL </isNull><isNotNull property="column1">#column1:INT# </isNotNull>)

A: for those still using the old version of ibatis (2.3 in my case), the above error while passing nullable parameters might be caused by not specifying jdbcType in parameterMap. there is a passage in iBatis 2.3.0 User Guide (p.27, Parameter Maps and Inline Parameters - jdbcType) pointing that out.


text:
Q: Differences between EL 2.1 and 2.2 I am looking for list of differences between EL 2.1 and 2.2.
I know one difference between EL 2.1 and 2.2 is ability to pass method parameters in 2.2.  Are there any other differences?
Is there any feature comparison chart available for the differences?  I have been searching for a few days and haven't been able to locate it so far.
Thank you

A: The answer is in the EL 2.2. specification document. Here's an extract of relevance:

A.1 Changes between Maintenance 1 and Maintenance Release 2
The main change in this release is the addition of method invokations with
  parameters in the EL, such as #{trader.buy("JAVA")}.

*

*Added one method in javax.el.ELResolver:

*

*Object invoke(ELContext context, Object base, Object method, Class<?>[]
  paramTypes, Object[] params).

*Added one method in javax.el.BeanELResolver:

*

*Object invoke(ELContext context, Object base, Object method, Class<?>[]
  paramTypes, Object[] params).

*Added one method in javax.el.CompositeELResolver:

*

*Object invoke(ELContext context, Object base, Object method, Class<?>[]
  paramTypes, Object[] params).

*Section 1.1.1. Added to the first paragraph:
Simlarly, . operator can also be used to invoke methods, when the method name
  is known, but the [] operator can be used to invoke methods dynamically.

*Section 1.2.1. Change the last part of the last paragraph from
Upon evaluation, the EL API verifies that the method conforms to the expected
  signature provided at parse time. There is therefore no coercion performed.
to
Upon evaluation, if the expected signature is provided at parse time, the EL API
  verifies that the method conforms to the expected signature, and there is therefore
  no coercion performed. If the expected signature is not provided at parse time,
  then at evaluation, the method is identified with the information of the
  parameters in the expression and the parameters are coerced to the respective
  formal types.

*Section 1.6. Added syntax for method invocation with parameters. The steps for evaluation of the expression was modified to handle the method
  invocations with parameters.

*Section 1.19. Production of ValueSuffix includes the optional parameters.

No other changes are mentioned. So, it's indeed just only the method invocation capability.


text:
Q: Missing schema when the Swagger Document saved in API Management Front End here's the problem I encountered when I try to add a Front End Swagger document into our team API.
In my original Swagger document (Swagger 2.0), I have a field under the path mentioned response body:
  responses:
    '200':
      description: Success
      schema:
        $ref: '#/definitions/QueryResponse'
    '401':
      $ref: '#/responses/401'
    '403':
      $ref: '#/responses/403'

However once I saved the documents inside the API Management Front End using the OpenAPI Editor, I found the $ref inside the responses are all gone, the document automatically changed to these:
  responses:
    '200':
      description: Success
    '401':
      description: Unauthorized (ensure correct authorization header in the request)
    '403':
      description: >-
        Forbidden to perform the operation (ensure the client has correct
        role for the partition Id)

Not only the $ref for 401 and 403 becomes directly taken text from the responses object, but the schema inside the 200 response is also missing. In my responses under root level it is written like:
responses:
  '401':
    description: Unauthorized (ensure correct authorization header in the request)
  '403':
    description: Forbidden to perform the operation (ensure the client has correct role for the partition Id)
This responses field also missing from the document once I saved.

And in my definitions under root level, there is the QueryResponse schema:
  QueryResponse:
    properties:
      timestamp:
        example: '2019-08-09T10:04:50.49476Z'
        type: string
      message:
        example: 'Hello'
        type: string
    type: object

This schema remained in the document after saved, but because of the $ref is missing from 'responses' field under the 'path', so it did not show as well.
While I also try to input the OpenAPI 3.0 document, I rewrite the document following the official documentation, I also checked about support for OpenAPI 3.0 in API Management, apparently, it is supported under Preview Feature. However, when I input the whole 3.0 document into the editor and was about to save, it shows an error called:
One or more fields contain incorrect values:
Parsing error(s): The Swagger version specified is unknown.
I have checked that in OpenAPI 3.0 there is no 'swagger' field anymore, instead, it is replaced by 'openapi' field, which I put right on the top of the document: openapi: 3.0.0
May I know what is the problem for the missing $ref in 2.0 or the error in 3.0? Thanks and really appreciates if any helps.

UPDATES
The missing schema is solved by putting below field into responses:
produces:
  - application/json

However, now it makes the other responses such as 400, 401 and 403 have the column 'Representations' which shows an empty column row. I do not want that, is there any other way to only apply the produces to the response 200 only? Because that is the only response that haves a JSON body.
Also, the $ref of 401 and 403 still missing and description is taken from the 'responses' under root level.

A: For not having the empty representations to show up in the developer portal, the template data for the operation details page has this causing the empty tabs

I was able to make these changes to the template to get it to not show them as expected while still being able to show them if present


text:
Q: Can I undo composer's dump-autoload? I incorrectly issued composer dump-autoload -o on my PHP project (thinking it did something else!). Is there a way to undo this?
I found an auto-generated file in vendor/composer/autoload_real.php - will just deleting this file do the trick?

A: Yes, manually removing all files of the autoloader in the  vendor/composer/ folder should work.
So, all vendor/composer/autoload_*.php files and the include_paths.php.
By using  dump-autoload -o Composer creates an optimized autoload_classmap.php file.
If in doubt, drop the whole vendor/composer folder and do a composer install afterwards. Composer will then auto-generate the files again.


text:
Q: How to identify which delimiter comes first after word in a string using python I have a string as :
The exam is for testing your skills. The exam includes the following:
1) Aptitude
2)synonyms
3)Reasoning

so i am using string method to identify the index of the word using the following code:
string.find('exam')

it gives me the index of the word in the string. And here i have to identify which delimiter is present at the end of each sentence.
for example:
The exam is for testing your skills. [here it is '.']
The exam includes the following: [here it is ':']

so how do i identify the deimiters with which the sentence ends based on the word search?

A: Your problem statement is somewhat vague, as a clause can end using ",",":",";", but may not end the sentence.  To revise this problem, identify the punctuation you are looking for and set as a list.
The following code identifies the starting position of all of your keywords.
 Then, it locates the first instance of one of your identified punctuation marks that you deem as "end of clause/sentence" and returns it.
import re

text = '''
    The exam is for testing your skills. The exam includes the following:
    1) Aptitude
    2)synonyms
    3)Reasoning'''

targets =[m.start() for m in re.finditer('exam', text)]

end_punct = ['!','.','?',':',';']

for target in targets:
    subtext = text[target:]
    print(subtext)
    for char in subtext:
        if char in end_punct:
            print(char)
            break

Sample return:
#Returns:
.
:


text:
Q: How do I find the key associated with the maximum computed value? I am trying to find out maximum value in a hash and corresponding key to that maximum value. My hash looks like
%hash = (
    bob => "4.9",
    gita => "3.9 , 6.8",
    diu => "3.0",
);

Now I want to find the maximum value in that hash with the key it belongs.
Output needed is
gita 6.8

I am trying to sort the values in %hash in ascending order to get the maximum value like this
sub hashValueAscendingNum {
    $hash{$a} cmp $hash{$b};
}

foreach my $highest (sort hashValueAscendingNum(keys(%hash))) {
    print "\t $hash{$highestMagnitude} \t\t $highest \n";
}

I want all the values in the hash to be checked, and the one with maximum value should be returned with its key.
How can i do that?

A: You need to first associate each key with the highest of the values corresponding to it in the original %hash and then find the key associated with the highest value.
#!/usr/bin/env perl

use strict; use warnings;

use List::Util qw( max );

my  %hash = (
    bob => [ 4.9 ],
    gita => [ 3.9, 6.8 ],
    diu => [ 3.0 ],
);

my %max = map { $_ => max @{ $hash{$_} } } keys %hash;

my ($argmax) = (sort { $max{$b} <=> $max{$a} } keys %max)[0];
my $max = $max{ $argmax };

print join(' => ', $argmax, $max), "\n";

Of course, this is very inefficient (esp. using sort) but for the dimensions you showed, it does not matter. For completeness, here is a more efficient version using each:
#!/usr/bin/env perl

use strict; use warnings;

use List::Util qw( max );

my  %hash = (
    bob => [ 4.9 ],
    gita => [ 3.9, 6.8 ],
    diu => [ 3.0 ],
);

my ($argmax, $max) = @{ init_argmax_max(\%hash) };

while (my ($k, $v) = each %hash) {
    $v = max @{ $v };
    if ( $v > $max ) {
        $argmax = $k;
        $max = $v;
    }
}

print join(' => ', $argmax, $max), "\n";

sub init_argmax_max {
    my ($hash) = @_;
    my ($argmax, $max) = each %{ $hash };

    keys %{ $hash };

    $max = max @{ $max };

    return [$argmax, $max];
}

A: A hash has only a single key and a single value, and each key must be unique. In your original problem you have this:
%hash = (
   bob => "4.9",
   gita =>"3.9 , 6,8",
   diu => "3.0",
);

Well, gita can't have two values. Nor, can you have two keys in your hash equal to gita. Thus, you can't use a simple hash to store your values.
There are ways around this though by using references. For example, each element in your hash can contain a reference to an array. Thus, your data structure can look like this:
%hash = (
    bob =>  [(4.9)],
    gita => [(3.9, 6.8)],
    diu  => [(3.0)],
);

The [ and ] marks a reference to an array.
However, this wouldn't really solve your particular problem since you now have to go through each key in the hash, then each element in the array for each key, and sort those. You could create a sorting subroutine, but just because you can say sort doesn't make it efficient.
Maybe what you need is an array of arrays. This will get rid of the issue you have with gita having two values, but make sorting a bit easier. Imagine a structure like this:
my @array = (
    [bob  => 4.9],
    [gita => 3.9],
    [gita => 6.8],
    [diu  => 3.0],
);

Now, we can do a sort on @array depending upon the value of $array[$x]->[1]! All we need is for each element of the array @array is to compare $a->[1] with $b->[1]. Then, if we do a reverse sort on it, the biggest element will be $array[0]. The name is $array[0]->[0] and the element is $array->[0]->[1].
#! /usr/bin/env perl
use strict;
use warnings;
use feature qw(say switch);

my @array = (
    [bob  => 4.9],
    [gita => 3.9],
    [gita => 6.8],
    [diu  => 3.0],
);

@array = reverse sort mysort @array;

say "$array[0]->[0] $array[0]->[1]";

sub mysort {
    $a->[1] <=> $b->[1];
}

And the output is:
gita 6.8.

You notice that link to Perldoc's perllol? I suggest you read it if you've never worked with Perl references before.

A: #!/usr/bin/perl
use warnings;
use strict;

my %hash = (
    bob  => [ 4.9 ],
    gita => [ 3.9, 6.8 ],
    diu  => [ 3.0 ],
);

my $max_key;
my $max_val=0;

foreach my $key (keys %hash) {
    foreach my $val ( @{$hash{$key}} ) {
        ($max_key, $max_val) = ($key, $val)
            if $val > $max_val;
    }
}

print "$max_key => $max_val\n";

A: You got several good answers. Now a bad one (assuming you fix the decimal separator in the hash):
my %hash = (bob => "4.9",
            gita =>"3.9 , 6.8",
            diu => "3.0",
            );

my $max = (map{join" ",@$_[0,1]}sort{$b->[1]-$a->[1]}map{[$_,sort{$b-$a}split(/ , /,$hash{$_})]}keys%hash)[0];

print "$max\n";

Output:
gita 6.8

Never do this unless you're deliberately trying to golf and/or obfuscate it though.


text:
Q: Flutter AppBar Icon is not responsive on all screens i Have two icons on my appbar on clicking save save  icon dissappers and approve icon will pop it works fine but by app bar icon on larger screen cut according to below image. here is mycode
appBar: PreferredSize(
      preferredSize:  Size.fromHeight(70.0),
      child: AppBar(
      elevation: 10,
      automaticallyImplyLeading: false,
      backgroundColor: Colors.red,
        title:  Text('Edit',style:
              TextStyle(fontSize: MediaQuery.of(context).size.width*0.1),
        ),

        actions: <Widget>[
          isVisibile
              ?  Container(
            height: 50,
                width: 50,
                child: Padding(
                  padding:  EdgeInsets.only(right:MediaQuery.of(context).size.width*0.3),
                  child: IconButton(
                        icon:  Icon(
                            Icons.save,
                            color: Colors.white,
                            size: MediaQuery.of(context).size.width*0.1,
                          ),

                        onPressed: () {

                        },
                      ),
                ),
              )

              : Container(),
          isInvisible
              ? Padding(
                padding: EdgeInsets.only(right:MediaQuery.of(context).size.width*0.05,bottom: MediaQuery.of(context).size.height*0.05),
                child: IconButton(
                    icon: Icon(
                      Icons.done,
                      color: Colors.white,
                      size: MediaQuery.of(context).size.width*0.1,
                    ),
                    onPressed: () async {
                      // approve
                    },
                  ),
              )
              : Container(),
        ],
      //),
      ),
    ),

here is my app bar on large screens

here is my image on small screen

so how can i make icons responsive thanks

A: Put your AppBar widget as a child of Container and set margin to EdgeInset.all(4). This should work.
Try Following code :
appBar: PreferredSize(
      preferredSize:  Size.fromHeight(70.0),
      child: Container(
              padding: EdgeInset.all(4), // you can change this value to 8
            child:AppBar(
            ...


text:
Q: How can I make sure that the function inside 'for loop' gets executed before I send the response in NodeJS? I am using bluebird for this. I need to get this function i.e. get_like_status(email, results[i].id) which is at the end of the for loop to execute before I send the headers. I get it undefined when I console the array list. I would appreciate it enormously if you can do it using bluebird however I am open to any other packages for promises.
var list = new Array();
  console.log(results.length);
  function get_like_status(email, project_id){
    connection.query("SELECT email FROM likes WHERE liked_by='"+email+"' AND project_id='"+project_id+"';", function(err, results, fields){
      if(err){console.log(err); return(err)}else{
        if(results.length > 0){
          console.log("yes");
          return "yes";
        }else{
          console.log("yes");
          return "no";
        }
      }

    })
  }
  for(var i=0; i < results.length; i++){
    var empty = new Array();
    list.push(empty);
    list[i].push(results[i].email);
    list[i].push(results[i].project_name);
    list[i].push(results[i].project_description);
    list[i].push(results[i].header_image);
    list[i].push(results[i].id);
    list[i].push(get_like_status(email, results[i].id)); // This gets executed after the program has sent response!
  }
  Promise.all(list).then(function(){
    console.log(list);
    res.send(list); });

A: You have to refactor your code to actually wait for the promises, right now the list array is just a regular array with different values, it's not an array of promises waiting to be resolved.
Something similar to this
function get_like_status(email, project_id) {
    return new Promise(function( res, rej ) {
        var query = "SELECT email FROM likes WHERE liked_by='" +
                    email + "' AND project_id='" + project_id + "';"

        connection.query(query, function(err, results, fields) {
            if (err) {
                rej(err);
            } else {
                res( results.length > 0 ? "yes" : "no" );
            }
        });
    });
}

var promises = [];
var list = results.map(function(item, index) {
    var arr = [
        item.email,
        item.project_name,
        item.project_description,
        item.header_image,
        item.id
    ]
    promises.push(
        get_like_status(item.email, item.id).then(function(res) {
            arr.push(res);
            return arr;
        })
    );
})

Promise.all( promises ).then(function() {
    res.send(list);
}).catch(function( err ) {
    res.send('epic fail!')
})

Note that if connection.query returns a promise, there's no need to wrap it in another promise, it's just not clear where connection.query is coming from?


text:
Q: How to delete component of BOM (bill of material) in SAP I want to delete the component (raw material) of a BOM without making any changes in ABAP coding.
Please tell me know if we have any transaction for it.

A: I think you need to use transaction 'CS02'.
CS02 – Change Material BOM
SAP transaction CS02 (Change Material BOM) is classified in the Logistics – General module under application component Bills of Material and runs R/3 Application development: PP Bills of Material program SAPMC29S upon execution
Check this link.
Hope it helps.

A: You can use CS02 (Change BOM) T-code to delete the Component of the BOM (Bill Of Material), if you required to delete the multiple BOM Component use LSMW Script.


text:
Q: How do you set up a WordPress blog with multiple authors to allow something like StackExchange's "community wiki" feature? I'm thinking about having a blog with multiple authors. In the WordPress Roles documentation, authors can publish posts but only edit their own and not posts by other authors, which is what I'm looking for.
I also want to allow certain posts to become open for anybody to edit without upgrading anybody to 'Editor', similar to the community wiki feature here on the StackExchange sites.
Is this possible?

A: I believe your best bet is to create a custom post type for the certain posts you want editable by multiple authors.
When you register your post assign a capability type (#WIKI# in this example) and then add the 'edit_others_#WIKI#s' to the author role.


text:
Q: Skipping an item from being checked in where clause In the code below, in the WHERE clause, all the items are checked against that condition "bcp.value = cm.id". Hence if item has no value in bcp table it wont show up, how do i make it show up?
I have tried my best using the likes of sub query without success.
Please help
 SELECT DISTINCT
   u.firstname,
   u.lastname,
   u.id,
   c.shortname,
   c.fullname,
   cs.name AS 'Units Code/s Covered',
   m.name,

   MIN(FROM_UNIXTIME(cmc.timemodified)) AS 'Start Time',
   MAX(FROM_UNIXTIME(bgi.dateissued))AS 'Time Completed'

FROM
  mdl_course_modules_completion cmc

  LEFT JOIN mdl_course_modules cm
        ON (cmc.coursemoduleid =cm.id)

    LEFT JOIN mdl_course_sections cs
        ON (cs.id = cm .section)

    LEFT JOIN mdl_modules m
        ON (m.id= cm.module )

 LEFT JOIN mdl_course c
        ON c.id = cm.course AND c.shortname = 'DOM_2015_1'
LEFT JOIN mdl_user u
        ON u.id = cmc.userid AND (u.firstname = 'bambo' OR u.firstname = 'Test bambo')

LEFT JOIN mdl_badge_issued bgi
        ON bgi.userid = cmc.userid

LEFT JOIN mdl_badge bg
        ON bg.id = bgi.badgeid

LEFT JOIN mdl_badge_criteria bc
        ON bc.badgeid = bg.id

LEFT JOIN mdl_badge_criteria_param bcp
        ON bcp.critid = bc.id AND bcp.value = cm.id

GROUP BY u.firstname, cs.name, FROM_UNIXTIME(bgi.dateissued)

A: Try this:
AND (bcp.value is null or bcp.value = cm.id)

A: Just add OR Inside your Where Clause like this
WHERE c.shortname = 'DOM_2015_1' AND (bcp.value = cm.id OR bcp.value IS NULL)
or if it string bcp.value = ""
Update
Before to adding this in Where clause you have to get correct Join maybe it will be better use FULL OUTER JOIN or RIGHT JOIN(Is it possible? It depends on your logic) instead of using LEFT JOIN

A: WHERE conditions are being applied to entire resultset, thus discarding any of those rows from table mdl_course_modules_completion that don't meet this criteria.
If you only need to check for NULL value that could come from mdl_badge_criteria_param bcp table, then adding additional (or bcp.value is null) would suffice.
This is because your mdl_course_modules cm table is being joined to mdl_badge_criteria_param bcp, and not the main table. If we had the case of joining directly with the main table, making bcp independent from cm, query could sometimes yield wrong results, when cm.id would be holding NULL, and bcp.value was a non-null value.
Keeping that in mind, your solution would be
WHERE c.shortname = 'DOM_2015_1' AND ( bcp.value = cm.id OR bcp.value is null )

Edit You may also consider dropping the entire condition considering bcp.value = cm.id since it seems like you want to allow every record, that has a matching cm.id with the main table to appear and instead applying a cm.id is not null to your where condition.


text:
Q: Find value that is two characters different Can anyone help i have a spreadsheet that has item codes in the same column and i need to find an item code that is just two charscters diffetent to the first.
I.e. i know which row dftca0004 is and need to search for the row that contains dftea0004. Both item codes are in the same column.
Thanks in advance

A: When all the values are in the A Column and dtifca0004 is in cell A1, the following formula will return the rownumber of dtifea0004. This formula will work when the formats are ****c***** and ****e*****
=MATCH(REPLACE(A1,5,1,"e"),A:A)

A: thank you the replace function works perfectly this is the final formula
=+IF($T$3="","",VLOOKUP(REPLACE($T$3,4,1,"e"),'Barcode Register'!A:E,5,FALSE))


text:
Q: Oracle setup required for heavy-ish load I am trying to make a comparison between a system setup using Hadoop and HBase and achieving the same using Oracle DB as back end. I lack knowledge on the Oracle side of things so come to a fair comparison.
I am looking for what kind of Oracle setup is required to handle a certain work load (hardware, OS, software stack, etc.).
The work load and non-functional requirements are roughly this:

*

*12M transactions on two tables with one simple relation and multiple (non-text) indexes within 4 hours. That amounts to 833 transactions per second (TPS), sustained. This needs to be done every 8 hours.

*Make sure that all writes are durable (so a running transaction survives a machine failure in case of a clustered setup) and have a decent level of availability?
With a decent level of availability, I mean that regular failures such as disk and a single network interface / tcp connection drop should not require human intervention. Rare failures, may require intervention, but should be solved by just firing up a cold standby that can take over quickly.

*Additionally add another 300 TPS, but have these happen almost continuously 24/7 across many tables (but all in pairs of two with the same simple relation and multiple indexes)?
Some context: this workload is 24/7 and the system needs to hold 10 years worth of historical data available for live querying. Query performance can be a bit worse than sub-second, but must be lively enough to consider for day-to-day usage.
The ETL jobs are setup in such a way that there is little churn. Also in a relational setup, this workload would lead to little lock contention. I would expect index updates to be the major pain. To make a comparison as fair as possible, I would expect the loosest consistency level that Oracle provides.
I have no intention of bashing Oracle in favor of some non-relational DB solution. I think it is a great database for many uses. I am trying to get a feeling for the tradeoff there is between going open source (and NoSQL) like we do and using a commercially supported, proven setup.

A: Firstly, I will say that this workload is by no means heavy by Oracle standards; thousands of commits/sec are possible, easily. Secondly, however, what matters here is not your database and it's not your server: it's your storage. There are many options here; you won't go too wrong with something like NetApp (I don't work for them, just a satisfied user) and the question is, what size? Here ORION is your friend. Whatever storage array you choose, this will take care of your first level of resilience, if your first node fails you simply mount the disks on another and start back up again, and Oracle will perform crash recovery so no data will be lost.
My advice is, get some numbers at a lower level - MB/s, IOPs - by performing a representative benchmark and take those to your nearest storage vendor and ask them what they've got. With NetApp at least, you can start fairly small and grow, adding another head for more resilience/better performance, adding shelves for more capacity, etc etc. Then test the crap out of it with Orion!