text:
Q: Purpose of Explicit Default Constructors I recently noticed a class in C++0x that calls for an explicit default constructor.  However, I'm failing to come up with a scenario in which a default constructor can be called implicitly.  It seems like a rather pointless specifier.  I thought maybe it would disallow Class c; in favor of Class c = Class(); but that does not appear to be the case.
Some relevant quotes from the C++0x FCD, since it is easier for me to navigate [similar text exists in C++03, if not in the same places]

12.3.1.3 [class.conv.ctor]
A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or value initialization (8.5).

It goes on to provide an example of an explicit default constructor, but it simply mimics the example I provided above.

8.5.6 [decl.init]
To default-initialize an object of type T means:
— if T is a (possibly cv-qualified) class type (Clause 9), the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);
8.5.7 [decl.init]
To value-initialize an object of type T means:
— if T is a (possibly cv-qualified) class type (Clause 9) with a user-provided constructor (12.1), then the default constructor for T is called (and the initialization is ill-formed if T has no accessible default constructor);

In both cases, the standard calls for the default constructor to be called.  But that is what would happen if the default constructor were non-explicit.  For completeness sake:

8.5.11 [decl.init]
If no initializer is specified for an object, the object is default-initialized;

From what I can tell, this just leaves conversion from no data.  Which doesn't make sense.  The best I can come up with would be the following:
void function(Class c);
int main() {
  function(); //implicitly convert from no parameter to a single parameter
}

But obviously that isn't the way C++ handles default arguments.  What else is there that would make explicit Class(); behave differently from Class();?
The specific example that generated this question was std::function [20.8.14.2 func.wrap.func].  It requires several converting constructors, none of which are marked explicit, but the default constructor is.

A: Unless explicitly stated otherwise, all standard references below refers to N4659: March 2017 post-Kona working draft/C++17 DIS.

(This answer focus specifically on explicit default constructors which have no parameters)

Case #1 [C++11 through C++20]: Empty {} copy-list-initialization for non-aggregates prohibits use of explicit default constructors
As governed by [over.match.list]/1 [emphasis mine]:

When objects of non-aggregate class type T are list-initialized such
that [dcl.init.list] specifies that overload resolution is performed
according to the rules in this section, overload resolution selects
the constructor in two phases:

*

*(1.1) Initially, the candidate functions are the initializer-list constructors ([dcl.init.list]) of the class T and the argument list
consists of the initializer list as a single argument.

*(1.2) If no viable initializer-list constructor is found, overload resolution is performed again, where the candidate functions are all
the constructors of the class T and the argument list consists of
the elements of the initializer list.

If the initializer list has no elements and T has a default
constructor, the first phase is omitted. In
copy-list-initialization, if an explicit constructor is chosen, the
initialization is ill-formed. [ Note: This differs from other
situations ([over.match.ctor], [over.match.copy]), where only
converting constructors are considered for copy-initialization. This
restriction only applies if this initialization is part of the final
result of overload resolution.  — end note ]

copy-list-initialization with an empty braced-init-list {} for non-aggregates prohibits use of explicit default constructors; e.g.:
struct Foo {
    virtual void notAnAggregate() const {};
    explicit Foo() {}
};

void foo(Foo) {}

int main() {
    Foo f1{};    // OK: direct-list-initialization

    // Error: converting to 'Foo' from initializer
    // list would use explicit constructor 'Foo::Foo()'
    Foo f2 = {};
    foo({});
}

Albeit the standard quote above refers to C++17, this likewise applies for C++11, C++14 and C++20.

Case #2 [C++17 only]: A class type with a user-declared constructor that is marked as explicit is not an aggregate
[dcl.init.aggr]/1 added was updated some between C++14 and C++17, mainly by allowing an aggregate to derive publicly from a base class, with some restrictions, but also prohibiting explicit constructors for aggregates [emphasis mine]:

An aggregate is an array or a class with

*

*(1.1) no user-provided, explicit, or inherited constructors ([class.ctor]),

*(1.2) no private or protected non-static data members (Clause [class.access]),

*(1.3) no virtual functions, and

*(1.4) no virtual, private, or protected base classes ([class.mi]).

As of P1008R1 (Prohibit aggregates with user-declared constructors), which has been implemented for C++20, we may no longer ever declare constructors for aggregates. In C++17 alone, however, we had the peculiar rule that whether a user-declared (but not user-provided) constructor was marked explicit decided whether the class type was an aggregate or not. E.g. the class types
struct Foo {
    Foo() = default;
};

struct Bar {
    explicit Bar() = default;
};

were aggregates/not aggregates in C++11 through C++20 as follows:

*

*C++11: Foo & Bar are both aggregates

*C++14: Foo & Bar are both aggregates

*C++17: Only Foo is an aggregate (Bar has an explicit constructor)

*C++20: None of Foo or Bar are aggregates (both has user-declared constructors)

A: This declares an explicit default constructor:
struct A {
  explicit A(int a1 = 0);
};

A a = 0; /* not allowed */
A b; /* allowed */
A c(0); /* allowed */

In case there is no parameter, like in the following example, the explicit is redundant.
struct A {
  /* explicit is redundant. */
  explicit A();
};

In some C++0x draft (I believe it was n3035), it made a difference in the following way:
A a = {}; /* error! */
A b{}; /* alright */

void function(A a);
void f() { function({}); /* error! */ }

