text:
Q: WHOIS command not returning useful information? Whenever you use WHOIS command doesn't return any usefully information. I usually have to go to Godaddy, Dnsstuff or other services to get the data.  I understand the reason is mostly due to spamming.
I was just wondering how other services get this data. Do they use different type of WHOIS command? Also confused about some of the data generated data from WHOIS command is just spam. Example doing whois google.com geneates spam website such as GOOGLE.COM.ZZZZZZ.THE.BEST.WEBHOSTING.AT.WWW.FATUCH.COM. Where is this data come from?
Exmaple:
Whois Server Version 2.0

Domain names in the .com and .net domains can now be registered
with many different competing registrars. Go to http://www.internic.net
for detailed information.

GOOGLE.COM.ZZZZZZ.THE.BEST.WEBHOSTING.AT.WWW.FATUCH.COM
GOOGLE.COM.WORDT.DOOR.VEEL.WHTERS.GEBRUIKT.SERVERTJE.NET
GOOGLE.COM.UY
GOOGLE.COM.UA
GOOGLE.COM.TW
GOOGLE.COM.TR
GOOGLE.COM.SA
GOOGLE.COM.PE
GOOGLE.COM.MX
GOOGLE.COM.DO
GOOGLE.COM.CO
GOOGLE.COM.CN
GOOGLE.COM.BR
GOOGLE.COM.AU
GOOGLE.COM.AR
GOOGLE.COM.AFRICANBATS.ORG
GOOGLE.COM

To single out one record, look it up with "xxx", where xxx is one of the
of the records displayed above. If the records are the same, look them up
with "=xxx" to receive a full display for each record.

>>> Last update of whois database: Wed, 30 Mar 2011 03:07:59 UTC <<<

NOTICE: The expiration date displayed in this record is the date the
registrar's sponsorship of the domain name registration in the registry is
currently set to expire. This date does not necessarily reflect the expiration
date of the domain name registrant's agreement with the sponsoring
registrar.  Users may consult the sponsoring registrar's Whois database to
view the registrar's reported date of expiration for this registration.

TERMS OF USE: You are not authorized to access or query our Whois
database through the use of electronic processes that are high-volume and
automated except as reasonably necessary to register domain names or
modify existing registrations; the Data in VeriSign Global Registry
Services' ("VeriSign") Whois database is provided by VeriSign for
information purposes only, and to assist persons in obtaining information
about or related to a domain name registration record. VeriSign does not
guarantee its accuracy. By submitting a Whois query, you agree to abide
by the following terms of use: You agree that you may use this Data only
for lawful purposes and that under no circumstances will you use this Data
to: (1) allow, enable, or otherwise support the transmission of mass
unsolicited, commercial advertising or solicitations via e-mail, telephone,
or facsimile; or (2) enable high volume, automated, electronic processes
that apply to VeriSign (or its computer systems). The compilation,
repackaging, dissemination or other use of this Data is expressly
prohibited without the prior written consent of VeriSign. You agree not to
use electronic processes that are automated and high-volume to access or
query the Whois database except as reasonably necessary to register
domain names or modify existing registrations. VeriSign reserves the right
to restrict your access to the Whois database in its sole discretion to ensure
operational stability.  VeriSign may restrict or terminate your access to the
Whois database for failure to abide by these terms of use. VeriSign
reserves the right to modify these terms at any time.

The Registry database contains ONLY .COM, .NET, .EDU domains and
Registrars.

A: You're asking for all record types, rather than just domain records. From whois help

By default, WHOIS performs a very broad search, looking in all record types for matches to your query in these fields: domain name, nameserver name, nameserver IP address, and registrar names. Use keywords to narrow the search.
The following keywords restrict a search to a certain TYPE of field in the database: domain Finds a domain record. Find out domain name, registrar name, whois server and URL, Nameserver name and IP Addresses, and updated date.

There are two possible fixes:
1. Set the domain option explicitly:
 whois "domain google.com"

2. Use a whois host that only returns 'domain" results
whois -h geektools.com google.com

See Why there's junk in your whois results, and how you can get rid of it for more info.

A: The short answer to your question, assuming you are using the debian/ubuntu whois library, is to use
$ whois -h whois.crsnic.net "domain google.com"

Here's the long answer.
The .COM TLD is a Thin WHOIS. When you peform a WHOIS query, the WHOIS tool first sends a WHOIS query to Verisign (hostname whois.crsnic.net) and extract the referral from the the response.
By default, when you query Verisign from the domain example.com, Whois performs a very broad search of the string "example.com" in several different objects including the domain name, the registrar name and the nameservers.
You can refine the query by specifying a keyword, as described in the Verisign documentation.
http://registrar.verisign-grs.com/whois/iframe/help.html?ppath=www.verisigninc.com/products-and-services/domain-name-services/whois&
The command above does exactly what I explained. Instead of google.com it sends to Verisign the full query "domain google.com". You have to explicitly pass the -h flag because Whois attempts to guess the hostname to query from the query, but it will fail because it won't recognize the query "domain google.com" as a valid domain.
Here's the result of the command.
$ whois -h whois.crsnic.net "domain google.com"

Whois Server Version 2.0

Domain names in the .com and .net domains can now be registered
with many different competing registrars. Go to http://www.internic.net
for detailed information.

   Domain Name: GOOGLE.COM
   Registrar: MARKMONITOR INC.
   Whois Server: whois.markmonitor.com
   Referral URL: http://www.markmonitor.com
   Name Server: NS1.GOOGLE.COM
   Name Server: NS2.GOOGLE.COM
   Name Server: NS3.GOOGLE.COM
   Name Server: NS4.GOOGLE.COM
   Status: clientDeleteProhibited
   Status: clientTransferProhibited
   Status: clientUpdateProhibited
   Status: serverDeleteProhibited
   Status: serverTransferProhibited
   Status: serverUpdateProhibited
   Updated Date: 15-sep-2010
   Creation Date: 15-sep-1997
   Expiration Date: 14-sep-2011

>>> Last update of whois database: Wed, 30 Mar 2011 08:50:16 UTC <<<

NOTICE: The expiration date displayed in this record is the date the
registrar's sponsorship of the domain name registration in the registry is
currently set to expire. This date does not necessarily reflect the expiration
date of the domain name registrant's agreement with the sponsoring
registrar.  Users may consult the sponsoring registrar's Whois database to
view the registrar's reported date of expiration for this registration.

TERMS OF USE: You are not authorized to access or query our Whois
database through the use of electronic processes that are high-volume and
automated except as reasonably necessary to register domain names or
modify existing registrations; the Data in VeriSign Global Registry
Services' ("VeriSign") Whois database is provided by VeriSign for
information purposes only, and to assist persons in obtaining information
about or related to a domain name registration record. VeriSign does not
guarantee its accuracy. By submitting a Whois query, you agree to abide
by the following terms of use: You agree that you may use this Data only
for lawful purposes and that under no circumstances will you use this Data
to: (1) allow, enable, or otherwise support the transmission of mass
unsolicited, commercial advertising or solicitations via e-mail, telephone,
or facsimile; or (2) enable high volume, automated, electronic processes
that apply to VeriSign (or its computer systems). The compilation,
repackaging, dissemination or other use of this Data is expressly
prohibited without the prior written consent of VeriSign. You agree not to
use electronic processes that are automated and high-volume to access or
query the Whois database except as reasonably necessary to register
domain names or modify existing registrations. VeriSign reserves the right
to restrict your access to the Whois database in its sole discretion to ensure
operational stability.  VeriSign may restrict or terminate your access to the
Whois database for failure to abide by these terms of use. VeriSign
reserves the right to modify these terms at any time.

The Registry database contains ONLY .COM, .NET, .EDU domains and
Registrars.

A: When you request WHOIS info for google.com, it searches for "google.com" in all records, not anchoring the pattern to the end as you expect.
And it depends on the WHOIS client and which servers it is configured to use. I did some research a couple years ago about setting up an internal WHOIS service (I work at a university, so we have lots of little fiefdoms and lots of networks) and from what I could tell, there was very little consistent structure in the data formats, so clients have to employ lots of heuristics to figure out referrals and such. My guess is that dnsstuff and godaddy just have probably more tuned heuristics. So you might just try a different client.

A: Do a whois query with an equal sign at beginning just before domain name.
What you see is just pure vanity nameservers created at the registry, as a useless prank (no technical consequences).


text:
Q: Stop Bootstrap table stretching to full screen width and adding extra space to the cells I have a table that fits on screens up to 600px. When the screen size becomes larger than 600px, the table grows to fill the screen and gives each column a lot of extra spacing on the right of each cell.
How do I remove this stop the table from growing and remove extra unwanted space so that the next column starts at the end of the largest cell from the previous column?

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
    integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> -->

      Stat
      First
      Last
      Handle

      Highest Money Reached
      Mark
      Otto
      @mdo

      2
      Jacob
      Thornton
      @fat

      3
      Larry
      the Bird
      @twitter

The code is also on this JsFiddle

A: You are using Bootstrap classes, and the Bootstrap .table sets the with of the table to width:100%;. You could remove the table class from your table HTML and that would your - however it also affects some of the styling also.
Instead, to prevent your table from stretching to the full screen width (unless it needs to), you just need to add the following to your CSS:
table.table { width:auto; }

Just make sure that this is included after your Bootstrap CSS, and don't forget to include the .table in your CSS selector to override the Bootstrap class.
Working Example:

table.table { width:auto;}

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
    integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

      Stat
      First
      Last
      Handle

      Highest Money Reached
      Mark
      Otto
      @mdo

      2
      Jacob
      Thornton
      @fat

      3
      Larry
      the Bird
      @twitter

redpajama_set_name: RedPajamaStackExchange


text:
Q: procmail to deliver mail to 2 maildir locations Now I am having Postifx --> procmailrc---> maildire---> dovecot   and I need to have another maildir in another folder inside /root as a backup at the same time having /$home/maildir ?
First and second both should have mails in maildir format.
How can I instruct procmail to have second maildir in another location /root ?.
If this second location need be another server, how can I send the mail to there?
my current procmailrc file is at /etc and which is --->
:0fw: spamassassin.lock
* < 256000
| /usr/bin/spamassassin

:0
* ^X-Spam-Status: Yes
/home/spammail/Maildir/

LOGFILE="/var/log/procmail.log"
DEFAULT="$HOME/Maildir/"
MAILDIR="$HOME/Maildir/"

Your help expected.
Thanks,
lasantha

A: Youc can use c flag (carbon copy).
Add this lines before the one with :0
:0c:
/your/backup/Maildir/


text:
Q: How to access key, value in json / ruby I have a json file like this, and I try to display the different value in my html:
{
    "testimonials": [
        {
            "office": "Test",
            "authors": "Benjamin",
        },
        {
            "office": "consultant",
            "authors": "Maxime ",
        },
        {
            "office": "DAF",
            "authors": "Alexandre",

        },
        {
            "office": "CEO",
            "authors": "Raphaël",
          },
        {
            "office": "Consultant",
            "authors": "Alexis",
        },
        {
            "office": "CEO,",
            "authors": "Sylvain",
        }
    ]
}

Could someone help me, for example, to access to display the value 'Alexis'

A: This is not valid JSON due to the trailing commas within your hashes. If you fix the commas, minify the JSON to make it easier to work with, and save it as a string, then you can begin to work with it in Ruby:
json = '{"testimonials":[{"office":"Test","authors":"Benjamin"},{"office":"consultant","authors":"Maxime "},{"office":"DAF","authors":"Alexandre"},{"office":"CEO","authors":"Raphaël"},{"office":"Consultant","authors":"Alexis"},{"office":"CEO,","authors":"Sylvain"}]}'

Now parse it into a real Ruby object:
hash = JSON.parse(json)
=> {
    "testimonials" => [
        [0] {
             "office" => "Test",
            "authors" => "Benjamin"
        },
        [1] {
             "office" => "consultant",
            "authors" => "Maxime "
        },
        [2] {
             "office" => "DAF",
            "authors" => "Alexandre"
        },
        [3] {
             "office" => "CEO",
            "authors" => "Raphaël"
        },
        [4] {
             "office" => "Consultant",
            "authors" => "Alexis"
        },
        [5] {
             "office" => "CEO,",
            "authors" => "Sylvain"
        }
    ]
}

This is a hash that has an array of hashes inside it. You should access it using the standard methods for Hash and Array.
Start by getting the value of the only key in the hash, which is an array:
array = hash['testimonials']
=> [
    [0] {
         "office" => "Test",
        "authors" => "Benjamin"
    },
    [1] {
         "office" => "consultant",
        "authors" => "Maxime "
    },
    [2] {
         "office" => "DAF",
        "authors" => "Alexandre"
    },
    [3] {
         "office" => "CEO",
        "authors" => "Raphaël"
    },
    [4] {
         "office" => "Consultant",
        "authors" => "Alexis"
    },
    [5] {
         "office" => "CEO,",
        "authors" => "Sylvain"
    }
]

You indicated you wanted to fetch a value from index 4:
sub_hash = array[4]
=> {
     "office" => "Consultant",
    "authors" => "Alexis"
}

And that you wanted to return the string Alexis:
string = sub_hash['authors']
=> "Alexis"

Or put it all together in one line:
string = hash['testimonials'][4]['authors']
=> "Alexis"

Or one even shorter line:
JSON.parse(json)['testimonials'][4]['authors']
=> "Alexis"


text:
Q: Application Performance improving using visual studio I'm working on a large application with great number of classes containing properties with getters making calls to the database. These properties are used everywhere in foreach loops and in grids rows data source binding. Is there an efficient way (technique or tool) to find all these properties so I can optimise them and include them in my final report? - Something like: Give me all properties that make a Database call in their getters and are used in a foreach loop or bound to data source of a grid rows.
Thanks


text:
Q: Requesting Administrator privileges during runtime How do I request Administrator privileges during runtime so the user is given the prompt to allow or disallow it?

A: if you want it in response to a button (eg, like 'show processes for all users' in task manager), you have to resart your app using the following method
ShellExecute(0,L"runas",exepath,0,0,SW_SHOWNORMAL);

A: This information is written in the exe file manifest. You must use the requestedExecutionLevel field (but not sure about that - try setting it to highestAvailable and see if it does what you need). See for example here for more information (somewhat older article but still valid): http://blogs.msdn.com/b/cjacks/archive/2006/09/08/exploring-manifests-part-2-default-namespaces-and-uac-manifests-in-windows-vista.aspx
There are tools in Visual Studio which allow you to embed your own manifest or even just edit it. Also there is a tool written in Perl ( http://metacpan.org/pod/Win32::Exe::Manifest ).
EDIT: see this article for more info: http://www.codeproject.com/Articles/66259/Requesting-Admin-Approval-at-Application-Start.aspx


text:
Q: How do I download a file from a host i'm already connected to over ssh I'm trying to download a file from a linux server i'm already connected to.
I know you can use scp to connect to and pull down a file from a host, but that requires still being on local.
I could scp the file back to my local machine, but the local machine is not accessible from the host.
Is there a way to just pull down the file you are already looking at? Something like:
From the host
$ download <THEFILE>

This would really just be more convenient than having to go back out to my local terminal than scp the file. Instead you could just say "grab this one" Done.
I suppose the client would have to know what to do with the file. And i'm pretty sure "terminal.app" does not have a default downloads folder. So perhaps this is not possible.
BTW I'm connect from a mac to Debian.

A: Your machine hostname is not resolvable from the remote host. You should do this the other way round. From your local host:
scp xyz@remote:/home/user/test /home/user

Or the other way is to set up remote port forwarding, so you will be able to connect from your remote machine to your local host. Your command can look like this:
[local] $ ssh -R 2222:localhost:22 remote
[remote]$ scp -P 2222 /home/user/test xyz@localhost:/home/user

Inspired by my answer on SO

A: If I understand your question, You are sitting in front of the mac and have a ssh into the debian. You see a file on the debian that you want on your mac.
You do not want to 'pull' the file from the debian to the mac because you must switch terminals.
Use scp to 'push' the file from the debian terminal.
scp /local/file/on/debian mac_user@mac:/downloads

/downloads on the mac must be accessible by the mac_user


text:
Q: How can I see when a package was released/updated using `apt`? I want to install the "file" package using apt, since my Docker container is missing the file command. Before installing, I'm checking the package details (see below).
How can I see the date these packages were released/updated? Their descriptions say that they are supported for 5 years, but that makes no sense, when I cannot see when they were released/updated?
Also, why is apt listing two "file" packages? Which one of those would be installed, when I run apt install file?
root@eca1fcd5655a:/mnt/dotnetcore# apt show -a file
Package: file
Version: 1:5.32-2ubuntu0.3
Priority: important
Section: utils
Origin: Ubuntu
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Christoph Biedl <debian.axhn@manchmal.in-ulm.de>
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Installed-Size: 81.9 kB
Depends: libc6 (>= 2.4), libmagic1 (= 1:5.32-2ubuntu0.3)
Homepage: http://www.darwinsys.com/file/
Task: minimal
Supported: 5y
Download-Size: 22.1 kB
APT-Sources: http://archive.ubuntu.com/ubuntu bionic-updates/main amd64 Packages
Description: Recognize the type of data in a file using "magic" numbers

Package: file
Version: 1:5.32-2
Priority: important
Section: utils
Origin: Ubuntu
Maintainer: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Original-Maintainer: Christoph Biedl <debian.axhn@manchmal.in-ulm.de>
Bugs: https://bugs.launchpad.net/ubuntu/+filebug
Installed-Size: 81.9 kB
Depends: libc6 (>= 2.4), libmagic1 (= 1:5.32-2)
Homepage: http://www.darwinsys.com/file/
Task: minimal
Supported: 5y
Download-Size: 22.1 kB
APT-Sources: http://archive.ubuntu.com/ubuntu bionic/main amd64 Packages
Description: Recognize the type of data in a file using "magic" numbers

A: The five-year support term applies to supported packages in Ubuntu LTS releases as a whole; when individual packages are released or updated doesn't matter. Packages in the main repository receive publicly-available security updates for five years after the initial release of the distribution.
To see the latest changes to a package, look at its changelog:
zcat /usr/share/doc/${package}/changelog.Debian.gz | head -n 20

In this case, /usr/share/doc/file/changelog.Debian.gz.
You can also view a changelog without installing the package by using apt changelog:
apt changelog file

or look at the release information on the package's page on Launchpad.
apt show -a lists two packages in your case because there are two versions available, one in the main repository, and another in the updates repository. The version which will be installed is the greater of the two, the version from the updates repository.


text:
Q: How can "an expression with side effects" be passed to getc?
"Advanced Programming in the UNIX Environment, 3rd Edition", page 151:
The difference between getc and fgetc is that getc can be implemented
  as a macro, whereas fgetc cannot be implemented as a macro. This means
  three things:

*

*The argument to getc should not be an expression with side effects.

*Since fgetc is guaranteed to be a function, we can take its address. This allows us to pass the address of fgetc as an argument to another
  function.

*Calls to fgetc probably take longer than calls to getc, as it usually takes more time to call a function.

What "expression with side effects" can occur for the function signatures with stream pointer as a parameter?
#include<stdio.h>
int getc(FILE* stream);
int fgetc(FILE* stream);

A: There are probably hundreds of ways to pass an expression with side effects, but a "credible" one would be something like:
FILE *files[NUM_FILES];
...
int rc = getc(files[counter++]);

If getc is implemented poorly as a macro, the expression files[counter++] could be evaluated more than once, leading to unexpected behavior.

A: As an example, don't write
FILE* foo() { puts( "Bah!\n" ); return stdout; }

void advance() { getc( foo() ); }


text:
Q: Iterating over plans returned by Stripe's PHP API wrapper As far as I can see, there was a way to iterate over collections returned by official Stripe PHP library like this:
foreach (\Stripe\Plan::all() as $plan) {
    print("$plan->id ($plan->interval)\n");
}

But that does not work any more (I'm on PHP7 and use stripe/stripe-php v3.9.2). I have to run it like this:
foreach (\Stripe\Plan::all()->__toArray()['data'] as $plan) {
    print("$plan->id ($plan->interval)\n");
}

Did anyone else noticed this problem? What changed? While I know how to make it work, it just does not look right.

A: As far as I can tell, this never worked. ::all() calls return a Collection object (or a Stripe_List object in 1.x versions) that is not directly iterable.
The proper syntax to iterate over the results of a call to ::all() is:
foreach (\Stripe\Plan::all()->data as $plan) {
    // Do something with $plan
}

With the newer versions (>= 3.9.0), you can use the auto-paging feature:
foreach (\Stripe\Plan::all()->autoPagingIterator() as $plan) {
    // Do something with $plan
}

This will let you iterate over the entire list of plans automatically. The bindings will take care of issuing all the requests with pagination parameters in the background for you.


text:
Q: Pine script - dolar cost average strategy I'm new to Pinescript and am trying to build a strategy that would place an initial order at a limit price and will DCA (dollar cost average) the position if the price drops by x percent. I've managed to get initial order placed with the code below, but cannot make the rest of it working. TradingView would place initial order and but would not DCA. I'm using a loop to place those subsequent orders. I'd appreciate your any insights you could provide into it.
//@version=4
strategy("DCA calculcator - version 2.0", shorttitle = 'DCA calculator', overlay = false)
base_order = input(title = 'Base order value', type = input.integer, defval = 100)
safe_order = input(title = 'Safe order value', type = input.integer, defval = 100)
take_profit = input(title = 'Take profit level', type = input.integer, defval = 2) / 100
price_deviation = input(1.5, type=input.float,  title="Price deviation to open safety order (%)", minval=0.0, step=0.1)/100
safe_order_step_scale   = input(1.0, type=input.float,  title="Safety Order Step Scale", step=0.1)
max_safe_order = input(title = 'Max safe order', type = input.integer, defval = 4)
start_time = input(type = input.time, title = 'Trade start time', defval = timestamp("1 April 2021 06:00"), group = "Trade start and end time")
end_time = input(type = input.time, title = 'Trade end time', defval = timestamp("1 July 2021 06:00"),  group = "Trade start and end time")

//declarations
var bo_price = 0.0
var open_trades = 0
var deal_start_condition = false

//utility functions
within_window() => time >= start_time and time <= end_time
plot_color() => (within_window() and strategy.opentrades == 0) ? color.new(color.blue, 50) : color.new(color.red, 100)
so_qty(so_level) => safe_order / so_level

safety_order_deviation(index) => price_deviation * pow(safe_order_step_scale,  index - 1)
safety_order_price(index, last_safety_order_price) => last_safety_order_price * (1 - safety_order_deviation(index))

var so_level = 0.0
var last_so_level = 0.0

safe_order_gen(so_price) => so_price * 0.98

//placing base order
if within_window()
    bo_price := close
    strategy.entry("BO placed", limit=bo_price, long=strategy.long, qty=base_order/bo_price)
    last_so_level :=  bo_price

    for index = 1 to 3
        so_price = last_so_level * 0.99
        strategy.entry('SO placed', long=strategy.long, limit=so_price, qty = safe_order / so_price)
        last_so_level := so_price

plot(bo_price, color = color.green)
plot(last_so_level, color = color.blue, title = 'SO price')


text:
Q: using ExternalContext.dispatch in JSF error handler causes corrupt page rendering Simplified, my error handler looks like this:
@Override
public void handle() throws FacesException {
    Iterator<ExceptionQueuedEvent> unhandledExceptionQueuedEvents = getUnhandledExceptionQueuedEvents().iterator();
    FacesContext context = FacesContext.getCurrentInstance();

    if (unhandledExceptionQueuedEvents.hasNext()) {
        Throwable exception = unhandledExceptionQueuedEvents.next().getContext().getException();
        unhandledExceptionQueuedEvents.remove();
        context.getExternalContext().dispatch("/error.jsf");
    }

    while (unhandledExceptionQueuedEvents.hasNext()) {
        unhandledExceptionQueuedEvents.next();
        unhandledExceptionQueuedEvents.remove();
    }
}

simplified template.xhtml

    <f:view>
    <h:head>

    </h:head>
    <h:body>

            <ui:insert name="body"></ui:insert>

    </h:body>
    </f:view>

error.xhtml

<ui:composition template="/template.xhtml">
    <ui:define name="body">
        ERROR
    </ui:define>
</ui:composition>

But when rendering error.jsf, templating with ui:composition goes very wrong. JSF renders template.xhtml up until around the , where it starts rendering the template all over again. The result is a page where menus are rendered twice, and all resources are included once again in the middle of the page. The start of it looks something like this:

<div<?xml version="1.0" encoding="UTF-8" ?="">

This is followed by an infinite loop on the server, causing millions of log rows containing the following bit over and over again
at com.xdin.competence.web.error.ErrorHandler.handleException(ErrorHandler.java:123) [:]
at com.xdin.competence.web.error.ErrorHandler.handle(ErrorHandler.java:108) [:]
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:115) [:2.0.3-]
at com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:107) [:2.0.3-]
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114) [:2.0.3-]
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:308) [:2.0.3-]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:324) [:6.0.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:242) [:6.0.0.Final]
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:734) [:6.0.0.Final]
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:541) [:6.0.0.Final]
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:479) [:6.0.0.Final]
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:407) [:6.0.0.Final]
at com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:542) [:2.0.3-]
at javax.faces.context.ExternalContextWrapper.dispatch(ExternalContextWrapper.java:89) [:2.0.3-]
at org.jboss.seam.faces.environment.org$jboss$weld$bean-jboss$classloader:id="vfs:$$$C:$JBoss$jboss-6$0$0$Final$server$career$deploy$career-portal$war"-ManagedBean-class_org$jboss$seam$faces$environment$SeamExternalContext_$$_WeldClientProxy.dispatch(org$jboss$weld$bean-jboss$classloader:id="vfs:$$$C:$JBoss$jboss-6$0$0$Final$server$career$deploy$career-portal$war"-ManagedBean-class_org$jboss$seam$faces$environment$SeamExternalContext_$$_WeldClientProxy.java) [:3.0.1.Final]