But in the FCD, they changed this (though, I suspect that they didn't have this particular reason in mind) in that all three cases value-initialize the respective object. Value-initialization doesn't do the overload-resolution dance and thus won't fail on explicit constructors.


text:
Q: Unable to connect to discovered orderer when node.js application is used to invoke chaincode I have deployed a simple Hyperledger network to AWS, using separate VM instances for an orderer, two peers, and their respective CAs. So I have one VM instance for the orderer, one instance for the orderer CA, and so on.
I am able to start the network, create a channel, and deploy the sample fabcar chaincode. I can also query and invoke the chaincode from inside any of the two peers just fine using peer chaincode query/invoke.
The problem I'm experiencing happens when I use a node.js application (that is outside of the network and is using the fabric-network module) to query or invoke the chaincode. I keep getting the following error:
error: [ServiceEndpoint]: Error: Failed to connect before the deadline on Committer- name: 172.31.42.206:7050, url:grpcs://172.31.42.206:7050, connected:false, connectAttempted:true
error: [ServiceEndpoint]: waitForReady - Failed to connect to remote gRPC server 172.31.42.206:7050 url:grpcs://172.31.42.206:7050 timeout:3000
error: [DiscoveryService]: _buildOrderer[channel1] - Unable to connect to the discovered orderer 172.31.42.206:7050 due to Error: Failed to connect before the deadline on Committer- name: 172.31.42.206:7050, url:grpcs://172.31.42.206:7050, connected:false, connectAttempted:true

When I query the chaincode, I get the above error, but I still get the query results. However, when I try to invoke, I get the error and the chaincode invocation does not go through.
My connection profile is as follows:
{
    "name": "test-network-org1",
    "version": "1.0.0",
    "client": {
        "organization": "Org1",
        "connection": {
            "timeout": {
                "peer": {
                    "endorser": "300"
                }
            }
        }
    },
    "organizations": {
        "Org1": {
            "mspid": "Org1MSP",
            "peers": [
                "peer0.org1.example.com"
            ],
            "certificateAuthorities": [
                "ca.org1.example.com"
            ]
        }
    },
    "peers": {
        "peer0.org1.example.com": {
            "url": "grpcs://peer0.org1.example.com:7051",
            "tlsCACerts": {
                "pem": "-----BEGIN CERTIFICATE-----...-----END CERTIFICATE-----\n"
            },
            "grpcOptions": {
                "ssl-target-name-override": "peer0.org1.example.com",
                "hostnameOverride": "peer0.org1.example.com"
            }
        }
    },
    "certificateAuthorities": {
        "ca.org1.example.com": {
            "url": "https://ca.org1.example.com:7054",
            "caName": "ca-org1",
            "tlsCACerts": {
                "pem": ["-----BEGIN CERTIFICATE-----...-----END CERTIFICATE-----\n"]
            },
            "httpOptions": {
                "verify": false
            }
        }
    }
}

In the node.js application, I have discovery.enabled set to True and discovery.asLocalhost set to False. I have also added the IP addresses of each VM to the /etc/hosts of the machine running the node.js application.
Is there something else that needs to be done or some setting that needs to be changed so that the application can connect to the discovered orderer? Any help is appreciated.

redpajama_set_name: RedPajamaStackExchange


text:
Q: execute bash files when previous ones have finished to run Hello I would need help
In fact I need to execute several bash files ex:
file1.sh
file2.sh
file3.sh
file4.sh

those file will generate data that will be used for another bash file call final.sh
So in order to gain time I want to execute the fileNb.sh  files sumultany on a cluster by doing :
for file in file*.sh; do sbatch $file; done
, and then when all job have been done, I would like to execute automatically the final.sh file.
Does someone have an idea ?
Thank you very much

A: One clean option is to reorganise the set of jobs as a job array and then add a dependency for final job on the whole array.
Assuming fileN.sh looks like this:
#!/bin/bash
#SBATCH --<some option>
#SBATCH --<some other option>

./my_program input_fileN

you can make this a job array. In a single submission file file.sh, write this
#!/bin/bash
#SBATCH --<some option>
#SBATCH --<some other option>
#SBATCH --array=1-4

./my_program input_file${SLURM_ARRAY_TASK_ID}

Then run
JOBID=$(sbatch --parsable file.sh)
sbatch --dependency after:$JOBID final.sh

In case your jobs cannot be parametrised by an integer directly, create a Bash array like this:
#!/bin/bash
#SBATCH --<some option>
#SBATCH --<some other option>
#SBATCH --array=0-2

ARGS=(SRR63563 SRR63564 SRR63565)

fasterq-dump --threads 10  ${ARGS[$SLURM_ARRAY_TASK_ID]} -O /path1/path2/path3/

A: You could do:
sbatch --wait file1.sh &
sbatch --wait file2.sh &
sbatch --wait file3.sh &
sbatch --wait file4.sh &
wait
sbatch final.sh

Or, more simply with GNU Parallel:
parallel -j4 sbatch --wait ::: file*.sh
sbatch final.sh

A: Is this no good?
for file in file*.sh; do sbatch $file; done; ./final.sh


text:
Q: Prove that domain is consist of only two points. Prove that f(x)=sin$^{-1}$$\frac{1+x^{2}}{2x}$ - $\frac{\Pi}{2}sec(x-1)$
contains only twpo points in domain namely{-1,1}.
I tried but i could not do this.

A: contains only twpo points in domai ,because $$\frac{1+x^2}{2x}=\frac{1}{x}+\frac{x^2}{2x}=\frac{1}{2}(x+\frac1x) \\\text {we know } |x+\frac 1x|\geq 2 \\\to |\frac{1}{2}(x+\frac1x)|\geq \frac{2}{2}=1 \\\frac{1+x^2}{2x} \in (-\infty,-1]\cup [1,\infty)$$ and $$D_{\sin ^{-1} u}=[-1,1]$$now $$[-1,1] \cap \left(  (-\infty,-1]\cup [1,\infty)\right)=\{1,-1\}$$


text:
Q: Install Web2py in virtual hosting Install Web2py by a script setup-web2py-ubuntu.sh, previously adjusted the way for their virtual hosting.
But it works only on port 443, and the 80 th issue

It works!

How to fix?
#NameVirtualHost *:80
#NameVirtualHost *:443
# If the WSGIDaemonProcess directive is specified outside of all virtual
# host containers, any WSGI application can be delegated to be run within
# that daemon process group.
# If the WSGIDaemonProcess directive is specified
# within a virtual host container, only WSGI applications associated with
# virtual hosts with the same server name as that virtual host can be
# delegated to that set of daemon processes.
WSGIDaemonProcess demo2.host.ru user=web2 group=client1

<VirtualHost *:80>
  WSGIProcessGroup demo2.host.ru
  WSGIScriptAlias / /var/www/clients/client1/web2/web/web2py/wsgihandler.py
  WSGIPassAuthorization On

  <Directory /var/www/clients/client1/web2/web/web2py>
    AllowOverride None
    Order Allow,Deny
    Deny from all
    <Files wsgihandler.py>
      Allow from all
    </Files>
  </Directory>

  AliasMatch ^/([^/]+)/static/(.*) \
        /var/www/clients/client1/web2/web/web2py/applications/$1/static/$2

  <Directory /var/www/clients/client1/web2/web/web2py/applications/*/static/>
    Options -Indexes
    Order Allow,Deny
    Allow from all
  </Directory>

  <Location /admin>
  Deny from all
  </Location>

  <LocationMatch ^/([^/]+)/appadmin>
  Deny from all
  </LocationMatch>

  CustomLog /var/log/apache2/access.log common
  ErrorLog /var/log/apache2/error.log
</VirtualHost>

<VirtualHost *:443>
  SSLEngine on
  SSLCertificateFile /usr/local/ispconfig/interface/ssl/ispserver.crt
  SSLCertificateKeyFile /usr/local/ispconfig/interface/ssl/ispserver.key
WSGIProcessGroup demo2.host.ru
  WSGIScriptAlias / /var/www/clients/client1/web2/web/web2py/wsgihandler.py
  WSGIPassAuthorization On

  <Directory /var/www/clients/client1/web2/web/web2py>
    AllowOverride None
    Order Allow,Deny
    Deny from all
    <Files wsgihandler.py>
      Allow from all
    </Files>
  </Directory>

  AliasMatch ^/([^/]+)/static/(.*) \
        /var/www/clients/client1/web2/web/web2py/applications/$1/static/$2

  <Directory /var/www/clients/client1/web2/web/web2py/applications/*/static/>
    Options -Indexes
    ExpiresActive On
    ExpiresDefault "access plus 1 hour"
    Order Allow,Deny
    Allow from all
  </Directory>

  CustomLog /var/log/apache2/access.log common
  ErrorLog /var/log/apache2/error.log
</VirtualHost>

Create files: parameters_443.py and parameters_80.py in folder web2py.
password="pbkdf2(1000,20,sha512)$851a015489"

Still not working...
Plz help! :'(


text:
Q: PHP Front Controller implementation without singleton : conceptual question i have a "conceptual" question about Front controller implementation in php.
Most of the Front Controllers i have seen around are implemented with Singleton, i am not a big fan of singleton pattern and i created a Container which has a static property that will store a unic instance of Front Controller.
With singleton, i had to put initialization code inside the constructor (or a method called by the constructor):
$fc = FrontController::getInstance();

With the container i could put configuration outside the FrontController, that was my goal and i still have a simple way to retrieve the FrontController.
$fc = Container->getFrontController();

This code looks much cleaner to me and i can get clean subclassing without caring about parent constructors.
That's quite the same thing at 'bootstrap' time, but in practice the difference from my previous implementation is that now i can create FrontControllers anywhere in the application (inside a DAO or inside a Action), because the constructor is no longer private/protected.
My question is:
   Is it a 'bad practice' to give to the user of my classes the possibility to create       FrontController instances anywhere in the app? I would write documentation and deliver the container with other classes, but i still wonder if i should prevent strange uses.

A: $fc = Container::getFrontController();

sounds Ok for me.
I don't think it would be a bad practice to allow developers to retrieve the Front Controller instance anywhere, if you control correctly what developers can do with it (e.g. do not overwrite some property or execute its methods in a wrong order without showing an error/warning to the user).

A: Is there any real reason to create FrontController instances inside the app? If there is then go ahead. Otherwise I am a bit skeptical about this as it may complicate things later on. What I'm afraid of is someone using new FrontController instances when there is a much simpler way, either out of laziness or because they don't know any better. Once they find something that works, some people tend to keep doing it even if there's a better way. Never forget that you may have to work with people that are not as good as you.
Personally I would hide this or not allow it altogether. However I would keep it in mind for later releases. If you ever stumble on a case where it's the best option by all means add it to your "official" interface.
Don't forget that once you release a function into the wild, it's excruciatingly difficult to kill it off.


text:
Q: Termination of python thread waiting on queue or working I have N worker threads, they all read from a single queue.SimpleQueue where the main program writes tasks to perform. When a thread gets a message from the queue, its task can last for some minutes. So if the main program is interrupted (eg by CTRL-C or SIGINT) it could be a long time before all threads terminate. However I'd like the program to terminate within a few seconds.
The task that a thread performs can be interrupted however, meaning that the thread can periodically check a flag or event variable to see whether it must terminate.
So I've come up with the following mix of sentinel messages and event variables to do the trick:
import queue
import threading

# worker thread
def worker_loop(work_queue, thread_id, event):

  while True:
    end = False
    item = work_queue.get()
    # work_queue.task_done()   # not needed for SImpleQueue

    if item is None:
      print("Thread %s: terminating due to sentinel" % thread_id)
      end = True
    else:
      # perform task, periodically checking for event
      for part in range(10):
        print("Thread %s: doing job part %s (item %s)" % (thread_id, part, item))
        do_work(part = part)                # this lasts a few seconds
        result = event.wait(timeout = 0.01)
        if result == True:
          print("Thread %s: terminating due to event" % thread_id)
          end = True
          break

    if end:
      return

# main
WORKERS = 5
THREADS = []

work_queue = queue.SimpleQueue()
event = threading.Event()

for thread_id in range(WORKERS):
  print("[Main] creating thread '%s'" % thread_id)
  t = threading.Thread(target = worker_loop, args = (work_queue, thread_id, event))
  THREADS.append(t)
  t.start()

# main code here...
# ...

# we received a signal, the time has come to terminate all threads...

# kill threads waiting on the queue
for i in range(NUM_THREADS):
  work_queue.put(None)

# signal other threads to terminate ASAP
event.set()

# wait for all threads to terminate
for thread_id in range(NUM_THREADS):
  THREADS[thread_id].join()

sys.exit()

My question is: is this method safe? It looks to me as if it is, but I figured I'd better check. Are there better/more elegant alternatives?


text:
Q: Catch event emitted from *class* constructor Is it possible to catch event emitted from class constructor? The problem is that it fires before handler is attached. Class code in CoffeeScript:
class YtVideo extends events.EventEmitter
    constructor: ->
            events.EventEmitter.call this
            # logic
            @emit 'error', 'Invalid YouTube link.'

Example:
ytVideo = new YtVideo

ytVideo.on 'error', (e) -> # This doesn't work for events from constructor.
    alert e

A: The simple answer is that, as you have seen, can you cannot fire 'error' synchronously in the constructor because you will not have had time to bind an error event handler yet.
Given that, you have two options:
1. Throw and catch a normal exception
throw 'Invalid YouTube link.'

and
try
  ytVideo = new YtVideo
catch e
  alert e

2. Delay the error event so you have time to bind the error listener
process.nextTick =>
  @emit 'error', 'Invalid YouTube link.'


text:
Q: For a given set of pairings in the 8-team basketball tournament,in how many ways can the top 3 positions in the final standings be filled? The top 2 teams must be from different brackets.
I couldn't understand the question.In the initial competition,8 teams are separated into 4 groups(with 2 teams each) to compete.And it will give 4 winner teams.But how can we choose the top 3 from 4?

A: You have a single elimination tournament. Presumably the listing of teams is given.  In a standard tournament if the teams are seeded, we have 1 vs 8, 2 vs 7, 3 vs 6 and 4 vs 5 in the first round.  Even if they are not seeded, we can use those names for the teams.  Then in the second round we have the 1-8 winner play the 4-5 winner and the 2-7 winner play the 3-6 winner and in the third round we have the final.  Then the third place team is decided by playing the second round losers.
You have eight choices for the champion.  Given the champion, how many choices are there for the loser of the final?  Given the first and second place teams, how many choices are there for third?


text:
Q: How search in multiple directories start.bat
@echo off
CALL bat.bat "C:\Users\admin\Documents\test 2,C:\Users\admin\Documents\test 1" "*.xml *.txt *.html" "D:\Work\bat\batLog.txt"

bat.bat
for %%G  in (%1) do (
echo %%~G
    pushd "%%G"
    If Exist "%%G" (
    for /R  %%H in ("%2") do (
if %%~zH LSS %3 (
>>"%4" (
        echo %%~H
        echo %%~tH
for /f "tokens=* delims=," %%i in ('type "%%~H"') do (
echo %%i
))) popd)))

pause
exit/b

why does not it go to the next directory? Echo only test 2

A: This is now a complete rewrite using your new code.  This should get you closer to what you want to do.  Hopefully I fixed all the other errors with your program.  I purposely indent my code so that I can see where a code block begins and ends. Much easier to see and understand how the code is working.
start.bat
@echo off
call bat.bat "C:\Users\admin\Documents\test 2,C:\Users\admin\Documents\test 1" "*.xml *.txt *.html" "20000" "D:\Work\bat\batLog.txt"

bat.bat
@echo off
REM %1 = List of Folders
REM %2 = List of file masks
REM %3 = File Size for comparison
REM %4 = Log File

set "folders=%1"
set "folders=%folders:,=","%"

for %%G in (%folders%) do (
    echo %%~G
    If Exist "%%~G" (
        pushd "%%~G"
        for /R %%H in (%~2) do (
            if %%~zH LSS %~3 (
                >>"%~4" (
                    echo %%~H
                    echo %%~tH
                    for /f "tokens=* delims=," %%I in ('type "%%~H"') do (
                        echo %%~I
                    )
                )
            )
        )
        popd
    )
)

pause
exit/b


text:
Q: Best Practices for Testing Application Dashboard Data We have a dashboard that contains metrics based on a 6 month reporting period.  Users log in and see their metrics based on the current 6-month reporting period.
Every 6 months, we load new metrics in our DEV/QA environment and configure them for the upcoming reporting period so we can test. But, our application and ETL use GETDATE(), so for the ETL to calculate properly, we have been setting the server's DATE in the future so everything will calculate and display as if we were in the future.

Our DBA group is now telling us that this should not be done and no
  one else in the industry does this.  Can someone give me some examples
  of what they have done for testing in this situation?  Should we be
  looking to re-design our ETL and application and what are some ideas
  for best practices?

We have unit testing for the application, so it will work.  We are more worried that the data from the ETL will not be correct on Day 1 of the new period.  It is very important that the metrics are displaying properly and the data is correct on Day 1.

A: I would not use GetDate() for this fixed-period scenario as the end date for queries, because the reports are only meningful for specific periods.
A better approach is to use a specific run-date for each reporting period. That run-date is not the current date.
For example, let's say one of your KPIs is the sales amount for the first 6 months of 2013. Your system should use end of June as the end date not the current run-date regardless of when the report is run. If you do this, you'd not have to touch the data.

A: DBAs have learned through hard experience that Murphy's Law should be applied to all situations - Anything that can go wrong, will go wrong. It is definitely unreasonable for you to expect the DBAs to tinker with the environments in strange ways to save you the difficulty of making your application work in a more flexible way. There is also no reason why the system would produce different outputs depending on if the date is gathered from a GetDate or from a user input, as long as the values are the same. Unless you have left some key information out here, your worries are unfounded and your DBAs are right to take a stand on this situation.


text:
Q: Dismiss a View Controller with a UIAlertAction I'm trying to present a log out alert. When the user taps on Yes, I want my view controller to dismiss with a method that can provide me a completion handler.
The view controller is inside a navigation controller and is the second one on the stack.
I came up with the following code:
@IBAction func logOut() {
        let logOutAlert = UIAlertController.init(title: "Log out", message: "Are you sure ?", preferredStyle:.Alert)

        logOutAlert.addAction(UIAlertAction.init(title: "Yes", style: .Default) { (UIAlertAction) -> Void in
            //Present entry view ==> NOT EXECUTED
            self.dismissViewControllerAnimated(true, completion:nil)
        })

        logOutAlert.addAction(UIAlertAction.init(title: "Cancel", style: .Cancel, handler: nil))

        self.presentViewController(logOutAlert, animated: true, completion: nil)
}

The line self.dismissViewControllerAnimated(true, completion:nil) is read but it doesn't do anything.

A: I suspect that dismissViewControllerAnimated doesn't do anything for you because the view controller isn't presented modally, but shown by way of a navigation controller. To dismiss is, you can tell the navigation controller to pop it from the stack, like so:
    logOutAlert.addAction(UIAlertAction.init(title: "Yes", style: .Default) { (UIAlertAction) -> Void in
        self.navigationController?.popViewControllerAnimated(true)
        })

Unfortunately, popViewControllerAnimated doesn't seem to provide a way to attach your own completion handler out of the box. If you require one, you could still add one by utilising the associated CATransaction, which could look something like this:
    logOutAlert.addAction(UIAlertAction.init(title: "Yes", style: .Default) { (UIAlertAction) -> Void in
        CATransaction.begin()
        CATransaction.setCompletionBlock(/* YOUR BLOCK GOES HERE */)
        self.navigationController?.popViewControllerAnimated(true)
        CATransaction.commit()
        })


text:
Q: Running S3-put-triggered Lambda function on existing S3 objects? I have a Lambda function in Node.js that processes new images added to my bucket. I want to run the function for all existing objects. How can I do this? I figured the easiest way is to "re-put" each object, to trigger the function, but I'm not sure how to do this.
To be clear - I want to run, one-time, on each of the existing objects. The trigger is already working for new objects, I just need to run it on the objects that were inserted before the lambda function was created.

A: The following Lambda function will do what you require.
It will iterate through each file in your target S3 bucket and for each it will execute the desired lambda function against it emulating a put operation.
You're probably going to want to put a very long execution time allowance against this function
var TARGET_BUCKET="my-bucket-goes-here";
var TARGET_LAMBDA_FUNCTION_NAME="TestFunct";
var S3_PUT_SIMULATION_PARAMS={
  "Records": [
    {
      "eventVersion": "2.0",
      "eventTime": "1970-01-01T00:00:00.000Z",
      "requestParameters": {
        "sourceIPAddress": "127.0.0.1"
      },
      "s3": {
        "configurationId": "testConfigRule",
        "object": {
          "eTag": "0123456789abcdef0123456789abcdef",
          "sequencer": "0A1B2C3D4E5F678901",
          "key": "HappyFace.jpg",
          "size": 1024
        },
        "bucket": {
          "arn": "arn:aws:s3:::mybucket",
          "name": "sourcebucket",
          "ownerIdentity": {
            "principalId": "EXAMPLE"
          }
        },
        "s3SchemaVersion": "1.0"
      },
      "responseElements": {
        "x-amz-id-2": "EXAMPLE123/5678abcdefghijklambdaisawesome/mnopqrstuvwxyzABCDEFGH",
        "x-amz-request-id": "EXAMPLE123456789"
      },
      "awsRegion": "us-east-1",
      "eventName": "ObjectCreated:Put",
      "userIdentity": {
        "principalId": "EXAMPLE"
      },
      "eventSource": "aws:s3"
    }
  ]
};

var aws = require('aws-sdk');
var s3 = new aws.S3();
var lambda = new aws.Lambda();

exports.handler = (event, context, callback) => {
    retrieveS3BucketContents(TARGET_BUCKET, function(s3Objects){
        simulateS3PutOperation(TARGET_BUCKET, s3Objects, simulateS3PutOperation, function(){
            console.log("complete.");
        });
    });
};

function retrieveS3BucketContents(bucket, callback){
    s3.listObjectsV2({
        Bucket: TARGET_BUCKET
    }, function(err, data) {
        callback(data.Contents);
    });
}

function simulateS3PutOperation(bucket, s3ObjectStack, callback, callbackEmpty){
    var params = {
      FunctionName: TARGET_LAMBDA_FUNCTION_NAME,
      Payload: ""
    };

    if(s3ObjectStack.length > 0){
        var s3Obj = s3ObjectStack.pop();
        var p = S3_PUT_SIMULATION_PARAMS;
        p.Records[0].s3.bucket.name = bucket;
        p.Records[0].s3.object.key = s3Obj.Key;
        params.Payload = JSON.stringify(p, null, 2);
        lambda.invoke(params, function(err, data) {
          if (err) console.log(err, err.stack); // an error occurred
          else{
              callback(bucket, s3ObjectStack, callback, callbackEmpty);
          }
        });
    }
    else{
        callbackEmpty();
    }
}

Below is the full policy that your lambda query will need to execute this method, it allows R/W to CloudWatch logs and ListObject access to S3. You need to fill in your bucket details where you see MY-BUCKET-GOES-HERE
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "Stmt1477382207000",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::MY-BUCKET-GOES-HERE/*"
            ]
        },
        {
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup",
        "logs:CreateLogStream",
        "logs:PutLogEvents"
      ],
      "Resource": "arn:aws:logs:*:*:*"
    }
    ]
}

A: This thread helped push me in the right direction as I needed to invoke a lambda function per file for an existing 50k files in two buckets. I decided to write it in python and limit the amount of lambda functions running simultaneously to 500 (the concurrency limit for many aws regions is 1000).
The script creates a worker pool of 500 threads who feed off a queue of bucket keys. Each worker waits for their lambda to be finished before picking up another. Since the execution of this script against my 50k files will take a couple hours, I'm just running it off my local machine. Hope this helps someone!
#!/usr/bin/env python

# Proper imports
import json
import time
import base64
from queue import Queue
from threading import Thread
from argh import dispatch_command

import boto3
from boto.s3.connection import S3Connection

client = boto3.client('lambda')

def invoke_lambdas():
    try:
        # replace these with your access keys
        s3 = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
        buckets = [s3.get_bucket('bucket-one'), s3.get_bucket('bucket-two')]

        queue = Queue()
        num_threads = 500

        # create a worker pool
        for i in range(num_threads):
            worker = Thread(target=invoke, args=(queue,))
            worker.setDaemon(True)
            worker.start()

        for bucket in buckets:
            for key in bucket.list():
                queue.put((bucket.name, key.key))

        queue.join()

    except Exception as e:
        print(e)

def invoke(queue):
    while True:
        bucket_key = queue.get()

        try:
            print('Invoking lambda with bucket %s key %s. Remaining to process: %d'
                % (bucket_key[0], bucket_key[1], queue.qsize()))
            trigger_event = {
                'Records': [{
                    's3': {
                        'bucket': {
                            'name': bucket_key[0]
                        },
                        'object': {
                            'key': bucket_key[1]
                        }
                    }
                }]
            }

            # replace lambda_function_name with the actual name
            # InvocationType='RequestResponse' means it will wait until the lambda fn is complete
            response = client.invoke(
                FunctionName='lambda_function_name',
                InvocationType='RequestResponse',
                LogType='None',
                ClientContext=base64.b64encode(json.dumps({}).encode()).decode(),
                Payload=json.dumps(trigger_event).encode()
            )
            if response['StatusCode'] != 200:
                print(response)

        except Exception as e:
            print(e)
            print('Exception during invoke_lambda')

        queue.task_done()

if __name__ == '__main__':
    dispatch_command(invoke_lambdas)

A: As I had to do this on a very large bucket, and lambda functions have a max. execution time of 10 minutes, I ended up doing a script with the Ruby AWS-SDK.
require 'aws-sdk-v1'

class LambdaS3Invoker

  BUCKET_NAME = "HERE_YOUR_BUCKET"
  FUNCTION_NAME = "HERE_YOUR_FUNCTION_NAME"
  AWS_KEY = "HERE_YOUR_AWS_KEY"
  AWS_SECRET = "HERE_YOUR_AWS_SECRET"
  REGION = "HERE_YOUR_REGION"

  def execute
    bucket.objects({ prefix: 'products'}).each do |o|
      lambda_invoke(o.key)
    end
  end

  private

  def lambda_invoke(key)
    lambda.invoke({
      function_name: FUNCTION_NAME,
      invocation_type: 'Event',
      payload: JSON.generate({
        Records: [{
          s3: {
            object: {
              key: key,
            },
            bucket: {
              name: BUCKET_NAME,
            }
          }
        }]
      })
    })
  end

  def lambda
    @lambda ||= Aws::Lambda::Client.new(
      region: REGION,
      access_key_id: AWS_KEY,
      secret_access_key: AWS_SECRET
    )
  end

  def resource
    @resource ||= Aws::S3::Resource.new(
      access_key_id: AWS_KEY,
      secret_access_key: AWS_SECRET
    )
  end

  def bucket
    @bucket ||= resource.bucket(BUCKET_NAME)
  end
end

And then you can call it like:
LambdaS3Invoker.new.execute

A: What you need to do is create a one time script which uses AWS SDK to invoke your lambda function. This solution doesn't require you to "re-put" the object.
I am going to base my answer on AWS JS SDK.

To be clear - I want to run, one-time, on each of the existing
  objects. The trigger is already working for new objects, I just need
  to run it on the objects that were inserted before the lambda function
  was created.

As you have a working lambda function which accepts S3 put events what you need to do is find all the unprocessed object in S3 (If you have DB entries for each S3 object the above should be easy if not then you might find the S3 list  object function handy http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#listObjectsV2-property).
Then for each unprocessed S3 object obtained create a JSON object which looks like S3 Put Event Message(shown below) and call the Lambda invoke function with the above JSON object as payload.
You can find the lambda invoke function docs at http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/Lambda.html#invoke-property
When creating the fake S3 Put Event Message Object for your lambda function you can ignore most of the actual object properties depending on your lambda function. I guess the least you will have to set is bucket name and object key.
S3 Put Event Message Structure http://docs.aws.amazon.com/AmazonS3/latest/dev/notification-content-structure.html
{
   "Records":[
      {
         "eventVersion":"2.0",
         "eventSource":"aws:s3",
         "awsRegion":"us-east-1",
         "eventTime":"1970-01-01T00:00:00.000Z",
         "eventName":"ObjectCreated:Put",
         "userIdentity":{
            "principalId":"AIDAJDPLRKLG7UEXAMPLE"
         },
         "requestParameters":{
            "sourceIPAddress":"127.0.0.1"
         },
         "responseElements":{
            "x-amz-request-id":"C3D13FE58DE4C810",
            "x-amz-id-2":"FMyUVURIY8/IgAtTv8xRjskZQpcIZ9KG4V5Wp6S7S/JRWeUWerMUE5JgHvANOjpD"
         },
         "s3":{
            "s3SchemaVersion":"1.0",
            "configurationId":"testConfigRule",
            "bucket":{
               "name":"mybucket",
               "ownerIdentity":{
                  "principalId":"A3NL1KOZZKExample"
               },
               "arn":"arn:aws:s3:::mybucket"
            },
            "object":{
               "key":"HappyFace.jpg",
               "size":1024,
               "eTag":"d41d8cd98f00b204e9800998ecf8427e",
               "versionId":"096fKKXTRTtl3on89fVO.nfljtsv6qko",
               "sequencer":"0055AED6DCD90281E5"
            }
         }
      }
   ]
}

A: well basically what you need is to use some api calls(boto for example if you use python)and list all new objects or all objects in your s3 bucket and then process these objects
here is a snippet:
from boto.s3.connection import S3Connection

conn = S3Connection()
source = conn.get_bucket(src_bucket)
src_list = set([key.name for key in source.get_all_keys(headers=None, prefix=prefix)])
//and then you can go over this src list
for entry in src_list:
   do something


text:
Q: Transform offsets input border in Chrome I was making a webpage and I needed to horizontally and vertically align a div with an input, in the center of the page. But when I tested the code it rendered something I didn't expect.

body {
  background: white;
  margin: 0;
  padding: 0;
  font-family: Source Sans Pro;
  line-height: 160%;
}

div {
  position: absolute;
  background: #E6E6E6;
  padding: 15px;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  -webkit-transform: translate(-50%, -50%);
}

<input />

I tested it in Chrome and Firefox, but this bug only happens in Chrome. Is there a reason for this, and how do I fix it?

A: The input element is, by default, styled with an inset value:

Try this instead:

input { border: 1px solid gray; }

body {
  background: white;
  margin: 0;
  padding: 0;
  font-family: Source Sans Pro;
  line-height: 160%;
}

div {
  position: absolute;
  background: #E6E6E6;
  padding: 15px;
  left: 50%;
  top: 50%;
   -webkit-transform: translate(-50%, -50%);
   transform: translate(-50%, -50%);
}

<input />


text:
Q: Conservation of Energy For Electrostatics
Starting from Newton's second law, I am trying to show that energy is not conserved with an applied external force when moving a positive charge from $r_b$ to $r_a$ (see image). I'm not sure where I'm missing a minus sign? Also shouldn't the work done by the external force increase the total energy so that $E_a = W_F + E_b$ ?

A: You need to double check the directions of your quantities. Let's say that the $\hat r$ unit vector points to the upper right. Using this convention, the external work and the kinetic energy stay the same. The electrical force is given by
$$\vec F_E=\frac{qq_0}{4\pi \epsilon_0 r^2}\hat r$$
The resulting equation in its most general form is then
$$\vec F+\vec F_E=m\frac{d\vec v}{dt}=m\vec v \cdot \frac{d\vec v}{dr}$$
$$\int_{\vec r_b}^{\vec r_a} \vec F\cdot d\vec r=-\int_{\vec r_b}^{\vec r_a}\vec F_E\cdot d\vec r+\int_{\vec v_b}^{\vec v_a}m\vec v\cdot d\vec v$$
By definition,
$$U(\vec r)=-\int_\infty^{\vec r}\vec F_E\cdot d\vec r$$
Hence,
$$-\int_{\vec r_b}^{\vec r_a}\vec F_E\cdot d\vec r=-\int_\infty^{\vec r_b}\vec F_E\cdot d\vec r + \int_\infty^{\vec r_a} \vec F_E\cdot d\vec r=U(\vec r_b)-U(\vec r_a)$$
Therefore,
$$A'=U(\vec r_a)-U(\vec r_b)+K(\vec r_a)-K(\vec r_b)$$
as you did suspect.

A: As you have suspected it is a matter of signs.
As an example of what you have done wrong look at your integral $\displaystyle \int_{r_{\rm b}}^{r_{\rm a}}F\,dr = F(r_{\rm a} - r_{\rm b})$.
Since $r_{\rm a} < r_{\rm b}$ this integral gives a negative value and yet the displacement of the force is in the same direction as the force!
I have annotated your derivation.

Charge $q$ is the origin of your coordinate system and with your statement that the net force is $F-F_{\rm E}$ you have defined the positive direction as in the $7$ o'clock direction.
What that means is that your starting point is at $r=-r_{\rm b}$ and your finishing point is $r=-r_{\rm a}$ as shown on the diagram above.
This assumes that you intended $r_{\rm a}$ and $r_{\rm b}$ to be positive quantities?
So now the work done by force $F$ is $\displaystyle \int_{-r_{\rm b}}^{-r_{\rm a}}F\,dr = F(r_{\rm b} - r_{\rm a})$, positive as expected.
The same change of sign will also occur for the electric potential energy terms and then you will find that the work done by force $F$ is equal to the change in kinetic energy plus the change in electric potential energy.
Perhaps you would have found it easier to choose the positive direction towards $1$ o'clock with the net force $F_{\rm E} -F$ and moving the charge from $+r_{\rm b}$ to $+r_{\rm a}$?

I have shown you how that might be done below.
System - Charge $Q_{\rm 0}$ alone
There are two external forces acting on the charge $\vec F_{\rm E}$ and $\vec F$.
You now need to consider a positive direction which can be $\hat r$ pointing roughly towards one o'clock.
This is the first place that you must be careful.
From your diagram $\vec F_{\rm E}=\dfrac{qq_0}{4\pi \epsilon_0 r^2}(\hat r)$ where $\dfrac{qq_0}{4\pi \epsilon_0 r^2}$ is a positive quantity and $\vec F = F(-\hat r)$ with $F$ chosen by you as being positive.
In moving from $\vec r_{\rm b} = r_{\rm b} (\hat r)$ to $\vec r_{\rm a}=r_{\rm a} (\hat r)$ the work done by the two forces is $\displaystyle \int_{r_{\rm b}}^{r_{\rm a}}(\vec F_{\rm E}+ \vec F)\cdot d\vec r$ where $d\vec r = dr\, \hat r$ with the sign of the component of the displacement $dr$ completely defined by the limits of integration.
This point is explained in the answer to the post Why does this line integral give the wrong sign?.
So the work done by the two external forces is
$\displaystyle \int_{r_{\rm b}}^{r_{\rm a}}(\vec F_{\rm E}+ \vec F)\cdot d\vec r=\displaystyle \int_{r_{\rm b}}^{r_{\rm a}}(F_{\rm E}(\hat r)+ F(-\hat r))\cdot dr(\hat r) =\displaystyle \int_{r_{\rm b}}^{r_{\rm a}}(F_{\rm E} -F)dr =\dfrac{qq_0}{4\pi \epsilon_0 r_{\rm a}}-\dfrac{qq_0}{4\pi \epsilon_0 r_{\rm b}}+F(r_{\rm b} - r_{\rm a})$
and this is equal to the change in the kinetic energy of the system (charge $q_0$).
From your derivation you have have chosen a different system as you cannot define a potential energy for a system consisting of a single particle/charge.
System - Charge $Q_{\rm 0}$ and charge $q$.
The assumption is then made that charge $q$ does not move / moves very little compared with charge $q_0$, ie the mass of $q$ is much greater than the mass of $q_0$.
Now there is only one external force $\vec F$ and two internal forces, the force on charge $q$ due to charge $q_0$ and its Newton third law pair, the force on charge $q_0$ due to charge $q$.
Because $q$ does not move the derivation is essentially the same and the work done by the external force is So the work done by the two external forces is $F(r_{\rm b} - r_{\rm a})$ with the change in electric potential energy being $\dfrac{qq_0}{4\pi \epsilon_0 r_{\rm a}}-\dfrac{qq_0}{4\pi \epsilon_0 r_{\rm b}} = U(r_{\rm a})-U(r_{\rm b})$ and the change in kinetic energy being $K_{\rm a}-K_{\rm b}$.
Bringing everything together gives $K_{\rm a}-K_{\rm b} = F(r_{\rm b} - r_{\rm a}) - (U(r_{\rm a})-U(r_{\rm b}))$.
If the work done by the external force, $F(r_{\rm b} - r_{\rm a})$, is greater than the increase in the electric potential energy of the system, $U(r_{\rm a})-U(r_{\rm b})$, the kinetic energy of the system increases.


text:
Q: Algorithm to get "adjacent" values of a list with subsets I have a text file like this:
A
B
C

And each element has a subset like this:
A = { a1, a2, a3 }
B = { b1, b2 }
C = { c1, c2, c3 }

I want to generate this:

    a1, b1, c1
    a2, b1, c1
    a3, b1, c1
    a1, b2, c1
    a1, b1, c2
    a1, b1, c3

I don't know the number of elements in the text file (e.g. could be: A, B, C, D, E) and the subsets could vary in size.
All I can think it's a recursive function with 2 indexes, maybe "position in the array" and "index of the array", but I really don't know how to implement all of this.
I even tried to adapt a function that does cartesian product with the same inputs, but I totally failed. I don't need to generate Cartesian product.

A: Build the "base list", which is comprised of the first element of every list.  Then loop through all the elements of all of the lists.  For each such element, update the base list at the appropriate position with that element, and add this updated list to a running tally of lists.
I've included an example implementation below.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class AdjacentListGenerator {
    public static <T> List<List<T>> generateAdjacentLists(List<List<T>> lists) {
        List<List<T>> result = new ArrayList<List<T>>();
        List<T> baseList = new ArrayList<T>();

        // Generate the base list, which is comprised of all the first elements
        for (List<T> list : lists) {
            baseList.add(list.get(0));
        }
        result.add(baseList);

        // Loop over each list, and for each element beyond the first, make a
        // copy of the base list, update that element in place, and add it to
        // our result
        for (int list_i = 0; list_i < lists.size(); list_i++) {
            List<T> list = lists.get(list_i);
            for (int listElement_i = 1; listElement_i < list.size(); listElement_i++) {
                List<T> updatedList = new ArrayList<T>(baseList);
                updatedList.set(list_i, list.get(listElement_i));
                result.add(updatedList);
            }
        }

        return result;
    }

    public static void main(String... args) {
        List<String> a = Arrays.asList(new String[] { "a1", "a2", "a3" });
        List<String> b = Arrays.asList(new String[] { "b1", "b2" });
        List<String> c = Arrays.asList(new String[] { "c1", "c2", "c3" });
        List<List<String>> lists = new ArrayList<List<String>>();
        lists.add(a);
        lists.add(b);
        lists.add(c);
        for (List<String> list : AdjacentListGenerator
                .generateAdjacentLists(lists)) {
            System.out.println(list);
        }
    }
}

Output
[a1, b1, c1]
[a2, b1, c1]
[a3, b1, c1]
[a1, b2, c1]
[a1, b1, c2]
[a1, b1, c3]

A: List<List<Integer>> myInput = ...

for(int i=0; i<myInput.size(); i++){
     for (int j=0; j<myInput.get(i).size(); j++){
        if (j == 0 && i > 0){
           continue;
        }
        List<Integer> result = new ArrayList<Integer>(myInput.size());
        for(int k=0; k<myInput.size(); k++){
            if (k == i){
               result.add(myInput.get(k).get(j));
            }else{
               result.add(myInput.get(k).get(0));
            }
        }
        System.out.println(result);
     }
}

Loop through all the lists where the index is the list to be iterated.
Find the size of the inner List to be iterated and loop that many time.
Loop through the lists always getting the first element unless the list is the list being indexed, in which case get the next value from the iteration list.

A: Everyone is using Containers so I will try to solve it only with arrays.
In this algorithm I just print 1st line then I'm focusing on surrounding next elements of subsets by first elements of rest subsets
String[] lines = { "a1, a2, a3", "b1, b2", "c1, c2, c3" };

String[][] array = new String[lines.length][];
for (int i = 0; i < lines.length; i++)
    array[i] = lines[i].replaceAll(" +", "").split(",");

//lets type 1st row to ignore it in rest algoritm
System.out.print(array[0][0]);
for (int i = 1; i < array.length; i++)
    System.out.print(", " + array[i][0]);
System.out.println();

//in rest of algorithm we must surround each element by
//1st element or rest rows, so lets iterate over each row
for (int row = 0; row < array.length; row++)
    //and surround its elements
    for (int col = 1; col < array[row].length; col++) {
        //left surround
        int i=0;
        for (; i<row; i++)
            System.out.print(array[i][0]+", ");
        //
        System.out.print(array[row][col]);
        //right surround
        for (i=i+1; i<array.length; i++)
            System.out.print(", "+array[i][0]);
        System.out.println();
    }

A: My answer assumes you have already sorted your datasets and they're in the correct order.
public class SubsetPrinter
{
  private static final String DELIMITER = ", ";
  private static final String NEWLINE = System.getProperty("line.separator");

  public static String printSubsets(Map<String, List<String>> elements)
  {
    List<String> lines = new ArrayList<String>();
    for (Map.Entry<String, List<String>> entry : elements.entrySet())
    {
      for (String sub : entry.getValue())
      {
        String line = getLine(elements, entry.getKey(), sub);
        if (!lines.contains(line))
        {
          lines.add(line);
        }
      }
    }
    return asString(lines);
  }

  private static String getLine(Map<String, List<String>> elements, String element, String sub)
  {
    StringBuilder line = null;
    for (Map.Entry<String, List<String>> entry : elements.entrySet())
    {
      if (line == null)
      {
        line = new StringBuilder();
      }
      else
      {
        line.append(DELIMITER);
      }
      if (entry.getKey().equals(element))
      {
        line.append(sub);
      }
      else
      {
        line.append(entry.getValue().get(0)); // appends the first
      }
    }
    return line.toString();
  }

  private static String asString(List<String> lines)
  {
    StringBuilder sb = null;
    for (String line : lines)
    {
      if (sb == null)
      {
        sb = new StringBuilder();
      }
      else
      {
        sb.append(NEWLINE);
      }
      sb.append(line);
    }
    return sb.toString();
  }
}

And the test being:
private Map<String, List<String>> getDataSet1()
{
  Map<String, List<String>> map = new HashMap<String, List<String>>();
  List<String> subsetA = Arrays.asList( new String[] { "a1", "a2", "a3" } );
  List<String> subsetB = Arrays.asList( new String[] { "b1", "b2" } );
  List<String> subsetC = Arrays.asList( new String[] { "c1", "c2", "c3" } );
  map.put("A", subsetA);
  map.put("B", subsetB);
  map.put("C", subsetC);
  return map;
}

@Test
public void testPrintSubsets()
{
  Map<String, List<String>> elements = getDataSet1();
  String output = SubsetPrinter.printSubsets(elements);
  System.out.println(output);
}

Output:
a1, b1, c1
a2, b1, c1
a3, b1, c1
a1, b2, c1
a1, b1, c2
a1, b1, c3

A: Formalizing your problem :
This can be mapped to multi-stage graphs.Just googled for a diagrammatic illustration  online of mult-stage graphs :  What you are trying to do is print all the paths from the super-source 'S' to the super sink 'T'. You might want to read up on the same. This is also related to the Network Flow problem,if you are interested further.


text:
Q: How to centre an iFrame on a specific aspect of the HTML document? Have created an iframe and wish to centre it on a specific area of the HTML document? E.g iframe of website, want to centre it on left hand side of the website.

A: You can not specifying "center" or "left", but try this example and adapt to your situation :
<div style="overflow: hidden; margin: 15px auto; max-width: 736px;">
    <iframe scrolling="no" src="yourURL" style="border: 0px none; margin-left: -185px; height: 859px; margin-top: -533px; width: 926px;"/>
</div>

Example from dimpost.com


text:
Q: What is the territorial extent of the New Republic & the Galactic Empire after Endor? In the Disney canon wiki page of the New Republic, it is described that following the Battle of Jakku, the Empire was militarily exhausted and forced into signing a peace treaty with the Republic. Imperial forces thereafter stayed within the borders defined in the treaty. This indicates that the Galactic Empire and New Republic likely coexisted for an extended period - until the Empire probably fractured with infighting, eventually leading to the rise of the First Order to be seen in The Force Awakens.
As of the ratification of this peace treaty, what are the established territories and borders of the two galactic governments, as far as what is known to us - named worlds, sectors etc.? Are there areas of the galaxy that fall outside both governments, and how much of these "neutral space" were formerly controlled by Palpatine's Empire and how much were neutral since before the Empire? Please answer strictly within Disney canon.


text:
Q: SASS error: can't import Compass I've been using sass and compass on this computer for a few months with no issues.
Additionally, my config.rb and sass directories have always been set up the same way, and they're the same on all of my projects.
Recently, I started getting this error in Sublime when I build the sass: Sass::SyntaxError: File to import not found or unreadable: compass.
The first line of my .scss file is @import "compass";, so I see this error in Terminal: error sass/style.scss (Line 36 of _vertical_rhythm.scss: Incompatible units: 'px' and 'em'.)
I've been searching for days, and I see answers around some of this stuff (the vertical-rhythm specifically), but nothing is my exact problem, and I can't find a solution.
My compass version is 0.12.5 (Alnilam), and my sass version is 3.3.4 (Maptastic Maple).
At work, everything compiles fine with the exact same files, working from the exact same GitHub repo. I need to check my versions of compass and sass at work tomorrow, but in the meantime, I'm stumped.
Any ideas? Has this happened to anyone?

A: After a month of troubleshooting, the solution ended up being simpler than expected.
I uninstalled all versions of both Sass and Compass, and then I installed the latest Compass and let it install Sass automatically.
So after doing sudo gem uninstall compass and sudo gem uninstall sass, I did sudo gem install compass. That installed both Compass and its dependencies (Sass version 3.2.19). (I'm on a Mac, so I had to use sudo.)
Solved!

A: if this is on mac:
Go to:
/var/folders/p_/w19t0k956zz_bg0bgs0cn6200000gn/T/liferay
and delete following folders:
document_preview document_thumbnail ruby


text:
Q: How to resolve the Blurness issue in print Preview of UWP? I am familiar with the data grid in the UWP plat form. we tried to provide the support for printing the results in  sheets. we have faced the hurdles while we print the content. In the print preview panel the content looks like blurry to the view, but in the printed sheet the contents look like normal. could your share your ideas to resolve this.
Thanks in advance for your updates.

A: It seems it is by design.
In UWP, we use the PrintManager to inform Windows that an application wishes to participate in printing.
When we run the ShowPrintUIAsync() method, it will run the "PrintDialog.exe" that the print Preview page will be shown.
We can use the "Inspect" to test the content of the print Preview page. From the following image, we can see the content is a Image control that render by the XAML.

For the performance, it does not render as clear as the printting result. We can not change that.
If you do want this feature, you are welcome to ask on UserVoice.


text:
Q: SQLite not recognizing column names I downloaded the ColDP archive from https://www.catalogueoflife.org/data/download and imported NameUsage.tsv into an SQLite table. I think the table has about 2 million rows.
Creating the table:
.mode tabs
.import NameUsage.tsv name_usage

The table schema
sqlite> .schema name_usage
CREATE TABLE IF NOT EXISTS "name_usage"(
  "col:ID   col:alternativeID   col:nameAlternativeID   col:sourceID    col:parentID    col:basionymID  col:status  col:scientificName  col:authorship  col:rank    col:notho   col:uninomial   col:genericName col:infragenericEpithet col:specificEpithet col:infraspecificEpithet    col:cultivarEpithet col:namePhrase  col:nameReferenceID col:publishedInYear col:publishedInPage col:publishedInPageLink col:code    col:nameStatus  col:accordingToID   col:accordingToPage col:accordingToPageLink col:referenceID col:scrutinizer col:scrutinizerID   col:scrutinizerDate col:extinct col:temporalRangeStart  col:temporalRangeEnd    col:environment col:species col:section col:subgenus    col:genus   col:subtribe    col:tribe   col:subfamilycol:family col:superfamily col:suborder    col:order   col:subclass    col:class   col:subphylum   col:phylum  col:kingdom col:sequenceIndex   col:branchLength    col:link    col:nameRemarks col:remarks" TEXT
);

It looks as if the table that has been created has got one very long column which consists of what should be all the separate column names. The type of that column has been set as TEXT.
I would quite like to get rid of the col: prefixes on all the names and also I would like to choose what type the different columns are. If there were less rows I might just edit it in vim and then create the table but the combination of not knowing exactly what the best approach is and the large number of rows makes me feel it would be better to get some advice on the best approach to getting this data into an SQLite table.
Edit:
First few lines of NameUsage.tsv
col:ID  col:alternativeID       col:nameAlternativeID   col:sourceID    col:parentID    col:basionymID  col:status      col:scientificName      col:authorship  col:rank        col:notho       col:uninomial   col:genericName col:infragenericEpithet col:specificEpithet     col:infraspecificEpithet        col:cultivarEpithet     col:namePhrase  col:nameReferenceID     col:publishedInYear     col:publishedInPage     col:publishedInPageLink col:code        col:nameStatus  col:accordingToID       col:accordingToPage     col:accordingToPageLink col:referenceID col:scrutinizer col:scrutinizerID       col:scrutinizerDate     col:extinct     col:temporalRangeStart  col:temporalRangeEnd    col:environment col:species     col:section     col:subgenus    col:genus       col:subtribe    col:tribe       col:subfamily   col:family      col:superfamily col:suborder    col:order       col:subclass    col:class       col:subphylum   col:phylum      col:kingdom     col:sequenceIndex       col:branchLength        col:link        col:nameRemarks col:remarks
5T6MX                                           accepted        Biota           unranked                Biota                                                                                acceptable                                      CoL
5SY                             HP              accepted        Velocipedoidea          superfamily             Velocipedoidea
3FD8

Edit:
head -3 NameUsage.tsv | cat -A
col:ID^Icol:alternativeID^Icol:nameAlternativeID^Icol:sourceID^Icol:parentID^Icol:basionymID^Icol:status^Icol:scientificName^Icol:authorship^Icol:rank^Icol:notho^Icol:uninomial^Icol:genericName^Icol:infragenericEpithet^Icol:specificEpithet^Icol:infraspecificEpithet^Icol:cultivarEpithet^Icol:namePhrase^Icol:nameReferenceID^Icol:publishedInYear^Icol:publishedInPage^Icol:publishedInPageLink^Icol:code^Icol:nameStatus^Icol:accordingToID^Icol:accordingToPage^Icol:accordingToPageLink^Icol:referenceID^Icol:scrutinizer^Icol:scrutinizerID^Icol:scrutinizerDate^Icol:extinct^Icol:temporalRangeStart^Icol:temporalRangeEnd^Icol:environment^Icol:species^Icol:section^Icol:subgenus^Icol:genus^Icol:subtribe^Icol:tribe^Icol:subfamily^Icol:family^Icol:superfamily^Icol:suborder^Icol:order^Icol:subclass^Icol:class^Icol:subphylum^Icol:phylum^Icol:kingdom^Icol:sequenceIndex^Icol:branchLength^Icol:link^Icol:nameRemarks^Icol:remarks$
5T6MX^I^I^I^I^I^Iaccepted^IBiota^I^Iunranked^I^IBiota^I^I^I^I^I^I^I^I^I^I^I^Iacceptable^I^I^I^I^ICoL^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I$
5SY^I^I^I^IHP^I^Iaccepted^IVelocipedoidea^I^Isuperfamily^I^IVelocipedoidea^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I^I$

A: Make shure your TSV file contains a header with the correct names of the columns. Also, check if the fields are properly separated by tabs, not spaces.
In your case, the fields contains a "col:" prefix, so when sqlite parse the first row as the header, it use these names. Regarding creating a single TEXT column, perhaps the fields are separated by spaces and not tabs.
Other option is to first create your table:
create table name_usage (
  ID int,
  alternativeID  int,
  ...
);

Although the import does it automatically, you won't be able to choose column's types (they'll probably be loaded as TEXT).
Then you can do the import in the same way:
.mode tabs
.import NameUsage.tsv name_usage

Or setting tab as separator:
.separator "\t"
.import NameUsage.tsv name_usage

Note that in the second option, sqlite will still use csv-style rules for interpreting quotation marks, which probably isn't what you want. Therefore, the first option is recommended.


text:
Q: PHP mbstring loaded in cli but not in web I am trying to install phpMyAdmin on a CentOs 6 system with lighttpd and php 5.3.3. The problem is that the mbstring module is not loaded. I checked the /etc/php.d/mbstring.ini file and the line is not commented. Also added the line from this file to the php.ini. Still not loading. phpinfo() also does not show that it includes the mbstring.ini file. But when I run php -i it is included and mbstring loaded.
phpinfo():
Additional .ini files parsed    /etc/php.d/curl.ini, /etc/php.d/fileinfo.ini, /etc/php.d/json.ini, /etc/php.d/lighttpd.ini, /etc/php.d/mysql.ini, /etc/php.d/mysqli.ini, /etc/php.d/pdo.ini, /etc/php.d/pdo_mysql.ini, /etc/php.d/pdo_sqlite.ini, /etc/php.d/phar.ini, /etc/php.d/sqlite3.ini, /etc/php.d/zip.ini

php -i :
Additional .ini files parsed => /etc/php.d/bcmath.ini,
/etc/php.d/curl.ini,
/etc/php.d/dom.ini,
/etc/php.d/fileinfo.ini,
/etc/php.d/gd.ini,
/etc/php.d/json.ini,
/etc/php.d/lighttpd.ini,
/etc/php.d/mbstring.ini,
/etc/php.d/mcrypt.ini,
/etc/php.d/mysql.ini,
/etc/php.d/mysqli.ini,
/etc/php.d/pdo.ini,
/etc/php.d/pdo_mysql.ini,
/etc/php.d/pdo_sqlite.ini,
/etc/php.d/phar.ini,
/etc/php.d/sqlite3.ini,
/etc/php.d/tidy.ini,
/etc/php.d/wddx.ini,
/etc/php.d/xmlreader.ini,
/etc/php.d/xmlwriter.ini,
/etc/php.d/xsl.ini,
/etc/php.d/zip.ini

A: Really silly I just had to restart the server it works perfectly now.


text: Q: Stage duplication in case of dual issue pipeline I understand that in a dual-issue pipeline, the processor is capable of sustaining two executions in a single clock cycle. Talking in terms of pipeline organization (Fetch, Decode, Execute and Write), which part gets duplicated leading to the dual issue?


text:
Q: Setting build configuration to staging Simple question. How do I set the build configuration to something other than Debug?
Setting /P:Configuration=Staging in the Command line parameters box, leads to this error:
TeamCity says to use "Build Parameters" instead of "/property:" in an MSBuild step. What does that mean?
So how is it done? I need to build MSDeploy packages for all configurations, I can get the packages to build but everything is Debug.

A: The way you're doing it is fine -- although perhaps use a lowercase /p:. Our team does it this way too. TeamCity isn't throwing an error, it's just trying to provide some helpful information.
JetBrains provides some documentation for its preferred method at the bottom of the page under Using System Properties in Build Scripts.


text:
Q: Facebook js sdk iPhone login I'm trying to login on my website with Facebook JS API from my iPhone. The login works fine on computer as well as iPad.
Here's the login screen:

On iPhone however, I get to a screen which looks like this:

When I close the Facebook screen with the "Back to previous page" message and reload the login page, I'm logged in successfully. It looks like the problem is, that iPhone is unable to close the login pop-up screen.
Here's my JavaScript code:

Forbind med Facebook

How can I fix this problem?

A: Checkout this URL,
please do the settings as mentioned in the above URL, this code is working in mobile devices.

  <title>My Facebook Login Page</title>

<button onClick="loginUser();">Login</button>

<button  onClick="FB.logout();">Logout</button>

A: I have the exact same problem. This may (or may not) be an open Facebook bug: https://developers.facebook.com/bugs/280811108698311


text:
Q: Use parallel port on lattepanda gpio pins using unity I am trying to build a Unity project to get some data from GPIO pins which are included on LattePanda Delta. I set the connections and tried to build it as serial connection with arduino and everything is working fine. I have a button with 3 axes and i can get -1,0,1 outputs with 9600 baud rate using arduino serial port connection. I did that for testing. My cables are connected on Arduino GPIO pins on LattePanda. Now the point is i am trying to get datas in Unity. First thing to do is defining GPIO controllers and reading pins. I made research and i figured out System.Device.Gpio nuget should be used. I also installed the Iot.Device.Bindings on Unity project solution.
I am trying to create a script and add a definition like
using System.Device.Gpio but when i am trying to do that, i am typing "System." than Device option is not disappearing. If it would, i was gonna define gpio as GpioController and than gonna create a pin with my GPIO Pin inputs. Here is the example code, the "** using .... **" section is not recognized by Visual Studio. How can i do it? My platform is UWP(to be able to use windows iot core). And also trying to understand what will be the output of "var output = pin.Read();" because it should give me something like "High" or "Low" OR "1" or "0". But i tried to define output variable as boolean, it is not a boolean. If i can fix the using System.Device.Gpio issue first, than i'm gonna take care of it.
In this code i am trying to read Pin-3 because one of my button's input action is connected to pin-3. For now, did not care other 2 actions.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
**using System.Device.Gpio;**

public class communication : MonoBehaviour
{
    void Start()
    {
        GpioController gpio = GpioController.GetDefault();

    }

    void Update()
    {
        using (GpioPin pin = gpio.OpenPin(3))
        {

            pin.SetDriveMode(GpioPinDriveMode.Output);
            var output = pin.Read();
            if(output==1){
            // do something
            }else{
            // do something
        }

        }

    }
}

A: I'm not familiar with the LattePanda Delta, but from what I could gather it runs full Windows, and not an IoT version of Windows. As such, I think you may want to use this library which will let you interface with the board in full Windows: https://github.com/LattePandaTeam/LattePanda-Development-Support/tree/master/LattePandaFirmata

"LattePanda.Firmata is an open-source Firmata library provided by LattePanda, which is suitable for Windows apps developed in Visual Studio. this class allows you to control the Arduino board from Windows apps..."

That GitHub project looks like it is made by the LattePanda team.
So instead of using the System.Device.Gpio, you would install their code and have something like this:
using LattePanda.Firmata;

...

Arduino arduino = new Arduino();

arduino.pinMode(12, Arduino.OUTPUT);
arduino.pinMode(13, Arduino.OUTPUT);

var digitalOutput = arduino.digitalRead(12);
var analogOutput = arduino.analogRead(13);

I have no immediate way to test the above, so the code probably isn't quite right, but hopefully you get the idea.


text:
Q: Is there something akin to SetupGetSequence in Moq In Moq, I know that there is SetupSequence for setting sequential usage of a function and there is SetupGet for setting a value for a property.
However I need to set a property in a sequential way.
Is there a way for setting up sequential get in Moq?
Note: I did not write the interface or the service which I am mocking, therefore I cannot change it.

A: Sequencing return values with SetupSequence works for property getters as well :
mock.SetupSequence(m => m.PropertyName).Returns(1).Returns(2).Returns(3);

Note: you can use Setup instead of SetupGet, because Moq checks whether the body of given lambda expression is a property and calls SetupGet internally [Source Code]. So the only benefit you have is skipping this internal check.


text:
Q: Do I need any Rules Engine to build a service like ifttt.com ( if this then that )? I'm trying to build a web service like ifttt.com .
Because I find that more than a half of the channels provided by ifttt is not available in China. So I decide to make a local one.

I'm learning the Logs of ifttt trying to understand the process of how ifttt dealing with tasks.

Now I know that I must have some method to deal with the rules.
A scheduled task process can be activated by a specified event and then a engine resolve rules to call specified actions, passing parameters.
I'm planing to use Java to develop this.
And do you think I should use any open source Rules Engine here, or it's better to write one by myself? It will be great if you provide some hints about what I should be care for writing the rules engine or defining the structure of rules.
Finally, welcome free discussions about what technology do you think ifttt might be using. Or what the Database Structure of ifttt might be like. Or.. any point about ifttt or Rules Engine or Scheduled Tasks will be helpful!

A: I like drools or JBoss Rules, although it's the only one I've ever used. Anything you can distill down to a spreadsheet is especially cool.
My vote would be that if you can make a spreadsheet out of it, there is nothing better than this.
Debugging the rules is a pain in the butt. I hope its gotten better.


text:
Q: Getting Blood Glucose from HealthKit Query I am trying to pull blood glucose values from a query I have made to get the last 10 in the Health App. I am able to pull the data from the Health app and get it in the form for a single entry:
(2017-02-21 13:13:00 -0500 - 2017-02-21 13:13:00 -0500), 80 mg/dL 52D7A973-7853-455C-9308-0E339153A3BE "Health" (10.2.1) metadata: {
HKWasUserEntered = 1;}

I am able to pull the startdate (and endDate) from this by adding:
guard let timing = reading?.endDate as Date? else {
                print("timing scheme didn't work.")
                return
            }

print(timing)

and pull the type (HKQuantityTypeIdentifierBloodGlucose) by writing
guard let bg = reading?.sampleType as HKSampleType? else {
                print("bg scheme didn't work")
                return
            }

print(bg)

However, I can not figure out to print the actual blood glucose value (ie. 80 mg/dL).
I tried:
let bg = reading.quantity

but I got the error
Value of type 'Optional<HKSample>' has no member 'quantity'

If anyone has insight to this, it would be extremely helpful! Thank you in advance!

A: // To read blood glucose:
            let gluco = reading as? HKQuantitySample
            if let bg = gluco?.quantity {
                print(bg)
            }


text:
Q: Send Form Data as PDF attachment through Sendgrid I want to submit a form's data as a PDF attachment through Sendgrid.
The flow is as it follows:

*

*A customer fills a form on a webpage.

*Press a submit button.

*A PDF is generated through FDPF.

*An email is sent to me, through SendGrid, with some text and the generated PDF as an attachment.
Here is some of the code:
<?php

if(isset($_POST['sendemail']))
{

    require('fpdf/fpdf.php');
    $title = 'Inscrição';
    $name = $_POST['name'];
    $email_id = $_POST['email'];
    $age = $_POST['age'];
    $aulas = $_POST['aulas'];
    $experience = $_POST['experiencia-dança'];
    $conhecimento = $_POST['conhecimento'];
    $comentario = $_POST['comentario'];

(...)
    $pdf = new FPDF();
    $pdf -> AddPage();
    $pdf->SetTitle($title);

(...)
   $pdf->Output();

(...)
   $sendgrid = new \SendGrid($API_KEY);
   $email = new \SendGrid\Mail\Mail();
   $email->setFrom("********@gmail.com", "***** SAMA");
   $email->setSubject("Email de teste");
   $email->addTo("*****@gmail.com", "****SAMA");
   $email->addContent("text/plain", $comentario);

   If($sendgrid->send($email));
        {
            $msg = "Obrigado pelo seu contacto!";
        }

With this code, I can send the email, but no attachment is coming.
The problem is when I add the following lines of code, the email stop being sent to my inbox:
    $attachment = $pdf;
    $file_encoded = base64_encode(file_get_contents($attachment));
    $email->addAttachment(
    $file_encoded,
    "application/text",
    "test.pdf",
    "attachment"
    );

Can somebody please help me with this?
Best regards

A: Resolved the problem with this lines of code:
$pdfdoc = $pdf->Output("pdf.pdf", "S");

$att1 = new \SendGrid\Mail\Attachment();
$att1->setContent($pdfdoc);
$att1->setType("application/octet-stream");
$att1->setFilename(basename("pdf.pdf"));
$att1->setDisposition("attachment");
$email->addAttachment($att1);


text:
Q: Solve the inequality $x^2+y^2 \geq\frac{1}{x+y}+2(x-y -1).$ For which real values  $x,y$ does the inequality $x^2+y^2 \geq\frac{1}{x+y}+2(x-y -1)$  hold?
I have found for $x=\dfrac{1}{10}, y=\dfrac{3}{10}$  that  LHS=RHS  but cant solve it in the general case.   Here is 3d-plot

A: The rational cubic
$$(x+y)(x^2+y^2)-1-2(x+y)(x-y-1)=0\tag{1}$$
splits $\mathbb{R}^2$ in two parts, corresponding to the values for which the inequality holds or not.
The support of such a cubic is quite close to the line $(x+y)=0$:
$\hspace2in$
It is birationally equivalent to the elliptic curve $4v^3+4u^2v-1=0$ with discriminant $-1456$.


text:
Q: I want to select a date in access select date from table1 where date <=(select Format(date,'mm/##/yyyy') as dates from table 2).
This query returns "02/##/2011".
I want to make a list like "02/02/2011","02/03/2011" etc.

A: I think the problem is with your query, if its a query. change your query by putt star (*) instead of hash(#).


text:
Q: What is the use of clothing in candy box the first game? I have acquired a few pieces of clothing and I have no idea of their uses. I would like to know them if they have any. I have the hat, the boots, and the amulet. I don't know if they can help me in any way shape or form.

A: You can find all inventory items description on the wiki.

*

*The hat allows you to purchase the Imp Invocation scroll and the Earthquake scroll

*The boots increase your speed during quests

*The amulet will multiply by three your candies production

*The ring makes you recover 2x as fast after a quest

*The armor protects you for 3 hp per hit
All the items you find in the game are helpful.


text:
Q: Unable to extract data from json using python I have the following code so far. The code manages to read the JSON file in python.  However, I am not sure how I can extract the instrument name, bid, and ask prices into their respective dictionaries. Need some help in storing the values into the dictionaries. Also, the instrument name consists of 4 parts.  For example BTC-31JUL20-9250-P.  I would want to split them making it into stable like of format where I can see the ask and bid price together too.
import json
import requests

def get_spot_price():
    url = 'https://www.deribit.com/api/v2/public/get_index?currency=BTC'
    data = requests.get(url).json()
    global btc_price
    btc_price = data['result'].get('BTC')
    print(btc_price)

def get_call_run():

    instrument = {}
    bid_price = {}
    ask_price = {}

    url = 'https://www.deribit.com/api/v2/public/get_book_summary_by_currency?currency=BTC&kind=option'
    data = requests.get(url).json()
    print(data)

get_spot_price()
get_call_run()

A: The data is already in JSON format and converted to a dictionary for you. If you look at the result of second call you will find a dictionary ready for you, it has a result key which is a list of python dictionaries each one has the keys you want here is the code to print them all and split the instrument name
instrument = []
bid_price = []
ask_price = []

url = 'https://www.deribit.com/api/v2/public/get_book_summary_by_currency?currency=BTC&kind=option'
data = requests.get(url).json()
results = data["result"]
for result in results:
    instrument.append(result["instrument_name"].split("-"))
    bid_price.append(result["bid_price"])
    ask_price.append(result["ask_price"])


text:
Q: Kubernetes Ingress Whitelist IP for host How can I whitelist IP addresses for different hosts, but for the same path?
example.com - should be without whitelist. All others must be whitelisted.
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  annotations:
    kubernetes.io/ingress.class: nginx
spec:
  rules:
  - host: login.example.com
    http:
      paths:
      - backend:
          serviceName: login
          servicePort: 4444
        path: /
  - host: admin.example.com
    http:
      paths:
      - backend:
          serviceName: admin
          servicePort: 3333
        path: /
  - host: api.example.com
    http:
      paths:
      - backend:
          serviceName: api
          servicePort: 2222
        path: /
  - host: example.com
    http:
      paths:
      - backend:
          serviceName: wp
          servicePort: 1111
        path: /

A: annotations:
    nginx.ingress.kubernetes.io/whitelist-source-range: "1.1.1.1/24"

A: Basically @ANISH gave you a good idea about  nginx.ingress.kubernetes.io/whitelist-source-range, where you can start.

You can specify allowed client IP source ranges through the
  nginx.ingress.kubernetes.io/whitelist-source-range annotation. The
  value is a comma separated list of CIDRs, e.g. 10.0.0.0/24,172.10.0.1.
To configure this setting globally for all Ingress rules, the
  whitelist-source-range value may be set in the NGINX ConfigMap.

However, if you dont want to apply it to all your ingress rules - just create 2 separate ingresses. 1 for whitelisted hosts and second for your example.com host


text:
Q: Connecting data from an array to an object to transform its value with a middleman What would be the best way to use queued_Dr to alter its values like upcoming_appointments.PCD by using all_appointments?
What would be the best approach to this problem?
var queued_Dr = ["Dr.Salazar","Dr.Connors","Dr.Johnson","Dr.Pearson"]

upcoming_appointments =
[{"DOB":"01-27-2002","name":"Judy, W." ,"PCD":"Dr-S"}
    ,{"DOB":"08-15-1995","name":"John, V." ,"PCD":"Dr-C"}
    ,{"DOB":"07-05-1992","name":"David, C.","PCD":"Dr-S"}
    ,{"DOB":"01-15-2002","name":"Anna, S." ,"PCD":"Dr-J"}
    ,{"DOB":"01-15-2002","name":"Jeff, D." ,"PCD":"Dr-P"}]

all_appointments =
[["Dr-S","New York","Dr.Salazar"],
 ["Dr-C","Austin","Dr.Connors"],
 ["Dr-J","Austin","Dr.Johnson"],
 ["Dr-S","New York","Dr.Salazar"],
 ["Dr-P","San Juan","Dr.Pearson"],
 ["Dr-J","Austin","Dr.Johnson"]]

Input:
queued_Dr = ["Dr.Salazar","Dr.Connors","Dr.Johnson","Dr.Pearson"]

Desired Output:
queued_Dr = ["Dr-S","Dr-C","Dr-J","Dr-P"]

Actual Output:
[ undefined, undefined, undefined, undefined ]

Attempt
const mapTo = (arrayWithNames) => {
  var newArray = [];
  return arrayWithNames.map(name => {
    const appointment = Object.values(all_appointments)
      .find(appointment => appointment[2] === name);
      newArray.push(appointment[0]);
  })
  return newArray;
}
const result = mapTo(queued_Dr)
console.log(result);

A: The first solution is to find the name in all_appointments and return the corresponding abbreviation.
The second solution is to just compose the abbreviation without other arrays.

const queued_Dr = ["Dr.Salazar","Dr.Connors","Dr.Johnson","Dr.Pearson"];

const all_appointments = [["Dr-S","New York","Dr.Salazar"],["Dr-C","Austin","Dr.Connors"],["Dr-J","Austin","Dr.Johnson"],["Dr-S","New York","Dr.Salazar"],["Dr-P","San Juan","Dr.Pearson"],["Dr-J","Austin","Dr.Johnson"]];

const result1 = queued_Dr
  .map((queu) => all_appointments
    .find((appointment) => appointment.at(-1) === queu)
    .at(0));

console.log(result1);

const result2 = queued_Dr
  .map((queu) => {
    const [abbr, name] =  queu.split('.');
    return `${abbr}-${name.at(0)}`;
  });

console.log(result2);
.as-console-wrapper {max-height: 100% !important; top: 0}


text:
Q: nagios mysql check using unexpected user after upgrading from ubuntu 12.04 to 14.04 I had Icinga monitoring my network. Everything was working fine.
After upgrading from ubuntu 12.04 to 14.04, MySQL monitoring started reporting problems.
I discovered that nagios check_mysql always uses 'root' user, where it previously used the nagios user (I assume because Icinga is running as that user).
user@server0:~$ /usr/lib/nagios/plugins/check_mysql -H server1
/usr/lib/nagios/plugins/check_mysql: /usr/lib/libmysqlclient.so.18: no version information available (required by /usr/lib/nagios/plugins/check_mysql)
Access denied for user 'root'@'server0' (using password: NO)

Is that some behaviour change I missed?
Also, I assume that the missing library does not cause problems, as passing -u/-p parameters to check_mysql makes it succesfully connect.

A: In recent version of Debian/Ubuntu, the nagios process (and likely other daemons) runs without $HOME set.  That is why check_mysql resorts to reading /proc/self/loginuid, which is wrong, it should just find out the real user id with getuid() and take that user's home directory.
Anyway, a solution is to supply -f optfile to check_mysql, eg.:
check_mysql -H 127.0.0.1 -f /var/lib/nagios/.my.cnf


text:
Q: JNDI ClassCastException with tomcat 6.0.26 I am developing a webapp that requires setting up a DataSource with JNDI using Enterprise JDBC Classes.I am using the Netbeans 6.9 bundled tomcat (6.0.26 app) server with mysql 5.xx.The issue really is that I can still see the database values from a relation being displayed in my jsp page whereas during the tomcat initialization it says something like this:
.
.
SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.BasicDataSource cannot be cast to javax.naming.Context
        at org.apache.jsp.Hello_jsp._jspService(Hello_jsp.java:141)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
        at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859)
        at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
        at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1555)
        at java.lang.Thread.run(Thread.java:619)
Jul 25, 2010 1:28:25 AM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextDestroyed()
Jul 25, 2010 1:28:25 AM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextDestroyed()
Jul 25, 2010 1:28:32 AM org.apache.catalina.core.ApplicationContext log
INFO: ContextListener: contextInitialized()
Jul 25, 2010 1:28:32 AM org.apache.catalina.core.ApplicationContext log
INFO: SessionListener: contextInitialized()
Jul 25, 2010 1:28:40 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet jsp threw exception
javax.naming.NameNotFoundException: Name nexusirm is not bound in this Context
        at org.apache.naming.NamingContext.lookup(NamingContext.java:770)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:140)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:781)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:140)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:781)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:140)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:781)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
        at org.apache.naming.SelectorContext.lookup(SelectorContext.java:152)
        at javax.naming.InitialContext.lookup(InitialContext.java:392)
        at org.apache.jsp.Hello_jsp._jspService(Hello_jsp.java:141)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
        at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859)
        at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
        at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1555)
        at java.lang.Thread.run(Thread.java:619)
Jul 25, 2010 1:29:50 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet jsp threw exception
javax.naming.NameNotFoundException: Name jdbc is not bound in this Context
        at org.apache.naming.NamingContext.lookup(NamingContext.java:770)
        at org.apache.naming.NamingContext.lookup(NamingContext.java:153)
        at org.apache.naming.SelectorContext.lookup(SelectorContext.java:152)
        at javax.naming.InitialContext.lookup(InitialContext.java:392)
        at org.apache.jsp.Hello_jsp._jspService(Hello_jsp.java:143)
        at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
        at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
        at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.netbeans.modules.web.monitor.server.MonitorFilter.doFilter(MonitorFilter.java:393)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
        at org.apache.coyote.http11.Http11AprProcessor.process(Http11AprProcessor.java:859)
        at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:579)
        at org.apache.tomcat.util.net.AprEndpoint$Worker.run(AprEndpoint.java:1555)
        at java.lang.Thread.run(Thread.java:619)
Jul 25, 2010 1:30:10 AM org.apache.catalina.core.ApplicationContext log

.
.
I have the following inside my /WEB-INF/web.xml
<resource-ref>
         <res-ref-name>jdbc/NexusIRM</res-ref-name>
         <res-type>javax.sql.DataSource</res-type>
         <res-auth>Container</res-auth>
         <res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>

And the following in my /META-INF/context.xml
 <Resource name="jdbc/NexusIRM"
           auth="Container"
           type="javax.sql.DataSource"
           driverClassName="com.mysql.jdbc.Driver"
           url="jdbc:mysql://localhost:3306/nexusirm"
           username="root"
           password=""
           maxActive="20"
           maxIdle="30"
           maxWait="-1"

 />

My Application code looks like:
                <%
 try{

Context initCtx = new InitialContext();

DataSource ds = (DataSource)
  initCtx.lookup("java:comp/env/jdbc/NexusIRM");

Connection conn=ds.getConnection();

Statement stmt=conn.createStatement();
ResultSet rs=stmt.executeQuery("SELECT * FROM irm_gtresult");

if(rs.next())
    {
    for(int i=1;i<9;i++){
out.write(rs.getString(i));
}
}
conn.close();
}catch(SQLException e)
{out.write(e.getMessage());
e.printStackTrace();}

%>

I am just curious to why these exceptions are being thrown while the application is being executed perfectly!

A: Try this ...
Connection conn;
try
{
    // Obtain our environment naming context
    Context initCtx = new InitialContext();
    Context envCtx = (Context) initCtx.lookup("java:comp/env");

    // Look up our data source
    DataSource ds = (DataSource)
      envCtx.lookup("jdbc/NexusIRM");

    // Allocate and use a connection from the pool
    Connection conn = ds.getConnection();
    ... use this connection to access the database ...
}
finally
{
   if(conn != null)
       conn.close();
}

NOTE: Make sure you put your close in a finally !!!


text:
Q: Travellerspoint map functionality I want to develop something like Travellerspoint. Can someone guide me how can i achieve it? I tried Google maps but that doesn't give me all map functionality as they have created.

A: You could try using OpenLayers. There is a showcase which includes some source code for the functions.
Showcase
http://openlayers.org/dev/examples/
Wiki
http://en.wikipedia.org/wiki/OpenLayers


text:
Q: Create Json with same key I am trying to add json documents to solr. I want the structure of the json file to be like:
{
    "add": {
        "doc": {
            "id": "DOC1",
            "my_boosted_field": {
                "boost": 2.3,
                "value": "test"
            }
        }
    },
    "add": {
        "commitWithin": 5000,
        "overwrite": false,
        "boost": 3.45,
        "doc": {
            "f1": "v1"
        }
    }
}

I cannot make it as an array as the Solr wants the exact same format to index the documents. How this can be done using gson or is there any other way?

A: Can you try modifying your JSON file like below.
{
    "add": {
        "doc": {
            "id": "DOC1",
            "my_boosted_field": {
                "boost": 2.3,
                "value": "test"
            },
            "f1": "v1"
        }
        "commitWithin": 5000,
        "overwrite": false,
        "boost": 3.45,
    }
}


text:
Q: CDI 2.0 (Weld): Can't inject non CDI component In a rest endpoint deployed on Wildfly 20, I need to inject an external non CDI instance of the javax.ws.rs.core.UriBuilder class. For example:
@Path("...")
public class MyResource
{
  ...
  @Inject
  private UriBuilder uriBuilder;
  ...
}

Here is the producer:
public class UriBuilderProducer
{
  @Produces
  public UriBuilder getUriBuilder()
  {
    return UriBuilder.fromResource(Customer.class);
  }
}

The beans.xml file reads as follows:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                       http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
   version="2.0" bean-discovery-mode="all">
</beans>

However, the deployment fails raising the following exception:
15:03:24,837 ERROR [org.jboss.msc.service.fail] (MSC service thread 1-3) MSC000001: Failed to start service jboss.deployment.unit."myresource.war".WeldStartService: org.jboss.msc.service.StartException in service jboss.deployment.unit."myresource.war".WeldStartService: Failed to start service
    at org.jboss.msc@1.4.11.Final//org.jboss.msc.service.ServiceControllerImpl$StartTask.execute(ServiceControllerImpl.java:1731)
    at org.jboss.msc@1.4.11.Final//org.jboss.msc.service.ServiceControllerImpl$ControllerTask.run(ServiceControllerImpl.java:1559)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.ContextClassLoaderSavingRunnable.run(ContextClassLoaderSavingRunnable.java:35)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor.safeRun(EnhancedQueueExecutor.java:1982)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.doRunTask(EnhancedQueueExecutor.java:1486)
    at org.jboss.threads@2.3.3.Final//org.jboss.threads.EnhancedQueueExecutor$ThreadBody.run(EnhancedQueueExecutor.java:1377)
    at java.base/java.lang.Thread.run(Thread.java:834)
 Caused by: org.jboss.weld.exceptions.DeploymentException: WELD-001408: Unsatisfied dependencies for type UriBuilder with qualifiers @Default
   at injection point [UnbackedAnnotatedField] @Inject private ...MyResource.uriBuilder
   at ...MyResource.uriBuilder(MyResource.java:0)

What did I miss here ?
Many thanks in advance for any help.
Kind regards,
Seymour

A: My bad, I've put the beans.xml in the wrong place. In order to land in the WEB-INF directory of the resulted WAR, one needs to put it in src/main/webapp/WEB-INF and not in src/main/resources/WEB-INF, as one would expect, based on maven COC (Convention Over Configuration) rules.
Having this file in the right place solves the issue, of course. Sorry for the inconvenience.
Kind regards,
Seymour