Any idea of what the cause could be?

A: You should not use ExternalContext#dispatch() to render a JSF view. It should only be used to forward to a non-JSF resource. You should instead set the desired JSF view by FacesContext#setViewRoot() and let JSF render it.
ViewHandler viewHandler = context.getApplication().getViewHandler();
UIViewRoot viewRoot = viewHandler.createView(context, viewId);
context.setViewRoot(viewRoot);
context.renderResponse();

Or, if you're currently already sitting in the render response, then it's too late to let JSF re-render it. You'd need to build and render the new view manually. In that case, replace the last line by:
ViewDeclarationLanguage vdl = viewHandler.getViewDeclarationLanguage(context, viewId);
vdl.buildView(context, viewRoot);
context.getApplication().publishEvent(context, PreRenderViewEvent.class, viewRoot);
vdl.renderView(context, viewRoot);
context.responseComplete();

Note that this is in turn too late if the response is already committed. You may want to check that beforehand as well.
You may find the source code of the OmniFaces FullAjaxExceptionHandler helpful to get some insight.


text:
Q: Different length scale per dimension in TensorFlow I would like to know how to use a different length scale in a kernel for each dimension of the input. For instance, take an input of dimension 4, I would like to use 4 different length scales where for each coordinate of the input.
That is, take the Gaussian Kernel (see https://www.tensorflow.org/probability/api_docs/python/tfp/math/psd_kernels/ExponentiatedQuadratic) for example, I want to define the kernel $k$ as
$k(x,y) = exp(- (\frac{(x_1 - y_1)^2}{\gamma_1^2} + \frac{(x_2 - y_2)^2}{\gamma_2^2}))$ instead of $k(x,y) = exp(- \frac{||x - y||^2}{\gamma^2})$ where $x = (x_1, x_2)$ and $y = (y_1, y_2)$.


text:
Q: error TargetInvocationException when debugging (precisly when connecting to db) asp.net mvc I have a TargetInvocationException error when debugging, it seems that there is not possible to connect to the database.
I don't know why, it suddenly doesn't work. I've just change the PC because of the expiration of the version of visual studio express I didn't know first that it is free.
So can somebody help me ?
Thank you for your help.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
    private static SimpleMembershipInitializer _initializer;
    private static object _initializerLock = new object();
    private static bool _isInitialized;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Ensure ASP.NET Simple Membership is initialized only once per app start
        LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
    }

  private class SimpleMembershipInitializer
    {
        public SimpleMembershipInitializer()
        {
            Database.SetInitializer<UsersContext>(null);

            try
            {
                using (var context = new UsersContext())
                {
                    if (!context.Database.Exists())   // Here is thrown the error
                    {
                        // Create the SimpleMembership database without Entity Framework migration schema
                        ((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
                    }
                }

It is when I try to connect the defaultConnection database.


text:
Q: How to filter a django OR query correctly I tried to make an OR query with django q. But the number of results is differnt to filter in single queries:
//result is 7
len(Project.objects.filter(Q(moderator='A') | Q(participant='B')))

//result is 6
len(Project.objects.filter(Q(moderator='A')))

//result is 0
len(Project.objects.filter(Q(participant='B')))

since the third query responses a empty queryset, I expect the same results with first and second query. What is here the problem?
I got the same result if I do:
//len is 6
q1 = Project.objects.filter(Q(moderator='A'))

//len is 0
q2 = Project.objects.filter(Q(participant='B'))

//len is 7
q1 | q2

I can resolve this with distinct(). But how can a merge with a querset of 0 produce more results than before?

A: This happens if both moderator and participant are ManyToManyFields, in that case, it will make two LEFT OUTER JOINs, and the Project object will thus be repeated for each record that matches.
We can work with .distinct() [Django-doc] to prevent returning the same Project multiple times:
len(Project.objects.filter(
    Q(moderator='A') | Q(participant='B')
).distinct())
You can also work with .count() [Django-doc] to count at the database side, which is more efficient than counting at the Django/Python layer:
Project.objects.filter(
    Q(moderator='A') | Q(participant='B')
).distinct().count()


text:
Q: Search Table Column for a String without ID I am new to this...
I am looking to search a single column in a single table (No ID attached) on one page and I'm stumped. Everything I've found has to do with redrawing the table or getting the value. I'm not looking to do that or to replace any value. Basically I want to search a table for a string "Is Closed". If it is found, then I will show a button using $('button').show() or $('button').hide()
I am pretty sure I would have to do a $$(".table name") to find the table, correct? How do I go about searching the colum for "Is Closed" string
Looking to use only JS or prototype, no JQuery

A: searchstring = document.getElementsById('searchstring');
for (i=0, i<searchstring.length; i++) {
    if (searchstring.rows[i].cells[0] == givenValue) {
        alert('found string');
    }
}

A: You need to be able to identify the table somehow, ID or class will work, or if you are absolutely sure its going to be the only table on the page that will work too.
Table with an id
var results = $('tableid').select('td').filter(function(cell){
    return cell.innerHTML.match(/Is Closed/);
});

Table with a class
var results = $$('.tableclass').first().select('td').filter(function(cell){
    return cell.innerHTML.match(/Is Closed/);
});

Or only table on the page (I don't recommend you use this method)
var results = $$('table').first().select('td').filter(function(cell){
    return cell.innerHTML.match(/Is Closed/);
});

results will be an array of table cells that contain the words 'Is Closed'


text:
Q: angular-snap slide out menu i am newbie to angular snap. I have the following requirement:

*

*Slide out menu left side

*should contain sub menus

*Sub menus also should be collapsible.

Does angular snap will provide all these features?
I started working on example with angular snap slide out menu.
How do we give two different menus in the drawer and when the user clicks on menu1, main div should display page1 and when user clicks on menu2, main div should display page2.

A: Two small points:

*

*Angular.js is a framework for building single page applications.

*Snap.js is a library that provides a "shelf" like menu interface.

Angular Snap is simply an integration of these two components. You aren't limited from using normal JavaScript to show and hide elements on a page based on a users's click.
Rather than tell you how you should get Angular Snap specifically to do this, here's a way to implement a dropdown hide/show action in Angular, which is absolutely compatible with your Snap.js app instance.
Angular.js Dropdown
function dropdown($scope) {

    $scope.subitems = [
        {
            title: 'Menu item one',
            url: '#'
        },
        {
            title: 'Menu item two',
            url: '#'
        },
        {
            title: 'Menu item three',
            url: '#'
        },
        {
            title: 'Menu item four',
            url: '#'
        }
    ];
}

    Dropdown Menu

            {{subitem.title}}

To my earlier point, you shouldn't necessarily consider integrating this an end-all be all solution to your issue. There are probably simpler solutions in a few lines of JavaScript, and unless your menu items need to be dynamic, I wonder if it's isn't just producing extra overhead and debugging to have Angular produce markup that could be hard-coded.
Either way, I would take into account all of your requirements and go from there. Don't consider these libraries a limitation--there's no part of either of them that isn't JavaScript, so possibly consider other out of the box or easy to implement solutions that use simple tools that already exist in the browser.
EDIT: Borrowed some code from here


text:
Q: Trying to find amount of Saturdays that fall on the last day of each month in Ruby I am working on a very specific problem. I need to find the number of times that Saturday falls on the last day of each month within a five year time period.
For this example, I need to find those Saturdays from 1/1/1990 to 1/1/1995.
I've already tried the following code.
require 'active_support/core_ext'
require 'date'

beginDate = Date.parse("1/1/1990")

endDate = Date.parse("1/1/1995")

saturdays = beginDate.upto(endDate).count(&:saturday?) && beginDate.upto(endDate).count.end_of_month

puts saturdays

Does anyone have any suggestions or pointers?

A: You don't need any ruby-on-rails crap here in the first place. Plain ruby would perfectly do.
require 'date'
beginDate, endDate =
  Date.parse("1/1/1990"), Date.parse("1/1/1995")
(beginDate..endDate).count do |d|
  d.saturday? && d.month != (d + 1).month
end
#⇒ 9

A: Mobile, so can't test, but something like  (0..11).map.with_index { |i| date = Date.today + i.months; date.beginning_of_month if date.end_of_month.saturday? }.reject(&:nil?)


text:
Q: Question about number theory - divisibility by $2^n$ ($n$ is large)
Let $a,b,c,d,e$ five natural numbers ($a,b,c,d,e \in N$). We know that $2^{1386} |
 abcde$. (note that $a,b,c,d,e$ are not constant and we can choose
  them).
Find the largest $k \in N $ such that $2^k | a+b+c+d+e$.
note:the question didn't say $abcde = 2^{1386}$ but I think the answer is given by assuming this. So assume $abcde = 2^{1386}$

I know the answer is 280. But I don't know how to get to the answer. the first guess is 277 which $a=2^{277} , b=2^{277} , c = 2^{277} , d= 2^{277} , e= 2^{278}$
but it is not the right answer. I want to know how to get to 280. Please not just give an example and give a solution for finding that specific example or for finding $k = 280$.

A: We can build bigger powers of two from smaller ones, for example:
$$2^6 = 2^5+2^5 = 2^5+2^4+2^4 = 2^5+2^4+2^3+2^3 = 2^5+2^4+2^3+2^2+2^2$$
So in general this kind of 5-term partition gives
$$2^{k+4} = 2^{k+3} + 2^{k+2} + 2^{k+1} + 2^{k} + 2^{k}$$
It's clear that multiplying those $5$ terms of the addition gives $2^{5k+6}$.
Do you see how to apply this to your problem?

A: For every $k\ge 278$ , we can choose $a=b=c=d=e=2^k$, doing the job.
Therefore, there is no largest $k$


text:
Q: Automate a series of actions done on a single .csv file to all .csv files within the same directory in R I'm working on a research project where I need to process data from a pair of tactile gloves. After exporting the data, there are 4 rows containing date and time that I don't need when doing analysis after, and there are a lot of columns that I also don't need. Long story short, I needed to delete the first 4 rows and only keep columns [1,2,33,53,76,95,114,133,164,184,207,226,245]. I wrote a pretty simple R script to do it for me, but I'm wondering how can I apply this set of operations to all .csv files in the same directory? Manually typing each file name every time is pretty painful. Thank you in advance!
# read uncleaned, raw, data
uncleaned_data<-read.csv("C:/Users/jiang/Desktop/Ready_Clean/Hongjiao_Medium_High1.csv", header = FALSE)

# remove the date and time headers
data_without_head<-uncleaned_data[-c(1,2,3,4),]

# extract the useful columns
cleaned_data<-data_without_head[,c(1,2,33,53,76,95,114,133,164,184,207,226,245)]

# write the new cleaned data into a new file name (adding "_cleaned" in the end)
write.table(cleaned_data,"C:/Users/jiang/Desktop/Ready_Clean/Hongjiao_Medium_High1_Cleaned.csv",row.names=FALSE,col.names=FALSE,sep=",")

A: You can list all the files in the directory and then filter the ones ending with .csv:
I assumed that your directory path is "C:/Users/jiang/Desktop/Ready_Clean/"
unfortunately i cant test the code in my pc but let me know if you have some questions.
library(tidyverse)
library(stringr)

#get all the .csvs present in the directory and then fabricate the new names just by appending '_cleaned' before .csv

paths <- list.files(path = "C:/Users/jiang/Desktop/Ready_Clean/") %>%
          str_subset(pattern = '.csv$') #capture all the files ending in .csv

paths <- str_c("C:/Users/jiang/Desktop/Ready_Clean/", paths)

paths_cleaned <- str_replace(paths, '.csv$', '_cleaned.csv')

get_csv <- function(path, path_clean){
    # read uncleaned, raw, data
    uncleaned_data    <- read.csv(path, header = FALSE)

    # remove the date and time headers
    data_without_head <- uncleaned_data[-c(1,2,3,4),]

    # extract the useful columns
    cleaned_data      <- data_without_head[, c(1,2,33,53,76,95,114,133,164,184,207,226,245)]

    # write the new cleaned data into a new file name (adding "_cleaned" in the end)
    write.table(cleaned_data,
                path_clean,
                row.names = FALSE,
                col.names = FALSE,
                sep = ",")
}

#walk2 would also be an option because we only care of side-effects here.
map2(path, path_cleaned, ~get_csv(.x, .y))

A: A Base R solution looks like this. First, we use list.files() to extract files ending with .csv, then use use the file list to drive lapply() to read the data, subset it, and write with write.table().
theFiles <- list.files(path="C:/Users/jiang/Desktop/Ready_Clean/",
                       pattern="\\.csv$",full.names=TRUE)
dataList <- lapply(theFiles,function(x){
     y <- read.csv(x,skip = 4,header=FALSE)[c(1,2,33,53,76,95,114,133,164,184,207,226,245)]
     write.table(y,paste0(x,".cleaned"))
})

Note that we use the skip = argument to skip the first four rows when reading each file, then immediately subset the object created by read.csv() via the [ form of the extract operator.
in the write.table() operation we use paste0() to append .cleaned to each original file name to distinguish the cleaned files from the originals.
Since the original question does not include a minimal reproducible example, we'll use the data from my Pokémon Stats GitHub repository to illustrate the solution.
The dimensionality of the Pokémon stats data is much different from the data described in the original question, so we'll skip the first four rows of each file, and retain only columns 1, 2, 4, and 6.
download.file("https://raw.githubusercontent.com/lgreski/pokemonData/master/PokemonData.zip",
                  "pokemonData.zip",mode="wb")
    unzip("pokemonData.zip",exdir="./pokemonData")

theFiles <- list.files("./pokemonData",pattern="\\.csv$",full.names=TRUE)
dataList <- lapply(theFiles,function(x){
     y <- read.csv(x,skip = 4,header=FALSE)[c(1,2,4,6)]
     write.table(y,file=paste0(x,".cleaned"),row.names=FALSE,col.names=FALSE,sep=",")
})

A screenshot of one of the original files can be used to verify the output. I have highlighted columns 1, 2, 4, and 6, starting with the fourth row of input (including the header row).

...and the output for the first few rows of ./pokemonData/gen01.csv.cleaned is:
4,"Charmander","Fire",309
5,"Charmeleon","Fire",405
6,"Charizard","Fire",534
7,"Squirtle","Water",314
8,"Wartortle","Water",405
9,"Blastoise","Water",530

The file gen01.csv contains the first generation Pokémon. The first three Pokémon in this file are Bulbasaur, Ivysaur, and Vensuaur. We can see from the output that these Pokémon and the header row in the original file were skipped, so the first observation is Pokémon 4, Charmander. We also see that the Total stat, the sixth column, matches the input file for the rows that have been written to the output file.
Validating the written files
Because we appended .cleaned at the end of each file we can use the same technique to list the .cleaned files as we did to list the .csv files and read them with read.csv(). This allows us to keep the original files distanct from the cleaned files.
# now read the cleaned files
theFiles <- list.files("./pokemonData",pattern="\\.cleaned$",full.names=TRUE)
dataList <- lapply(theFiles,read.csv,header=FALSE)
head(dataList[[1]])

At this point the dataList object is a list() that contains 8 data frames, one for each generation of Pokémon.
We use head() to print the first few rows of the first data frame in the list, which matches the results above:
> head(dataList[[1]])
  V1         V2    V3  V4
1  4 Charmander  Fire 309
2  5 Charmeleon  Fire 405
3  6  Charizard  Fire 534
4  7   Squirtle Water 314
5  8  Wartortle Water 405
6  9  Blastoise Water 530

Writing the cleaned files to a separate directory
Per the request made in the comments to my answer, here is a solution that creates a /cleaned subdirectory within the directory where the files were originally stored, and writes the files to that directory.
First, we create objects for the input and output directories. Then we create a new subdirectory for the output files if it does not already exist.
# solution that creates a ./cleaned subdirectory

inputDirectory <- "./pokemonData"
outputDirectory <- paste0(inputDirectory,"/cleaned")
if(!dir.exists(outputDirectory)) dir.create(outputDirectory)

By checking whether the directory exists before attempting to create it, we eliminate errors on the second and subsequent runs of this script.
Next, we list the files in the input directory. Because we're doing to use the inputDirectory and outputDirectory objects later in the script to manually build the full path names for each input and output file, we set the full.names= argument of list.files() to FALSE.
theFiles <- list.files(inputDirectory,pattern="\\.csv$",full.names=FALSE)

Next, we use lapply() to read the files, subset the right rows and columns, and write the cleaned files to the output directory.
dataList <- lapply(theFiles,function(x){
     y <- read.csv(paste0(inputDirectory,"/",x),skip = 4,header=FALSE)[c(1,2,4,6)]
     write.table(y,file=paste0(outputDirectory,"/",x),row.names=FALSE,col.names=FALSE,sep=",")
})

# verify that files were written to cleaned directory
list.files(outputDirectory,full.names=TRUE)

...and the output:
> list.files(outputDirectory,full.names=TRUE)
[1] "./pokemonData/cleaned/gen01.csv" "./pokemonData/cleaned/gen02.csv"
[3] "./pokemonData/cleaned/gen03.csv" "./pokemonData/cleaned/gen04.csv"
[5] "./pokemonData/cleaned/gen05.csv" "./pokemonData/cleaned/gen06.csv"
[7] "./pokemonData/cleaned/gen07.csv" "./pokemonData/cleaned/gen08.csv"
>

Appendix
Since commenters are asserting that the dots in the file names in paste0() aren't being rendered correctly, the following screenshot of the subdirectory demonstrates that the code does indeed work as I intended.

A: Hi I did some coding for you to answer your question.

*

*first set working directory

*list all the files you need to process. My assumption here is all files starts with "Hongjiao_Medium_High" and then there is some number

*use FOR loop over the list of file names to iterate

*pasted your code inside the FOR loop with some tweaks

Below is the code :
setwd("C:/Users/jiang/Desktop/Ready_Clean")
list_of_file_names <- list.files(pattern = "*png")

for(i in list_of_file_names){
  # read uncleaned, raw, data
  print(i)
  uncleaned_data<-read.csv( i , header = FALSE)

  # remove the date and time headers
  data_without_head<-uncleaned_data[-c(1,2,3,4),]

  # extract the useful columns
  cleaned_data<-data_without_head[,c(1,2,33,53,76,95,114,133,164,184,207,226,245)]

  # write the new cleaned data into a new file name (adding "_cleaned" in the end)
  write.table(cleaned_data,paste(i,"_Cleaned.csv"),row.names=FALSE,col.names=FALSE,sep=",")
}


text:
Q: Remove empty row from array in javascript I am trying to check and remove any empty row in my table mapped to an array in javascript.
Sample array would be like below.
1   2   3
4   5   6

7   8   9

Now this array is having 4 rows and 3rd one is empty which I want to remove. How to do that. I tried using  if(adata[i]) is not null, but that wont work since an indivdual value can be null. i want to check for complete row being null

A: This short code should match your requirement :
var input = [[1,,3], [11,, ,12], [,,,,,], [37,38,39]];
var result = input.filter(element => element.join("") != "");
console.log(result); // [ [ 1, , 3 ], [ 11, , , 12 ], [ 37, 38, 39 ] ]

Edit : for ES5 you'll write rather
var result = input.filter(function(element) {return element.join("") != ""});


text:
Q: How to write regular expression for this case? I want to write a regular expression in javascript to match the following valid scenarios. later on, If I have to extract using a group then I will be able to do so.
I have tried the below regex, but it not giving me the desired pattern.
/[0-9][+-[0-9]+]*/
Regex should be able to match the "Valid" scenarios.

// Valid
64344
   9434
  434-543
434-543
434  -   543
4435 - 343434
1-2,3,5,6
1-2,3,5,6-6,45-4
3,5,6, 8 -  9,24
   1-2,3,5 ,6
1-  2,3,  5,6-6,45-4

// Invalid
23 -
2343.3434
343.3434 - 13.466
23 ,
234,
,54
xyz   9
3,5,6,8-9,24,
,35,65,65
,35,65,65 -
,3  5,65,65,
3,5,6, 8-  9,24,
1-  2,3,  5,6-6,4 5-4
,  35,65,6 5
,35,  6  5,65,

A: Looking at your samples, I feel what you want is a comma separated numbers where some of which can be ranged like 1-2 and also having optional spaces between them and also at start or end of string. Here is a regex you can use,
^\s*\d+(?:\s*-\s*\d+\s*)?(?:\s*,\s*\d+(?:\s*-\s*\d+)?)*\s*$

Explanation:

*

*^ - Start of string

*\s* - optional space at start of input

*\d+ - Matches one or more just number

*(?:\s*-\s*\d+\s*)? - This matches a ranged number like this -2 which can have spaces within it and ? at the end means ranged part is optional

*(?:\s*,\s*\d+(?:\s*-\s*\d+)?)* - This regex part ensures that the numbers can be comma separated and \d+(?:\s*-\s*\d+)? part in it enables numbers of 2-3 form where ? in it indicates that it can be just pure number without having ranged part and * whole of this can be zero or more times

*\s* - optional space at the end of input

*$ - end of input

Live Demo


text:
Q: How to store multi select values in Laravel 5.2 I have a form which stores News.

Here I am using Multiselect and I want to save all the selected option in the table as say  Users,staff,cinemahall as a string.
My controller function to store values is
 public function store(Request $request)
{

    $input=$request->all();

    General_news::create($input);
    return redirect()->back();
}

This function store the all submitted fields but for multiselect it stores only last option i.e cinemahall

When form is submitted all selected options are displayed but it's not saving in database table properly.
help me to solve this issue.

A: Make sure you set the name attribute to an array
<select multiple="multiple" name="news[]" id="news">

To store it as string separated by commas
$news = $request->input('news');
$news = implode(',', $news);

You have a string which will look like Users,staff,cinemahall. Now, instead to retrieve all input, you may need to retrieve it one by one, since you need to mutate the news value. Additionally, you can also use except() method to exclude news from mass getting all value.
$news = $request->input('news');
$news = implode(',', $news);

$input = $request->except('news');
//Assign the "mutated" news value to $input
$input['news'] = $news;

General_news::create($input);
return redirect()->back();

A: Thanks @Chay22
you could also use Mutators and  Accessor https://laravel.com/docs/5.4/eloquent-mutators#defining-an-accessor
public function setFooAttribute($value)
{
    $this->attributes['foo'] = implode(',',$value);
}

public function getFooAttribute($value)
{
    return explode(',',$value);
}

A: If you are using a multiselect, that probably means that you need a many to many relationship and a pivot table. Kind of like how posts can belong to many tags and tags can belong to many posts.
In your case this would probably be between news and the news_types tables.


text:
Q: How to Edit text function in React Hooks CRUD app? example note taking / todo app? I'm learning React with Hooks and context. Learning by making a simple CRUD app. I have functions that allow me to ADD notes, DELETE notes, Filter if important, Toggle importance in some Context. So far so good.
However I'm stuck on how I would be able to edit my note. I've searched online and every react hooks CRUD tutorial seems to just be add and delete.
My functions for a CRUD note taking app below.
import React, { createContext, useState, useEffect } from 'react';

import uuid from 'uuid/v1';

export const NotesContext = createContext();

const NotesContextProvider = (props) => {
  const [notes, setNotes] = useState([]);
  const [showAll, setShowAll] = useState(true);

  const notesToShow = showAll ? notes : notes.filter((note) => note.important);

  //CRUD operations

  // Create
  const addNote = (content) => {
    setNotes([
      ...notes,
      {
        content,
        id: uuid(),
        important: false
      }
    ]);
  };

  // Update
  const toggleImportance = (noteId) => {
    const updatedNotes = notes.map((note) =>
      note.id === noteId ? { ...note, important: !note.important } : note
    );
    setNotes(updatedNotes);
  };

  // Delete
  const removeNote = (id) => {
    setNotes(notes.filter((note) => note.id !== id));
  };

  // Get any notes stored in local storage
  useEffect(() => {
    const data = localStorage.getItem('notes');
    if (data) {
      setNotes(JSON.parse(data));
    }
  }, []);

  // save notes to local storage
  useEffect(() => {
    localStorage.setItem('notes', JSON.stringify(notes));
  }, [notes]);

  return (
    <NotesContext.Provider
      value={{
        addNote,
        removeNote,
        notes,
        showAll,
        setShowAll,
        notesToShow,
        toggleImportance
      }}>
      {props.children}
    </NotesContext.Provider>
  );
};
export default NotesContextProvider;

I'm hoping to have an onClick on an edit button on my note/todo and it'll allow me to update the note/todo.
Thanks any guidance would be appreciated.


text:
Q: YouTube not working on 32 Bit Ubuntu 14.04 I am using Ubuntu 14.04 on a 32 Bit PC. For the past two or three days neither of my browsers (Firefox & Chromium) is able to play Youtube.
I see this message:

"pubads.g.doubleclick.net refused to connect"
How can I fix this?

A: The 32-bit of these browsers and the back-porting to 14.04 is pretty limited. My guess is that at some point some sunset dates on various technologies like what types of ciphers used to encrypt the HTTPS connection have passed and now those ciphers or certificate algorithms are no longer allowed by the server.
If you open the Inspector and go to Console (in both Firefox or Chrome it's almost the same) and try to load the page you should see an error or warning in the console explaining what support is no longer present.
It's a real pain too because 32-bit systems are left mostly just needing to be updated to 64-bit systems, even if they don't use more than 4GB of RAM etc. It's mostly because developers don't want to support both 32-bit and 64-bit and package managers also don't want to.
EDIT If you think this answer is wrong please explain why. I have multiple 32-bit systems I very much want the browser supported, but they aren't.


text:
Q: Java jsonrpc4j jsonRpcServer NoClassDefFoundError (Eclipse) I want to create a basic JSON-RPC server over TCP. To do this I found the project https://github.com/briandilley/jsonrpc4j. When I tried to create in Eclipse a basic Maven project using the jsonRpcServer (see App.java), the exception java.lang.NoClassDefFoundError pops-up. Any hints?
App.java
package com.sxtlcfi.maven;
import com.googlecode.jsonrpc4j.JsonRpcServer;

public class App {

    public static void main(String args[]){

        // create the jsonRpcServer
        UserServiceImpl userService = new UserServiceImpl();

        // actual runtime
        String[] arrOfClassPath = System.getProperty("java.class.path").split(";");
        for (String a : arrOfClassPath) System.out.println(a);

        //Issue: https://code.google.com/archive/p/jsonrpc4j/issues/64
        JsonRpcServer jsonRpcServer1 = new JsonRpcServer(userService);
        //Exception in thread "main" java.lang.NoClassDefFoundError: javax/servlet/ServletOutputStream
        //at com.sxtlcfi.maven.App.main(App.java:60)
        //Caused by: java.lang.ClassNotFoundException: javax.servlet.ServletOutputStream
        //  at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641)
        //  at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188)
        //  at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520)
        //  ... 1 more

        //System.out.println(UserService.class.getMethods()[0].getName());
        //JsonRpcServer jsonRpcServer2 = new JsonRpcServer(userService, UserService.class);
    }
}

UserService.java
package com.sxtlcfi.maven;
public interface UserService {
    User createUser(String userName, String firstName, String password);
    User createUser(String userName, String password);
    User findUserByUserName(String userName);
    int getUserCount();
}

UserServiceImpl.java
package com.sxtlcfi.maven;

import java.util.ArrayList;

public class UserServiceImpl
    implements UserService {

    ArrayList<User> database = new ArrayList<User>();

    public User createUser(String userName, String firstName, String password) {
        User user = new User();
        user.setUserName(userName);
        user.setFirstName(firstName);
        user.setPassword(password);

        database.add(user);
        return user;
    }

    public User createUser(String userName, String password) {
        return this.createUser(userName, null, password);
    }

    public User findUserByUserName(String userName) {
        //return database.findUserByUserName(userName);
        for (int i = 0; i < database.size(); i++) {
            if(database.get(i).getUserName() == userName) {
                return database.get(i);
            }
        }
        return null;
    }

    public int getUserCount() {
        //return database.getUserCount();
        return database.size();
    }

}

User.java
package com.sxtlcfi.maven;

public class User {

    private String userName;
    private String firstName;
    private String password;

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUserName() {
        return userName;
    }

}

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.sxtlcfi.maven</groupId>
  <artifactId>maven-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <dependencies>
    <!-- https://mvnrepository.com/artifact/junit/junit -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.13.2</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.github.briandilley.jsonrpc4j/jsonrpc4j -->
    <dependency>
      <groupId>com.github.briandilley.jsonrpc4j</groupId>
      <artifactId>jsonrpc4j</artifactId>
      <version>1.6</version>
    </dependency>
  </dependencies>
</project>

A: I had the exact same issue. Managed to resolve it by adding these 2 dependencies to gradle:
 // https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api
implementation("javax.servlet:javax.servlet-api:4.0.1")

// https://mvnrepository.com/artifact/javax.portlet/portlet-api
compileOnly("javax.portlet:portlet-api:3.0.1")


text:
Q: What is a by statement really doing in a sas data step? Okay this seems like a very simple thing, but I can't explain what a "by statement" in a sas datastep is really doing.  I know when I need to use it, but I am not sure what it is doing.
In the example below I understand what the virtual sas column of first.var and last.var is when it has the values that it does.  Is the by statement creating these virtual columns around the var initial and metal?  Then sas is scanning the entire data set once?
data jewelers ;
  input id initial $ metal $ ;
datalines;
456 D Gold
456 D Silver
123 L Gold
123 L Copper
123 L PLatinum
567 R Gold
567 R Gold
567 R Gold
345 A Platinum
345 A Silver
345 A Silver
;

proc sort ;
  by initial metal ;
run;

data dups;
  set jewelers ;
  by initial metal ;
  if not (first.metal and last.metal) then output;
run;

if I proc print dups I expect this:
567 R Gold
567 R Gold
567 R Gold
345 A Silver
345 A Silver

A: As you've acknowledged, SAS is creating the automatic variables first.byvar and last.byvar for each byvar in your by statement. Records read in from a set statement are held in a buffer before SAS moves them to the PDV (Program Data Vector - where data step logic is executed on each row before it is output), so SAS can look ahead to the next record in the buffer to see whether any of the byvars have changed, and set last.byvar = 1 for the row currently in the PDV.
The only difference I can see between what you say you expect and what you get in the dups dataset is the order of the records - because you've sorted by initial and then metal, the A Silver records are sorted ahead of the R Gold records.
If you want to get duplicates across these two variables while preserving the original row order, you'd need to make a note of what the original record order was and sort your duplicates dataset back into that order after your second data step.

A: SAS is basically comparing the current record to the one before and the one after to calculate the FIRST. and LAST. flags.  You can roll your own if you want.
data test ;
   set jewelers end=eof;
   by initial metal ;
   if not eof then
      set jewelers (firstobs=2 keep=initial metal
                    rename=(initial=next_initial metal=next_metal))
   ;
   first_initial = (_n_=1) or (initial ne lag(initial));
   last_initial = eof or (initial ne next_initial) ;
   first_metal = first_initial or (metal ne lag(metal)) ;
   last_metal = last_initial or (metal ne next_metal);
   put / (initial metal) (=);
   put (first:) (=);
   put (last:) (=);
run;


text:
Q: Gettimeofday not working when assigned to variable I have a simple timestamp issue. I am trying to get a timestamp using gettimeofday and it all works as it should when I print the value to the terminal however when I assign it to a variable it does not. I can not figure out what im doing wrong. The code and output looks as follows:
#include <stdio.h>
#include <sys/time.h>
#include <windows.h>

int main(int argc, char const *argv[])
{
    struct timeval t_struct;
    while(1){
        gettimeofday(&t_struct, NULL);
        printf("Print only: %f \n", (float) t_struct.tv_sec + (float) t_struct.tv_usec/1000000);
        float timestamp = (float) t_struct.tv_sec + (float) t_struct.tv_usec/1000000;
        printf("Assigned  : %f \n", timestamp);
        Sleep(100);
    }
    return 0;
}

Output:
Print only: 1598259371.284617
Assigned  : 1598259328.000000
Print only: 1598259371.385117
Assigned  : 1598259328.000000
Print only: 1598259371.485873
Assigned  : 1598259328.000000

Note that I am used to programming in Python and not C, I am aware that the issue might be trivial.

A: The solution was to change the variable type to double instead of float and I also changed the division to be /1000000.0 to avoid integer division.


text:
Q: How to combine two generic methods I have to two extensions:
public static IQueryable<T> Existing<T>(this IQueryable<T> qry)
    where T : class, IDeletable
{
    return qry.Where(...);
}

public static IEnumerable<T> Existing<T>(this IEnumerable<T> qry)
    where T : class, IDeletable
{
    return qry.Where(...);
}

How do I combine those two methods into one method? I tried the following:
public static TU Existing<TU, T>(this TU qry)
    where TU : class, IQueryable<T>, IEnumerable<T>
    where T : class, IDeletable
{
    return (TU)qry.Where(...);
}

But this doesn't work because the type can't be inferred correctly (because IQueryable inherits from IEnumerable, I guess). Moreover, T isn't always IQueryable, which also seems to be a problem here (question: if I specify multiple interfaces in the where clause, aren't those matched in a disjunctive manner?). In the previous case IQuerable was used if it suited or else IEnumerable. How can I circumvent this?

A: Your attempt will always limit it to IQueryable<T> implementations. I assume you really want it to work for both in-process queries and out-of-process queries. Assuming that the "..." in the Where clause is a lambda expression, you need to be aware that even if you have the same code in both methods, the compiler will be handling them very differently - because it will already have applied overload resolution to determine the Where implementation to use.
I would strongly advise you to leave the two separate overloads as they are.

A: public static IQueryable<T> Existing<T>(this IEnumerable<T> qry) where T : class, IDeletable
{
    return qry.Where(/*...*/).AsQueryable();
}

Calling AsQueryable on something that is already queryable will do nothing. Also, IQueryable inherits from IEnumerable, so first: you can pass an IQueryable to this method, and second: the result is actually an IEnumerable as well as an IQueryable.


text:
Q: How to set window size and position in trimesh I have trimesh 3.9.32 installed on Raspbian GNU/Linux 10 (buster) armv7l. This snippet:
import trimesh

mesh = trimesh.creation.cylinder(1, height=1)
mesh.show()

displays a window spilling into my second display. I would like to control window size and position. I tried to use trimesh.viewer.SceneViewer, but I'm getting AttributeError: module 'trimesh' has no attribute 'viewer'. What is a way to set window size and position or make it full screen on my primary display?

A: The following should fix your problem:
from trimesh import viewer
from trimesh.viewer import windowed

Source: https://github.com/mikedh/trimesh/issues/427


text:
Q: iOS Zoomview using Bubbleview touch location how to create bubble view for touch location ....(Xcode for iOS)
I had a problem with Zooming the image at certain location using bubbleview of touch location.
I wanna zoom certain location which I touch and that bubble have to display above my finger. But here it zooming upper location and bubble the upper location of my finger. How to zoom touch location and bubble it above my finger..?
UITouch *touch = [touches anyObject];
CGPoint touchLocation = [touch locationInView:self.view];
if (CGRectContainsPoint(self.MeterView.frame, touchLocation)) {
    _zoomView = [[BubbleView alloc] initWithFrame:CGRectMake(3, touchLocation.y-120, 120,120)];
    [_zoomView setZoomScale:2.0];
}

A: There are couple of very good projects on github which provides bubble zoom functionality where you move your finger.
They are,

*

*iOS-MagnifyingGlass

*BKZoomView
I hope it may help you.


text:
Q: Keep Logged in Users out of Admin Panel So I'm creating user registration. Just simply <?php wp_register(); ?> but then it gives them a link to the admin panel, which in my situation they really don't need. How do I remove the "Site Admin" link and redirect a subscriber if they try to access the admin panel? I guess once they log in I will need to redirect them to a certain page also.

A: So I found the answer and thought it might be useful for later viewers. Adding the code below will redirect all users that are not admin to the homepage.
function prevent_admin_access() {
    if (strpos(strtolower($_SERVER['REQUEST_URI']), '/wp-admin') !== false && !current_user_can('administrator')) {
        wp_redirect(get_option('siteurl'));
    }
}

add_action('init', 'prevent_admin_access', 0);

The only problem with this code is that the registration needs to be changed so the user can pick their own password.

A: You can remove the read capability from subscribers, which is what gives them access to the dashboard.  This is best done with an activation hook on a plugin -- it only needs to be done once.
<?php
register_activation_hook( __FILE__, 'wpse43054_activation' );
function wpse43054_activation()
{
    $role = get_role( 'subscriber' );
    if( $role ) $role->remove_cap( 'read' );
}

And, of course, you probably want to give that capability back on plugin deactivation.
<?php
register_deactivation_hook( __FILE__, 'wpse43054_deactivation' );
function wpse43054_deactivation()
{
    $role = get_role( 'subscriber' );
    if( $role ) $role->add_cap( 'read' );
}

Finally, you can hook into init and redirect folks if they are logged in, try to access the admin area and don't have the read capability.
<?php
add_action( 'init', 'wpse43054_maybe_redirect' );
function wpse43054_maybe_redirect()
{
    if( is_admin() && ! current_user_can( 'read' ) )
    {
        wp_redirect( home_url(), 302 );
        exit();
    }
}

You'll also probably want to remove the admin bar for users with a read capability.  You can do that by hooking into get_user_metadata and hijacking the check for the user meta value for show_admin_bar_front.
<?php
add_filter( 'get_user_metadata', 'wpse43054_hijack_admin_bar', 10, 3 );
function wpse43054_hijack_admin_bar( $null, $user_id, $key )
{
    if( 'show_admin_bar_front' != $key ) return null;
    if( ! current_user_can( 'read' ) ) return 0;
    return null;
}

All that as a plugin.


text:
Q: Ruby on rails console I have an issue with a nested model in my application. I can't get the values to show. I know I have to do it like this: @modelname.attribute (view), but it doesn't seem to work. That's why I started to look in the console if everything I did in the controller was right.
Everything seems ok. But I have one question, in the console, when you do this (example):
@modelname = Modelname.find(an id)

it gives you the corresponding object like this:
=>#< Modelname, id: x, other attributes >

and when I'm trying to find my other object in the console, I get this:
=>[#< Modelname, id: x, other attributes >]

Why? What's the difference and could that be my problem?

A: The second time –in the console– you're getting an array. That's the difference. As of why, we don't know what your wrote to find the model, but you must be calling ModelName.where or one fo the other methods in the ActiveRecord query API that returns an array (an ActiveRecord::Relation to be precise)


text:
Q: How can I prevent my functional component from re-rendering with React memo or React hooks? When hiddenLogo changes value, the component is re-rendered. I want this component to never re-render, even if its props change. With a class component I could do this by implementing sCU like so:
shouldComponentUpdate() {
  return false;
}

But is there a way to do with with React hooks/React memo?
Here's what my component looks like:
import React, { useEffect } from 'react';
import PropTypes from 'prop-types';

import ConnectedSpringLogo from '../../containers/ConnectedSpringLogo';

import { Wrapper, InnerWrapper } from './styles';
import TitleBar from '../../components/TitleBar';

const propTypes = {
  showLogo: PropTypes.func.isRequired,
  hideLogo: PropTypes.func.isRequired,
  hiddenLogo: PropTypes.bool.isRequired
};

const Splash = ({ showLogo, hideLogo, hiddenLogo }) => {
  useEffect(() => {
    if (hiddenLogo) {
      console.log('Logo has been hidden');
    }
    else {
      showLogo();

      setTimeout(() => {
        hideLogo();
      }, 5000);
    }
  }, [hiddenLogo]);

  return (
    <Wrapper>
      <TitleBar />
      <InnerWrapper>
        <ConnectedSpringLogo size="100" />
      </InnerWrapper>
    </Wrapper>
  );
};

Splash.propTypes = propTypes;

export default Splash;

A: As G.aziz said, React.memo functions similarly to pure component. However, you can also adjust its behavior by passing it a function which defines what counts as equal. Basically, this function is shouldComponentUpdate, except you return true if you want it to not render.
const areEqual = (prevProps, nextProps) => true;

const MyComponent = React.memo(props => {
  return /*whatever jsx you like */
}, areEqual);

A:  React.memo is same thing as React.PureComponent
You can use it when you don't want to update a component that you think is static so, Same thing as PureCompoment.
For class Components:
class MyComponents extends React.PureCompoment {}

For function Components:
const Mycomponents = React.memo(props => {
  return <div> No updates on this component when rendering </div>;
});

So it's just creating a component with React.memo

To verify that your component doesn't render you can just
  activate HightlightUpdates in react extension and check your components reaction on
  rendering

A: We can use memo for prevent render in function components for optimization goal only. According React document:

This method only exists as a performance optimization. Do not rely on it to "prevent" a render, as this can lead to bugs.

A: According to react documentation:- [https://reactjs.org/docs/react-api.html][1]

React. memo is a higher order component. If your component renders the
same result given the same props, you can wrap it in a call to React.
memo for a performance boost in some cases by memoizing the result.
This means that React will skip rendering the component, and reuse the
last rendered result.

For practical understanding I came across these two videos they are very good if you wanna clear concepts also, better to watch so it'll save your time.
Disclaimer:- This is not my YouTube channel.

*

*https://youtu.be/qySZIzZvZOY [ useMemo hook]

*https://youtu.be/7TaBhrnPH78 [class based component]


text:
Q: Display text in as you hover over different parts of a chart I have 2 donut charts in my application and I was wondering if it is possible to display text in the middle empty space as i hover over different parts of the donut charts. For instance both charts have different colours and each have their own percentage. So for instance if i hover over a certain color of the chart I would want to display a text in the middle. I was wondering what is the best way to do this as i am very bad with css and i do not want to do a simple hover over if there is better ways of doing this. Also if we are not hovering over the chart no text should be displayed.
Here is my code
var chart = c3.generate({
    bindto: "#chart",
    data: {
        columns: [
            ['rat', 30],
            ['bat', 50],
        ],
        type : 'donut'

    },
       legend: {
        show: false
    },

});

var chart = c3.generate({
    bindto: "#chart1",
       size: {
        height: 200,
        width: 450
    },
    data: {
        columns: [
            ['cat', 50],
            ['mat', 50],
        ],
        type : 'donut'

    },
      legend: {
        show: false
    },

});

This is my FIDDLE

A: According to reference, you can specify onmouseover and onmouseout handlers to c3.generate, which also get an element under cursor in arguments, then you can show/hide some text in the center, for example: http://jsfiddle.net/Lccmvysr/1/


text:
Q: Tracking in chapter titles with titlesec I've been trying to add tracking (letter spacing) to my chapter titles with titlesec, but to no avail.
I'm using fontspec and XeTeX, so microtype isn't available to me. Another post said this can be done with \addfontfeatures{LetterSpace=XXX}, but the tracking remains the same.
I'm a TeX newbie, so I'm not sure where the error is in my MWE.
Here's an image and the code I used to produce it:

\documentclass{book}
\usepackage{lipsum}
\usepackage{fontspec}
\usepackage{titlesec}
\usepackage{fmtcount}

\newcommand{\ttlspc}{\addfontfeatures{LetterSpace=20}}
\titleformat{\chapter}[display]{}
    {\ttlspc\filcenter\normalfont\Large\bfseries Part\ \Numberstringnum{\thechapter}}
    {.2cm}
    {\ttlspc\normalfont\Large\itshape\filcenter}

\begin{document}
\chapter{TheNameOfTheChapter}
\lipsum[1]
\end{document}

What can be done to solve my problem?

A: There are two problems; one is minor and is in the fact that you must declare \setmainfont in order to apply \addfontfeatures.
The second problem is due to the fact that you're overriding \ttlspc by saying `\normalfont after it.
\documentclass{book}
\usepackage{lipsum}
\usepackage{fontspec}
\usepackage{titlesec}
\usepackage{fmtcount}

\setmainfont{Latin Modern Roman} % or whatever font

\newcommand{\ttlspc}{\addfontfeatures{LetterSpace=20}}
\titleformat{\chapter}[display]{}
    {\filcenter\normalfont\ttlspc\Large\bfseries Part\ \Numberstringnum{\thechapter}}
    {.2cm}
    {\normalfont\ttlspc\Large\itshape\filcenter}

\begin{document}
\chapter{TheNameOfTheChapter}
\lipsum[1]
\end{document}

Don't use letter spacing unless you're doing all caps or caps and small caps: see http://webtypography.net/2.1.7
Here's a possibility with spaced small caps:
\documentclass{book}
\usepackage{lipsum}
\usepackage{fontspec}
\usepackage{titlesec}
\usepackage{fmtcount}
\setmainfont{Hoefler Text}
\newfontfamily{\romanspaced}{Hoefler Text}[
  LetterSpace=15
]

\newcommand{\ttlspc}{\addfontfeatures{LetterSpace=20}}
\titleformat{\chapter}[display]{}
    {\filcenter\normalfont\romanspaced\Large\scshape Part\ \Numberstringnum{\thechapter}}
    {.2cm}
    {\normalfont\normalsize\romanspaced\scshape\filcenter}

\begin{document}

\chapter{The Name Of The Chapter}

\lipsum[1]

\end{document}


text:
Q: How do I make a specific page section visible based on the querystring I want to have a page with 3 sections:
<?php
session_start();
if (isset($_SESSION['login'])) {
    echo "Work";
    $_GET['id'] = 'edit';
?>
Edit post
<?php
}
else {
    echo "notWork";
}
if (isset($_GET['id']) && $_GET['id'] == 'edit') {
    echo "Editing  . . .";
}?>

But I have no idea how to do that page "Edit", will be visible only when we go link protected.php?if=edit.

A: ok.simply check your page referer with this code :
$_SERVER['HTTP_REFERER']

more documentation here
http://php.net/manual/en/reserved.variables.server.php

A: I think you should use $_GET['if'] instead of $_GET['id'] as the url parameter is named if.

A: So, if I go to page protected.php and the parameter if is edit, please change the code. There's a typo!
<?php
    if (isset($_GET['if']) && $_GET['if'] == 'edit') {
        echo "Editing  . . .";
    }
?>

A: You could include the edit-page according to the id you passed through the URL.
Something like: if($_GET['id'] == edit) include('edit.php')
However, doing so without further checks, everybody could see the page just by guessing the right value for id. Because of this you'd rather do a check against the user rights every time you include something.

A: If you want read passed value from url, you can use $_GET['if'] or $_REQUEST['if'] to get that value.
Also as you said "page with 3 sections", so i think you want to be show only on section at time then you should use elseif => http://php.net/manual/en/control-structures.elseif.php


text:
Q: Selector not called on selecting menu item after force touch I have this code, for responding to a menu item being tapped after a force touch:
class InterfaceController: WKInterfaceController {
    override init() {
        super.init()

        self.addMenuItemWithItemIcon(WKMenuItemIcon.Pause, title: "Pause", action: Selector("test"))
    }

    func test() {
        print("test")
    }
}

When I force touch, the menu appears. When I tap the "Pause" button, test() is not called.
Any ideas why this might be?

A: Solved.
Though its the result of a silly mistake (aren't most problems?), I think this is something a lot of people will run into, so I'll keep it here with my answer.
I enabled force touch on the simulator, so I could show the menu. When I'm tapping again on the button, force touch is still enabled, so I'm force touching, thus dismissing the menu.
Solution: Disable force touch before tapping a menu button.

A: I wanted to comment with my thanks for this solution but I don't have the rep so I'll begin with, THANKS!
However I can also add an addendum to the solution by pointing out the shortcut keys are really handy here for switching between force press pressures.
⇧⌘1 - for shallow pressure (tap)
⇧⌘2 - for deep pressure (force press)
Make sure the iOS Simulator (watch) is focussed and you'll be good to go.

A: I'd like to add a small detail to make the SIM procedure more explicit because I actually saw this question and answer before and didn't perform it correctly because it wasn't totally obvious (to me at least).

*

*Press ⇧⌘1 for all regular presses.

*Press ⇧⌘2 before you use force touch.

*Tricky part: After the menu item appears press ⇧⌘1 again before dismissing the menu item!


text:
Q: Inno Setup - Set Default Component depending on System Language I'm relatively new to InnoSetup so excuse me if I'm missing something.
Situation: My program is organized into selectable components. "Core Component" and "Language Component" (and some other which are irrelevant here). The "Language Component" contains "English", "Spanish", and some more.. The setup is localized in all languages that the components support.
What I'm trying to achieve: When the user has for example a Spanish OS and selects the Spanish language for the setup, I want the "Language Component > Spanish" to be selected automatically BY DEFAULT, but the user still be able to select an other language for my programm even if the setup is in Spanish.
What it does right now: Right now the first language element is selected by default which is "English" as it is the first element. The user has to specifically select "Spanish" or other no matter what language is being used for the setup.
Question: Is it possible to make Inno Setup select or check components depending on the setup locale?
Demo Code:
[Setup]
AppName=My App
AppVersion=1.0
DefaultDirName={pf}\My App

[Components]
Name: "core_files"; Description: "Core Component"; Types: full compact custom; Flags: fixed
Name: "lang_files"; Description: "Language Component"; Types: full compact custom; Flags: fixed
Name: "lang_files\en"; Description: "English"; Flags: exclusive
Name: "lang_files\es"; Description: "Spanish"; Flags: exclusive;

[Files]
;Source: "Files\*"; DestDir: "{app}"; Components: game_files
;Source: "Files_EN\*"; DestDir: "{app}"; Components: lang_files\en
;Source: "Files_ES\*"; DestDir: "{app}"; Components: lang_files\es

[Icons]
Name: "{group}\My Program"; Filename: "{app}\MyProg.exe"

[Languages]
Name: "en"; MessagesFile: "compiler:Default.isl"
Name: "es"; MessagesFile: "compiler:Languages\Spanish.isl"

Please note:
Using this does not seems to have any effect:
Name: "lang_files\es"; Description: "Spanish"; Languages: es; Flags: exclusive;

Using this is not an option for me, as the user cannot select an other language during installation, the only option for him would be changing the whole setup language if he wants to change my app language.
Source: "Files_ES\*"; DestDir: "{app}"; Languages: es; Components: lang_files\es

Conclusion:
I hope there is some way to make this work. I was wondering why setting the language on the "Component" is being ignored or has just no effect but still does not show any errors while compiling. Maybe something like this would be possible in the [Code] section but I don't know anything about Pascal.
Any help or pointing me in the right direction is highly apreciated.
Greetings.

A: SOLUTION: Hello everybody, thanks for the help. With a bit of google, brain and a lot of failed compiles I finally cold hack up some reasonably good looking solution.
Here is the code in case somebody would find it useful:
[Setup]
AppName=My App
AppVersion=1.0
DefaultDirName={pf}\My App

[Types]
Name: "full_en"; Description: "Full installation"; Languages: en;
Name: "full_es"; Description: "Full installation"; Languages: es;
Name: "custom"; Description: "Custom installation"; Flags: iscustom
; Full installation (With all languages)
#define full "full_en full_es"

[Components]
Name: "core_files"; Description: "Core Component"; Types: {#full} custom; Flags: fixed
Name: "lang_files"; Description: "Language Component"; Types: {#full} custom; Flags: fixed
Name: "lang_files\en"; Description: "English"; Types: full_en custom; Flags: exclusive
Name: "lang_files\es"; Description: "Spanish"; Types: full_es custom; Flags: exclusive;

[Files]
;Source: "Files\*"; DestDir: "{app}"; Components: game_files
;Source: "Files_EN\*"; DestDir: "{app}"; Components: lang_files\en
;Source: "Files_ES\*"; DestDir: "{app}"; Components: lang_files\es

[Icons]
Name: "{group}\My Program"; Filename: "{app}\MyProg.exe"

[Languages]
Name: "en"; MessagesFile: "compiler:Default.isl"
Name: "es"; MessagesFile: "compiler:Languages\Spanish.isl"

I'm using "Installation Types" to check the languages by default. This solution seems to work quite well for me right and works whichout mayor Pascal coding. As drawback is that it Requires per-language installation types, which can get quite big if you include many languages. I wonder if there is some other more elegand and compact way to do that.
Greetings and thanks for the help!
UPDATED: No pascal scripting involved at all now..
UPDATED 2: Using ISPP to avoid duplication, easier use and better readability using all languages for an element.

A: From this page (http://www.jrsoftware.org/ishelp/index.php?topic=languagessection) I read this information:
"If the ShowLanguageDialog [Setup] section directive is set to yes (the default), a Select Language dialog will be displayed which gives the user an opportunity to override the language Setup chose. On non Unicode Inno Setup languages that can't be displayed properly on the user's system will be hidden. See the [LangOptions] section help topic for details."


text:
Q: Can I use a serial port as TCP/IP interface on Red Hat Linux? Background
We want to run an FTP server on a Red Hat Enterprise OS. The problem is, the machine we have does not have an Ethernet port/interface (please don't ask why; it's just a project requirement).
We only have a serial port.
Question
Is there COTS / open source software that I can use to make serial port "look" like a an Ethernet port? My project is commercial. We run Red Hat Enterprise Linux 5.3.
Note:
Pardon me if my post title is unclear. If you can think of a better title, please suggest or simply change the title.

A: You should also be able to use PPP (point-to-point protocol) to another endpoint over a serial connection.

A: I found a couple of things, but I'm not sure if it's the answer to my question. Please comment as you see fit:

*

*ser2net

*Eltima Serial To Ethernet
I also found another question asked on SO, but I'm not sure if it's related to what I'm trying to do:


text:
Q: Purple Screen after trying to boot into Ubuntu 16.04 LTS I flashed the Ubuntu iso onto my USB, booted into it and now a purple screen is happening.  Picture linked: https://imgur.com/HLjxMMj

A: It seems the boot process is stuck at some point. Potential culprits are often graphic drivers. Maybe you can use the recovery mode (if that's available when booting from USB).
Alternatively, press the Esc-key to see what is going on in the background. Or you can try CTRL-ALT-T to open a terminal for obtaining further information.


text:
Q: How to open an uploaded PDF-file using Vue.js I have a vue.js code to upload and delete files:
export default {
    name: "FileUpload",
    methods: {
        addFile() {
            if (this.multiple) {
                let files = _.concat(
                    this.files,
                    Array.from(this.$refs[this.label].files)
                );
                this.$emit("update:files", files);
            } else {
                this.$emit("update:file", this.$refs[this.label].files[0]);
            }
        },
        removeFile(idx) {
            if (this.multiple) {
                _.pullAt(this.files, [idx]);
                this.$emit("update:files", this.files);
            } else {
                this.$emit("update:file", null);
            }
        },
    }
}

What should I add to have the possibility to open uploaded files directly in the browser?


text:
Q: JavaScript if answer is correct, generate new string I have a program that randomly generates two numbers (x and y) and asks the user to multiply them. Once they multiply them, it will tell them if they get it right or wrong. The thing I'm having problems with is that if they get the answer correct, it should then generate a new set of numbers. I'm not sure how to make the program perform that function again. Also it has to clear the answer field no matter if they get it right or wrong. Thanks!
var x, y; // global variables for randomly generated numbers
var correct = ['Very good!', 'Excellent!', 'Correct - Nice work!', 'Correct - Keep up the good work!'];
var incorrect = ['No. please try again.', 'Wrong. Try once more.', 'Incorrect - Dont give up!', 'No - Keep trying.'];

// getting two random numbers between 1-12 then assigning them to x and y

function generateNumbers() {
    function aNumber() {
        return Math.floor((Math.random() * 12) + 1);
    }
    x = aNumber();
    y = aNumber();
}

// generating the question that will be used with the random numbers x and y
function genQuestion() {
    generateNumbers();
    document.getElementById('question').value = x + " times " + y;
}

// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything
function buttonPressed() {
    var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct
    var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect
    var answer = document.getElementById('answer').value;

    if (answer == x * y) // correct
        {
            function genQuestion() {
                generateNumbers();
                document.getElementById('question').value = x + " times " + y;
            }
            window.alert(correctans);
            var total = document.getElementById('total').value++;
        }
    else {              // incorrect
        window.alert(incorrectans);
    }
}

A: You're not calling the genQuestion function, and it makes little sense to redefine it.
// function that is performed when the button "check answer" is clicked. It will generate one of 4 answers depending
//if it's right or wrong and will add 1 to the value of total. If it's incorrect it won't add anything
function buttonPressed() {
    var correctans = correct[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's correct
    var incorrectans = incorrect[Math.floor(Math.random() * 4)]; // randomly selecting an answer if it's incorrect
    var answer = document.getElementById('answer').value;

    if (answer == x * y) // correct
        {
            //call genQuestion to create new question
            genQuestion();
            window.alert(correctans);
            var total = parseInt(document.getElementById('total').value)++;
        }
    else {              // incorrect
        window.alert(incorrectans);
    }
    //clear 'answer' field
    document.getElementById('answer').value = '';
}


text:
Q: spring acl in jsf i've just build in spring-security-acl into my system, how can i call the "hasPermission" el-function from my xhtml pages?
e.g.
<f:subview rendered="#{hasPermission(object,'read')}">
   HELLO
</f:subview>

i just get
javax.el.ELException: Function 'sec:hasPermission' not found

i'm running on tomcat

A: Define a taglib for the spring-security function.Then access the spring function with expression language like #{prefix:function(params)}
Refer the link Spring Security Taglib and JSF


text:
Q: CLEditor Multiple Instances resize with 100% width I've successfully implemented the CLEditor with 100% width but I can't seem to get around the the resize firing off endlessly.
    //Initialize WYSIWYG
    var editorTextarea1 = $('#registration-confirmation'),
    editorWrapper1 = editorTextarea1.parent(),
    editor1 = editorTextarea1.cleditor({
        width:  '100%',
        height: 350
    })[0];

    // Update size when resizing
    editorWrapper1.sizechange(function()
    {
        editor1.refresh();
    });

    var editorTextarea2 = $('#thank-you-message'),
    editorWrapper2 = editorTextarea2.parent(),
    editor2 = editorTextarea2.cleditor({
        width:  '100%',
        height: 350
    })[0];

    // Update size when resizing
    editorWrapper2.sizechange(function()
    {
        editor2.refresh();
    });


text:
Q: How do I find Bluetooth in my BIOS?
Possible Duplicate:
Deactivate Bluetooth on startup

I want to permanently disable Bluetooth, which I can't seem to do from the OS anymore.
I've read that I need to make the change in my BIOS but I've gone through every setting in the BIOS and I don't see anything that rhymes with Bluetooth.
How do I stop it from launching on startup?

A: Quite often BIOS has two sets of options. Ordinary and Advanced. To see advanced set You have to use some key combination (in my case it is Ctrl+F1) and then appear much more options. To find out if You have such possibility You have to read Your mainboar manual.
Regards