text:
Q: Error building custom Docker image with Postgres and security updates: "configuration file createcluster.conf is available" I have a Dockerfile that builds an image based on postgres, but additionally installs security updates (this is to ensure that the image has the latest patches even if a release is slightly older).
This is the Dockerfile:
FROM postgres:14.2

# apply security updates
RUN \
  apt-get update -qq && \
  apt-get upgrade -y && \
  rm -rf /var/lib/apt/lists/*

ENV PGDATA /var/lib/postgresql/data

# switch to lower-privileged user
USER 999

CMD ["postgres", "-c", "listen_addresses=*", "-c", "config_file=/etc/postgresql/postgresql.conf"]

Now, this build broke:
Reading package lists...
Building dependency tree...
Reading state information...
Calculating upgrade...
The following packages will be upgraded:
  libpq5 postgresql-14 postgresql-client-14 postgresql-client-common
  postgresql-common
5 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.
Need to get 17.9 MB of archives.
After this operation, 25.6 kB of additional disk space will be used.
Get:1 http://apt.postgresql.org/pub/repos/apt bullseye-pgdg/main amd64 libpq5 amd64 14.3-1.pgdg110+1 [172 kB]
Get:2 http://apt.postgresql.org/pub/repos/apt bullseye-pgdg/main amd64 postgresql-common all 241.pgdg110+1 [230 kB]
Get:3 http://apt.postgresql.org/pub/repos/apt bullseye-pgdg/main amd64 postgresql-client-common all 241.pgdg110+1 [92.1 kB]
Get:4 http://apt.postgresql.org/pub/repos/apt bullseye-pgdg/main amd64 postgresql-client-14 amd64 14.3-1.pgdg110+1 [1,629 kB]
Get:5 http://apt.postgresql.org/pub/repos/apt bullseye-pgdg/main amd64 postgresql-14 amd64 14.3-1.pgdg110+1 [15.8 MB]
debconf: delaying package configuration, since apt-utils is not installed
Fetched 17.9 MB in 1s (25.4 MB/s)
(Reading database ... 12100 files and directories currently installed.)
Preparing to unpack .../libpq5_14.3-1.pgdg110+1_amd64.deb ...
Unpacking libpq5:amd64 (14.3-1.pgdg110+1) over (14.2-1.pgdg110+1) ...
Preparing to unpack .../postgresql-common_241.pgdg110+1_all.deb ...
Leaving 'diversion of /usr/bin/pg_config to /usr/bin/pg_config.libpq-dev by postgresql-common'
Unpacking postgresql-common (241.pgdg110+1) over (238.pgdg110+1) ...
Preparing to unpack .../postgresql-client-common_241.pgdg110+1_all.deb ...
Unpacking postgresql-client-common (241.pgdg110+1) over (238.pgdg110+1) ...
Preparing to unpack .../postgresql-client-14_14.3-1.pgdg110+1_amd64.deb ...
Unpacking postgresql-client-14 (14.3-1.pgdg110+1) over (14.2-1.pgdg110+1) ...
Preparing to unpack .../postgresql-14_14.3-1.pgdg110+1_amd64.deb ...
invoke-rc.d: could not determine current runlevel
invoke-rc.d: policy-rc.d denied execution of stop.
Unpacking postgresql-14 (14.3-1.pgdg110+1) over (14.2-1.pgdg110+1) ...
Setting up postgresql-client-common (241.pgdg110+1) ...
Setting up libpq5:amd64 (14.3-1.pgdg110+1) ...
Setting up postgresql-client-14 (14.3-1.pgdg110+1) ...
Setting up postgresql-common (241.pgdg110+1) ...
debconf: unable to initialize frontend: Dialog
debconf: (TERM is not set, so the dialog frontend is not usable.)
debconf: falling back to frontend: Readline
Configuring postgresql-common
-----------------------------
createcluster.conf: A new version (/tmp/postgresql-common.sK2jGD) of
configuration file /etc/postgresql-common/createcluster.conf is available, but
the version installed currently has been locally modified.
  1. install the package maintainer's version
  2. keep the local version currently installed
  3. show the differences between the versions
  4. show a side-by-side difference between the versions
  5. start a new shell to examine the situation
What do you want to do about modified configuration file createcluster.conf?

How can I solve this problem?

A: The build breaks because it asks you what to do, and from a script (or automated build), this is not possible.
The solution is to allow apt to configure the installation noninteractively. Add to your Dockerfile:
ENV DEBIAN_FRONTEND=noninteractive

This way, automatic selections to the packages will apply. This is fine for most cases.


text:
Q: Conditionally fill column by other columns values I have ~ 4 million rows of personal data that looks like the following:
names <- c("Peter", "Peter", "Peter", "Peter", "Peter", "Peter", "Peter", "Lisa", "Bert", "Carine", "Carine", "Carine", "Carine", "Carine", "Carine")
luckyToday <- c(0,0,0,NA,0,0,1,NA,1,NA,0,0,0,1,1)
luckyYesterday <- NA_real_
df1 <- data.frame(names,luckyToday,luckyYesterday)

df1
# names luckyToday luckyYesterday
# 1   Peter          0             NA
# 2   Peter          0             NA
# 3   Peter          0             NA
# 4   Peter         NA             NA
# 5   Peter          0             NA
# 6   Peter          0             NA
# 7   Peter          1             NA
# 8    Lisa         NA             NA
# 9    Bert          1             NA
# 10 Carine         NA             NA
# 11 Carine          0             NA
# 12 Carine          0             NA
# 13 Carine          0             NA
# 14 Carine          1             NA
# 15 Carine          1             NA

The data contains observations of people (some with 1 observation, some with more) and their luckiness (1=lucky, 0=unlucky, NA=no information). As kind of a lagged variable, I want to introduce a new variable ("luckyYesterday") that tells me if the person was lucky during the last observation or not. So I want the data look like this:
df2
# names luckyToday luckyYesterday
# 1   Peter          0             NA
# 2   Peter          0              0
# 3   Peter          0              0
# 4   Peter         NA              0
# 5   Peter          0              0
# 6   Peter          0              0
# 7   Peter          1              0
# 8    Lisa         NA             NA
# 9    Bert          1             NA
# 10 Carine         NA             NA
# 11 Carine          0              0
# 12 Carine          0              0
# 13 Carine          0              0
# 14 Carine          1              0
# 15 Carine          1              1

I know that R is not the perfect programm to apply such data wrangling, but it is necessary.
I want to consider the following things:

*

*Consider that these are unique persons I have observations from, dont mix up observations of different people.

*Lower observations are newer. The last observation of a unique person is the latest one (row #7 is the latest observation of Peter).

*If there is a NA in the "luckyToday" column (for example row #4), I dont want the corresponding "luckyYesterdayNA" (row #5) filled with a NA, too. I rather want the corresponding cell get filled with the value of the newest "non-NA" observation in the "luckyToday" column, which is a "0" in the example data. If the previous observations are only NAs, then I assume that they equal the latest observation. (if I have 9 NAs and the 10th observation is a "1", then I want to assume that observations 1-9 are also "1".

*If there is only one observation per person, I want a NA in the "luckyYesterday" column anyway since I have no knowledge about the previous state of luck.

I tried it by myself with 2 for-loops, but I takes ages on my data with over 4 million observations. Can anyone help my with a faster solution such as with data.table or an apply function, please? I would appreciate that so much!
Cheers

A: You can use the shift function from data.table to observe yesterday and na.locf function from zoo package to fill NA with yesterday or tomorrow depending on if the fromLast parameter is F or T, and also group by the name if you don't want to mix observations of different people:
library(data.table); library(zoo)
setDT(df1)[,luckyYesterday := shift(na.locf(luckyToday, fromLast = TRUE)), names]

df1
#      names luckyToday luckyYesterday
#  1:  Peter          0             NA
#  2:  Peter          0              0
#  3:  Peter          0              0
#  4:  Peter         NA              0
#  5:  Peter          0              0
#  6:  Peter          0              0
#  7:  Peter          1              0
#  8:   Lisa         NA             NA
#  9:   Bert          1             NA
# 10: Carine         NA             NA
# 11: Carine          0              0
# 12: Carine          0              0
# 13: Carine          0              0
# 14: Carine          1              0
# 15: Carine          1              1

A: names <- c("Peter", "Peter", "Peter", "Peter", "Peter", "Peter",
    "Peter", "Lisa", "Bert", "Carine", "Carine", "Carine", "Carine", "Carine", "Carine")
luckyToday <- c(0,0,0,NA,0,0,1,NA,1,NA,0,0,0,1,1)
luckyYesterday <- NA
df1 <- data.frame(names,luckyToday,luckyYesterday)

# New code
library(data.table)
data.table(df1)[,list(luckyToday, c(NA, luckyToday[1:(.N-1)])),by=list(names)]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Related objects reference with custom manager I want to get the related object references and I want to use a custom manager.
Is there something outside? How I can use a custom manager to get these objects?
 b.entry_set.all()

E.g
b.custom_manager.entry_set.all()
b.entry_custom_manager_set.all()

A: This has been possible since Django 1.7. Say you have a model Entry with two managers:
class Entry(models.Model):
    blog = models.ForeignKey('Blog', on_delete=models.CASCADE)
    ...

    objects = models.Manager()  # Default Manager
    entries = EntryManager()    # Custom Manager

Then you can control which manager you use by passing manager to entry_set:
b = Blog.objects.get(id=1)
b.entry_set.all() # implicitly use the default manager
b.entry_set(manager='objects').all() # explicitly use the default manager
b.entry_set(manager='entries').all() # explicitly use the entries manager

See the docs on using a custom reverse manager for more info.

A: It looks like a ticket is still open for this feature https://code.djangoproject.com/ticket/3871


text:
Q: Swift - How to expand UITableViewCell's height, while pushing adjacent cells away from the selected cell? I am working on a ViewController with a TableView populated with dynamic cells from a prototype nib. I have run into a dead-end trying to recreate certain a cell-expanding animation.
My goal:
When a cell is selected, the selected cell should "expand" (grow in height to twice it's starting size) while at the same time creating space between the cell directly above and below the selected cell.
I've found an example of EXACTLY the asethetic I am looking for in the app "Things". Below are two screenshots showing the table before and and after a cell is selected:
Screenshot of table BEFORE expansion
Screenshot of table AFTER expansion
The best way I can describe the desired animation is the UITableView version of "the parting of the Red Sea". When a cell is selected, the surrounding cells give way lending the selected cell more room.. and the user's focus.
What I've tried:
I found Simon Lee's method answering a similar question and implemented it into my project. And although it animates the row-height change perfectly, it only pushes the adjacent cells on one side of the selected cell. (ie: if the cell at index 4 is selected, all the cells from index 5+ move down but those from index 0-3 stay static. Thereby not achieving the look I'm seeking.)
Using that method, the relevant sections of my code looked something like:
var cellHeight: CGFloat = 72
var selectedCell: IndexPath?

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath == selectedCell {
            return cellHeight * 2
        } else {
            return cellHeight
        }
    }
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    selectedCell = indexPath

    tableView.beginUpdates()
    tableView.endUpdates()
}

func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
    selectedCell = nil

    tableView.beginUpdates()
    tableView.endUpdates()
}

Because that didn't result in my desired animation, I tried insertRows:at:with: to insert 2 empty cells (1 above and 1 below the selected row) -- then deleteRows:at:with: to remove them upon deselecting the cell. This ultimately made for a better looking animation, and looked closer to the "Things" example I'm shooting for. However this made the table overly complicated because by adding and removing cells each time a row is selected, it would change the index of the other cells making it frustrating to predict which cells would have what index at any given time.
A possible solution idea?
After working on this for a couple of days the only other way I could think to accomplish what I want is to somehow scroll the table slightly at the same time that the selected cell's height it changed.. so that as the cell expands (moving the following cells downward) it would make the previous cells appear to move upward. I'm hesitant to try this because it feels like a hack, there should be a better way to accomplish this.
ANY help would be thoroughly appreciated! I've been pulling my hair out at an alarming rate. Thank you to anyone who can share their knowledge.


text:
Q: Why is meta so harsh and how can I provide better feedback here? Am I not asking questions / feedback correctly? This site is supposed to be for feedback, but it seems that people are more "downvote happy" here than on SOFU which naturally discourages feedback. In the past I've deleted my questions which were on the downvote trend, obviously not useful to the community.
While I'm not a new user to SOFU, I'm an infrequent user on MSO and previously used the UserVoice site. The atmosphere here doesn't seem conducive to site/community building, as its the same small group of users.

A: Looking at all the responses to your questions, I don't see any responses that are particularly harsh . I see people that have disagreed with you and or down voted, but things things were done in a very civil manner.
On MSO, you can't take down votes personally. Since requests here can shape SOFU as we know it, I, and many others here, tend to be very opinionated regarding things they want and don't want. On MSO I have over 200 down votes, not because I furiously hate 200 people, but because there have been many suggestions I don't agree with. I treat every suggestion independent of the person suggesting it, and never associate a vote with a particular user.

A: In my experience, it's not so much that people disagree, it's that often the attitude here is "If you don't like it, don't use it" or "It's just that way, all your reasons for disliking it are invalid". Only said more in a very coarse manner sometimes.
Often MSO reminds me of an Old Boys Club, where new users whilst welcome, they are only tolerated because the rules say so.
Obviously I realise that this is a gross generalisation, and I have seen some very sensible discussions happening on here, but often threads get hijacked regularly.

A: Because meta is murder ... http://www.codinghorror.com/blog/archives/001282.html
The engine was never really designed as a discussion/support site, it was adapted to it. Personally, I find that if your raise interesting topics they get plenty votes. I also find people are pretty civil here on meta (with a handful of notable exceptions)
Keep in mind, when you ask a question on meta, there is usually no correct answer™. Its touchy-feely, some people will agree with you strongly, some will disagree with you strongly.
If this behavior frustrates you then move along to \S[OUF]\ where downvotes mean "you are wrong", and not "I disagree with you".

A: Meta, by it's purpose, is a lot more subjective. The key to SO/SF/SU is that there are qualitative methods to measure answers, responses, comments and opinions while here, well, things are by definition a lot less certain.
As others have said, there's just a lot more scope for disagreement - perhaps even ownership of ideas rather than understanding of others'.

A: People need to stop taking the back and forth on Meta so seriously.
God forbid people disagree with you.
I do not believe in the idea that every idea is a good idea and I feel that is my right and duty as a user of these websites to voice my opinion on it. Whether that means making my own questions or providing answers that both agree and disagree.
There is no purpose in making suggestions if people cannot go and say "I do not like this" or "I do not think that would work". But it should be remembered that one person's opinion is no more valuable than any other user's (unless we're counting the Dev team here).
Some people on here who have been around for a while and have attained a reputation (no pun intended) may be seen as a more authoritative voice based on their past experiences and past opinions. They may have more people that typically agree with them, but that doesn't necessarily mean that they are any more right than any other user.
If someone disagrees with you, don't take offense to it. Try to understand that we are all wanting what we think is best for the sites and nothing should really be seen as an attack on other users.

A: Meta is where the hard problems are thrashed out, and sometimes the emphasis is on the thrashing.
It is also, sometimes, where we come to vent. In anycase, you should not expect Meta to have the same culture as the other sites. Different problems, different needs, so different ways.

In particular, you should not think of downvotes on meta as punitive---reputation here means even less than it means on other the other sites---they are just disagreement.


text:
Q: Use Python to run a javascript in background using Thread I am currently working on building a simple word editor using PYQT5 as the main GUI and using Node.js as the text area and do some words filtering stuffs. Here are my code for the PYQT part:
import threading

from PyQt5 import QtCore, QtGui, QtWidgets
from Naked.toolshed.shell import execute_js, muterun_js

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1090, 780)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
        self.gridLayout.setObjectName("gridLayout")
        self.webView = QtWebEngineWidgets.QWebEngineView(self.centralwidget)
        self.webView.setUrl(QtCore.QUrl("http://127.0.0.1:3000/"))
        self.webView.setObjectName("webView")
        self.gridLayout.addWidget(self.webView, 0, 0, 1, 1)
        MainWindow.setCentralWidget(self.centralwidget)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))

from PyQt5 import QtWebEngineWidgets

def loadJS():
    #try to use threading here to run it in background but still no effects

    js = threading.Thread(target=execute_js("../Editor/Engine/index.js"))
    js.daemon=True
    js.start()

def loadGUI():
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    MainWindow.show()
    sys.exit(app.exec_())

if __name__ == "__main__":
    import sys
    loadJS()
    loadGUI()

My expected result is using WebView in PYQT5 to load my localhost so I can get something like this:
Expected output

My Node.js script runs just fine and does all its job, but there's no way to run my main GUI. From my understanding, when run, the system waits for loadJS() to finish its job then call loadGUI(). So I tried to use Threading to put loadJS() into background and keep it running while the loadGUI() in the front. However, it seems to have no effects. I am not sure if I am using Threading wrong or misunderstand its purpose. Any help is appreciated.

A: In your initial code you are invoking directly in the function in main thread, instead you have to pass as target to the name of the function and in args to the arguments as a tuple.
js = threading.Thread(target=execute_js, args=("../Editor/Engine/index.js",))
js.daemon=True
js.start()


text:
Q: Problems when drawing on SurfaceView I'm experimenting with the SurfaceView in Android and I'm trying to create a simple drawing type application, where you "draw" by touch on it.  I have a thread running to handle the drawing onto the canvas but I'm hitting some performance issues.  I read on http://developer.android.com/guide/topics/graphics/index.html that you need to repaint the entire surface so I tried storing all the touched points in a float array mPoints and than redraw them every time.  Problem is when a lot of points build up it gets really slow.  Here is the code for that:
    @Override
    public void run() {

        while(mIsRunning) {
            Canvas c = null;
            try {
                c = mSurface.lockCanvas(null);
                synchronized(mSurface) {
                    int size = mPoints.getSize();
                    for(int i = 0; i < size; i += 2) {
                        c.drawCircle(mPoints.get(i), mPoints.get(i + 1), 3, mPaint);
                    }
                }
            }
            finally {
                if (c != null)
                    mSurface.unlockCanvasAndPost(c);
            }

        }
    }

However when I updated it so that it cleared the float array and only drew new touched points it causes a lot of flickering.  From what I can tell this is because Android uses double buffering.  I'm not sure how to get around these problems.

A: try writing to a bitmap and then redrawing the bitmap every time.  You can maybe keep a record of last 10 points or something to allow undo etc.

A: Building on Adil's answer, this is what I came up with and seems to work.  It doesn't seem to quite pick up every single point if you try and draw a continuous line of points so it needs some further optimization but it does get the job done:
    @Override
    public void run() {
        mDrawing = Bitmap.createBitmap(mWidth, mHeight, Bitmap.Config.ARGB_8888);
        Canvas tempCanvas = new Canvas();
        tempCanvas.setBitmap(mDrawing);

        Canvas c = null;
        while(mIsRunning) {
            int size = mPoints.getSize();
            for(int i = 0; i < size; i += 2) {
                tempCanvas.drawCircle(mPoints.get(i), mPoints.get(i + 1), 3, mPaint);
            }

            mPoints.empty();

            try {
                c = mSurface.lockCanvas(null);
                synchronized(mSurface) {
                    c.drawBitmap(mDrawing, 0, 0, mPaint);
                }
            }
            finally {
                if (c != null)
                    mSurface.unlockCanvasAndPost(c);
            }

        }
    }


text:
Q: Generating unique and opaque user IDs in Google App Engine I'm working on an application that lets registered users create or upload content, and allows anonymous users to view that content and browse registered users' pages to find that content - this is very similar to how a site like Flickr, for example, allows people to browse its users' pages.
To do this, I need a way to identify the user in the anonymous HTTP GET request. A user should be able to type http://myapplication.com/browse/<userid>/<contentid> and get to the right page -  should be unique, but mustn't be something like the user's email address, for privacy reasons.
Through Google App Engine, I can get the email address associated with the user, but like I said, I don't want to use that. I can have users of my application pick a unique user name when they register, but I would like to make that optional if at all possible, so that the registration process is as short as possible.
Another option is to generate some random cookie (a GUID?) during the registration process, and use that, I don't see an obvious way of guaranteeing uniqueness of such a cookie without a trip to the database.
Is there a way, given an App Engine user object, of getting a unique identifier for that object that can be used in this way?
I'm looking for a Python solution - I forgot that GAE also supports Java now. Still, I expect the techniques to be similar, regardless of the language.

A: Your timing is impeccable: Just yesterday, a new release of the SDK came out, with support for unique, permanent user IDs. They meet all the criteria you specified.

A: I think you should distinguish between two types of users:
1) users that have logged in via Google Accounts or that have already registered on your site with a non-google e-mail address
2) users that opened your site for the first time and are not logged in in any way
For the second case, I can see no other way than to generate some random string (e.g. via uuid.uuid4() or from this user's session cookie key), as an anonymous user does not carry any unique information with himself.
For users that are logged in, however, you already have a unique identifier -- their e-mail address. I agree with your privacy concerns -- you shouldn't use it as an identifier. Instead, how about generating a string that seems random, but is in fact generated from the e-mail address? Hashing functions are perfect for this purpose. Example:
>>> import hashlib

>>> email = 'user@host.com'
>>> salt = 'SomeLongStringThatWillBeAppendedToEachEmail'

>>> key = hashlib.sha1('%s$%s' % (email, salt)).hexdigest()
>>> print key
f6cd3459f9a39c97635c652884b3e328f05be0f7

As hashlib.sha1 is not a random function, but for given data returns always the same result, but it is proven to be practically irreversible, you can safely present the hashed key on the website without compromising user's e-mail address. Also, you can safely assume that no two hashes of distinct e-mails will be the same (they can be, but probability of it happening is very, very small). For more information on hashing functions, consult the Wikipedia entry.

A: Do you mean session cookies?
Try http://code.google.com/p/gaeutilities/

What DzinX said.  The only way to create an opaque key that can be authenticated without a database roundtrip is using encryption or a cryptographic hash.
Give the user a random number and hash it or encrypt it with a private key.  You still run the (tiny) risk of collisions, but you can avoid this by touching the database on key creation, changing the random number in case of a collision.  Make sure the random number is cryptographic, and add a long server-side random number to prevent chosen plaintext attacks.
You'll end up with a token like the Google Docs key, basically a signature proving the user is authenticated, which can be verified without touching the database.
However, given the pricing of GAE and the speed of bigtable, you're probably better off using a session ID if you really can't use Google's own authentication.


text:
Q: Сервер не возвращает данные Всем привет! Надеюсь на Вашу помощь. Есть страничка, на которой есть select. При его изменении подгружаются данные с php-скрипта через ajax. Мне же необходимо получить эти самые данные только со своего сервера. Однако при отправке post через curl возвращаются только заголовки:
HTTP/1.1 200 OK
Server: nginx/1.12.2
Date: Mon, 04 Mar 2019 20:10:24 GMT
Content-Type: text/html; charset=UTF-8
Content-Length: 0
Connection: keep-alive
X-Powered-By: PHP/7.2.15

И никакие данные не возвращаются.
Делаю так, даже меняю заголовки referer, origin и т.д:
$h = date('H') - 3;
    $i = date('i');
    $s = date('s');
    $headers = array(
        'Referer: https://site.ru/page_with_select/',
        'Origin: https://site.ru',
        'Date: Mon, 04 Mar 2019 '.$h.':'.$i.':'.$s.' GMT',
        'Content-type: application/x-www-form-urlencoded',
        'Content-Length: 31',
        'Connection: keep-alive',
        'Cache-Control: no-store, no-cache, must-revalidate',
        'Set-Cookie: PHPSESSID=ИД сессии из cookies.txt; path=/',
        'User-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.119 Safari/537.36',
    );
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://site.ru/page_with_select/script.php");
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "postdata=postdata");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_COOKIEJAR, 'cookies.txt');
    curl_setopt($ch, CURLOPT_COOKIEFILE, 'cookies.txt');
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    $string = curl_exec($ch);
    curl_close($ch);
    print_r($string);

Когда же я меняю ajax прямо в браузере, на их сайте, все данные подгружаются нормально.
В чем может быть проблема? Заранее спасибо!


text:
Q: Places SDK for Android: styling an Autocomplete Activity I am using an Intent to launch an Autocomplete Activity from the Places SDK for Android, as described here, along the following lines:
Intent intent = new Autocomplete.IntentBuilder(
        AutocompleteActivityMode.FULLSCREEN, fields)
        .build(this);
startActivityForResult(intent, AUTOCOMPLETE_REQUEST_CODE);

But I cannot see a way of styling the resulting Autocomplete Activity, to make it match the theme of my app as closely as possible, and in particular to follow the day/night theme being used in the app.  At present the background of the places list always appears to be white, with dark text on top, i.e. suited only to a light theme.
For example the following is what it looks like, when launched from within an app running on a system set to dark theme:

How is this Activity meant to be styled?

A: In colors.xml file make sure you have these defined:
<resources>
   <color name="colorPrimary">#ffffff</color>
   <color name="colorPrimaryDark">#03DAC5</color>
   <color name="colorAccent">#03d</color>
</resources>

In styles.xml you should have this defined:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
   <item name="colorPrimary">@color/colorPrimary</item>
   <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
   <item name="colorAccent">@color/colorAccent</item>
</style>

With that I was able to change the colors of the Places SDK.
colorPrimary is used for the background surrounding the EditText
colorPrimaryDark is used for the status bar

A: According to the documentation there is something called AutoCompleteActivity that extends AppCompatActivity as well as AutocompleteSupportFragment that extends Fragment.
instead of using the IntentBuilder to create what i assume is just a generic version of AutocompleteActivity you should create your own AutocompleteActivity using the provided constructor and then override onCreate to set the Theme to dark. and then you just open the activity like you would with a regular intent.
Important note: in the documentation you will find that for some reason AutocompleteSupportFragment includes a lot more usefull methods that could be interesting for you (like setLocationRestriction(), setPlaceFields(), setTypeFilter etc) but for some reason these dont appear in the docs of AutoCompleteActivity. im not sure if they just forgot to put them in the doc or if the fragment version is actually more powerful than the Activity. this just means you might have to use the fragment (and plant it into an empty activity) instead of the activity.


text:
Q: How to split strings using C# and Linq I want to split a string like Members in table Set and select the result with other fields as a record.
For example, lets assume the Set has 2 fields (ID, Members) and 2 records: (1, "A, B") and (2, "C").
Now I need a Linq query to retrieve records as: (1, A), (1, B), (2,C).
I am using Visual Studio 2008.

A: LINQ-to-SQL won't do this, but you can retrieve this data using LINQ-to-SQL and then run straight LINQ against it.
List<Set> sets;
using (var context = new MyDataContext())
{
    sets = context.Sets.ToList();
}

var result = sets.SelectMany(s =>
    s.Members.Split(',').Select(m => new { s.ID, m }));


text:
Q: Getting thread id in c++ I am new to C++ and I am following course on YouTube
where I saw this line of code:
uint32_t threadID = std::hash<std::thread::id>{}(std::this_thread::get_id());

Why are there curly braces in between hash type and thread::getid()? Also I've seen that it can be replaced by (). What's that about?

A: std::hash is a struct, not a function.  The code initializes a temporary/anonymous hash object, then calls the hash object's operator() with the calling thread's ID as an argument.
Therefore, that code is equivalent to this:
std::hash<std::thread::id> myHashObject{};
uint32_t threadID = myHashObject(std::this_thread::get_id());

The curly-braces are just the new-style way to initialize a C++ object.

A: std::hash is a type. We need an object of that type to do actual hashing. So, the {} (or ()) is creating a temporary object of that type. Then the parentheses containing the std::this_thread::get_id() means we're invoking the operator() on that object.


text:
Q: Merging Text/Data files into Rows and Columns over for 80m lines of data I've been assigned to take over 5k of csv files and merge them to create seperate files which contain transposed data with each filename becoming a column in a new file (the source column 1 being extracted from each file as the data) and rows = dates.
I was after some input/suggestions on how to accomplish this..
Example details as follows:
File1.csv -> File5000.csv
Each file contains the following

Date, Quota, Price, % Value, BaseCost,...etc..,Units
'date1','value1-1','value1-2',....,'value1-8'
'date2','value2-1','value2-2',....,'value2-8'
....etc....
'date20000','value20000-1','value20000-2',....,'value20000-8'

The resulting/merged csv file(s) would look like this:
Filename- Quota.csv

Date,'File1','File2','File3',etc.,'File5000'
'date1','file1-value1-1''file2-value1-1','file3-value1-1',
etc.,'File5000-value20000-1'
'date20000','file1-value20000-1','file2-value20000-1','file3-value20000-1',
etc.,'File5000-value20000-1'

Filename Price,csv

Date,'File1','File2','File3',etc.'File5000'
'date1','file1-value2-1''file2-value2-1','file3-value2-1',
etc.,'File5000-value2-1'
'date20000','file1-value20000-2','file2-value20000-2','file3-value20000-2',
etc.,'File5000-value20000-2'

....up to Filename: Units.csv

Date,'File1','File2','File3',etc.'File5000'
'date1','file1-value2-8''file2-value2-8','file3-value2-8',
etc.,'File5000-value20000-8'
'date20000','file1-value20000-8','file2-value20000-8','file3-value20000-8',
etc.,'File5000-value20000-8'

I've been able to use an array contruct to reformat the data, but due to the shear number of files and entries it uses way too much RAM - the array gets too big, and this approach is not scalable.
I was thinking of simply loading each of the 5,000 files one at a time and extracting each line 'one at a time' per file, then outputing the results to each new files 1-8 row-by-row, however this may take an extremely long time to convert the data even on an SSD drive with over 80million lines of data in 5k+ files.
The idea was it would load File1.csv, extract the first line, store the Date and first column data into a simple array. Then load the second File2.csv, extract the first line, check if the Date matches and if so store the first column data in the same array....repeat for all 5k files and once completed store the array into a new file Column1-8.csv. Then repeat each file again for the corresponding dates and only extract the first data column of each file to add to the Value1.csv file. Then repeat the whole process for Column2 data, up to Column8....taking forever :(
Any ideas/suggestions on approach via scripting language?
Note: The machine it will likely run on only has 8GB RAM, using *nix.


text:
Q: document.getElementById(..) gives null even though element is present I have the following program in which a user can enter any name in a search box after which I redirect the user to a page called usernameSearchResults.php where I print a list of the usernames obtained in the form of an array from usernamesearch.php. Here is the javascript:
$(window).on('load', function() {
$(".searchBarForm").submit(function(e){
    e.preventDefault();

    var search=document.getElementsByClassName("search")[0].value;

    $.ajax
    ({
        type: 'POST',
        url: 'usernamesearch.php',
        data:
        {
            search:search
        },
        success: function (response)
        {
            window.location.href="usernameSearchResults.php";
            response = JSON.parse(response);

            var array_length = Object.keys(response).length;//getting array length

            for(var i=0;i<array_length;i++){

                if(i==0){
                    document.getElementById("searchResults").innerHTML=""+response[0].username+"
";//i=0
                }else{
                    document.getElementById("searchResults").innerHTML+=""+response[i].username+"
";
                }

            }

            window.stop();//stops page from refreshing any further(put here to fix a bug that was occuring)
        },
        error: function(xhr, status, error) {
            alert(xhr.responseText);
        }
    });

return false;
})
});

This is usernameSearchResults.php(inside  tags):

Username Search Results

But the problem is that whenever I go to any other page say index.php and enter the username to be searched, the page redirected to is indeed usernameSearchResults.php but the page is blank and error in the console shown says document.getElementById("searchResults") is null.But if I stay at the page usernameSearchResults.php and refresh it and then search any name again, then the results are correctly obtained. What is the problem here?

A: I would say that the user is being redirected to usernameSearchResults.php but the JavaScript code is still being executed from the current page, which have no element with id "searchResults" defined.
As @Kashkain said, one way to achieve what you want is to pass your response variable in your redirection url and process it then into your other page.

A: I think the problem here is that the new document could very well still not have been loaded when you call getElementById.
You could add a listener on your target element which would trigger on the load event. In this event's handler you could execute the operations that are now giving you an error.
I have never done or tried this, but maybe something like this would work:
$('#searchResults').on('load', function() {
   //execute code here
});

Or you could add a form to the page with action="target_url" method="post" and send your response data through post by doing form.submit, and place the problematic code into usernameSearchResults.php, which will need to read data from POST - this way you can send your ajax data to the new page


text:
Q: Component extends with super class needs help to test Here is my base class:
export class DetailsComponent
extends AddClinicComponent
implements OnInit, AfterViewInit{}

in the spec of DetailsComponent.spec I am tryin to write a testing, which is in AddClinicComponent component.
here is the test:
fit('it should open popup  on click of button add clinic button ', async(() => {
    spyOn(component, 'openDialog');
    fixture.detectChanges();
    const removeButton =
        fixture.debugElement.nativeElement.querySelector('.hfs-add-btn');
    expect(removeButton).toBeTruthy();
    let event = new MouseEvent('click');
    removeButton.dispatchEvent(event);
    fixture.whenStable().then(() => {
        expect(component.openDialog).toHaveBeenCalled();
    });
}));

But getting an error as :
 Error: Directive AddClinicComponent has no selector, please add it! how to resolve it?
what is the correct way to test the extended component?
my super class:
import { TemplateRef, ViewChild } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { AddClinicDataService } from '../services/personnel-add-clinic-data.service';
import { HFSClinicTaleSchema } from './hfs-clinic-table.schema';
export abstract class AddClinicComponent {
    popTableSchema;
    clinicTaleSchema;
    @ViewChild('popupTemp', { static: true })
    popupTemp: TemplateRef<HTMLAllCollection>;
    public primaryName = '';
    public primaryAdminId = '';
    public dialog: MatDialog;

    constructor(protected aAddClinicDataService: AddClinicDataService) {
        this.clinicTaleSchema = HFSClinicTaleSchema;
    }

    clinicRowGenerator(rows) {
        return rows.map((p) => {
            return {
                ...p,
                address: Object.values(p.address).filter((v) => v != null),
                transform: true,
            };
        });
    }

    handleAddClinic() {
        this.popTableSchema = { ...HFSClinicTaleSchema, rows: [] };
        this.openDialog(this.popupTemp);
    }
    openDialog(templateRef: TemplateRef<HTMLAllCollection>) {
        const dialogRef = this.dialog.open(templateRef);
        dialogRef.afterClosed().subscribe((result) => {
            console.log(`Dialog result: ${result}`);
        });
    }

    addClinics() {
        const { rows } = this.popTableSchema;
        const transform = [...rows]
            .filter((r) => r.checked)
            .map((item) => ({ ...item, checked: false }));
        if (!transform.length) return;
        this.rowTransformer(transform);
        this.dialog.closeAll();
    }

    searchClinics($event: Event): void {
        $event.preventDefault();
        const formDetails = this.postProfile();
        const countryCodes = formDetails.countries.map((v) => v.codeId);
        const searchParams = {
            primaryAdminId: this.primaryAdminId,
            primaryName: this.primaryName,
            countryCodes: countryCodes.join(','),
        };
        this.fetchClinicList(
            `name=${this.primaryName}&adminUserName=${
                this.primaryAdminId
            }&countryCds=${countryCodes.join(',')}`
        );
        this.primaryAdminId = '';
        this.primaryName = '';
    }
    fetchClinicList(searchParams) {
        this.aAddClinicDataService
            .getClinicsList(searchParams)
            .subscribe((data) => {
                const nwRows = data?.map((d) => {
                    return {
                        ...d,
                        address: Object.values(d.address).filter(
                            (v) => v !== null
                        ),
                    };
                });
                this.popTableSchema = { ...this.popTableSchema, rows: nwRows };
            });
    }
    protected abstract rowTransformer(value);
    abstract postProfile();
}

after having some try:
I got this error:
 Error: This constructor is not compatible with Angular Dependency Injection because its dependency at index 0 of the parameter list is invalid.
        This can happen if the dependency type is a primitive like a string or if an ancestor of this class is missing an Angular decorator.

        Please check that 1) the type for the parameter at index 0 is correct and 2) the correct Angular decorators are defined for this class and its ancestors.

constructor of details component:
constructor(
        private personnelViewDataService: PersonnelViewDataService,
        private personnelTranslateService: PersonnelTranslateService,
        private cdr: ChangeDetectorRef,
        public dialog: MatDialog,
        protected aAddClinicDataService: AddClinicDataService
    ) {
        super();
    }

constructor of AddClinicComponent
 constructor(protected aAddClinicDataService: AddClinicDataService) {
        this.clinicTaleSchema = HFSClinicTaleSchema;
    }

A: Dependency injection works only if the class has an Angular decorator.

DI is wired into the Angular framework and allows classes with Angular decorators, such as Components, Directives, Pipes, and Injectables, to configure dependencies that they need.

https://angular.io/guide/dependency-injection
This could be causing the error, try to inject the service in the component class and when calling super pass the service to the extended class
constructor of details component:
constructor(
  private personnelViewDataService: PersonnelViewDataService,
  private personnelTranslateService: PersonnelTranslateService,
  private cdr: ChangeDetectorRef,
  public dialog: MatDialog,
  public aAddClinicDataService: AddClinicDataService
) {
  super(aAddClinicDataService);
}


text:
Q: VueJS reactive Date object Rather beginner question, but I couldn't find a solution anywhere.
I have 2 buttons that increment/decrement a given Date object by +/- 1 day. The object is updated, but the changes are not displayed. I found out it's because the Date Obj is not reactive, but I didn't find a solution or a workaround to this.
JSFiddle Demo
HTML:

  <button @click="inc">+ 1 day</button>
  <button @click="dec">- 1 day</button>

  {{date}}

JS/Vue:
new Vue({
  el: "#app",
  data: {
    date: new Date()
  },
  methods: {
    inc () {
        this.date.setDate(this.date.getDate() + 1)
        console.log(this.date)
    },
    dec () {
        this.date.setDate(this.date.getDate() - 1)
        console.log(this.date)
    }
  }
})

In the console the Date is incresed/decreased fine, but the date rendered on the page just stays the same. Can anybody help with this? Thanks.

A: You are modifying the date object in place in which case Vue can not detect the changes, create a new date object instead:
https://jsfiddle.net/13gzu8xs/1/
new Vue({
  el: "#app",
  data: {
    date: new Date()
  },
  methods: {
    inc () {
      this.date.setDate(this.date.getDate() + 1)
      this.date = new Date(this.date)     //  create a new date and assign to this.date
        },
    dec () {
      this.date.setDate(this.date.getDate() - 1)
      this.date = new Date(this.date)
    }
  }
})


text:
Q: Check, with jquery, if a specific dropdown option is selected, and if it is, enable/show a hidden/disabled dropdown box I'm loading data from a database table directly into a form's dropdown box. I'm trying to check on page load if a specific value is set into this box and if it is I want to enable another dropdown box which is disabled and hidden by default.
I'm using Chronoforms v5 for the form creation (joomla) and I have setup events which enable & show the 2nd dropdown box if a specific value is chosen in the 1st dropdown box, and reversely if no value is chosen in the 1st dropdown, or a value different than the one I want, I disable & hide the 2nd dropdown box. But these events happen only after the user is actively changing the values in the 1st dropdown box. I need the events to happen on page loading as well.
Chronoform's javascript is
function chronoforms_fields_events(){

    $(':input[name="custom"]').on('change', function(){
        if($(this).val() == 'United_States'){
            $(':input[name="state"]').prop('disabled', false);
        }
    });

    $(':input[name="custom"]').on('change', function(){
        if($(this).val() == 'United_States'){

            if($(':input[name="state"]').closest('.gcore-subinput-container').length > 0){
                $(':input[name="state"]').closest('.gcore-subinput-container').show();
                }else if($(':input[name="state"]').closest('.gcore-form-row').length > 0){
                $(':input[name="state"]').closest('.gcore-form-row').show();
            }

        }
    });

    $(':input[name="custom"]').on('change', function(){
        if($(this).val() != 'United_States'){

            if($(':input[name="state"]').closest('.gcore-subinput-container').length > 0){
                $(':input[name="state"]').closest('.gcore-subinput-container').hide();
                }else if($(':input[name="state"]').closest('.gcore-form-row').length > 0){
                $(':input[name="state"]').closest('.gcore-form-row').hide();
            }

        }
    });

    $(':input[name="custom"]').on('change', function(){
        if($(this).val() != 'United_States'){
            $(':input[name="state"]').prop('disabled', true);
        }
    });

    $(':input[name="custom"]').on('click', function(){
        if($(this).prop('checked')){
            $(':input[name="state"]').prop('disabled', false);
        }
    });
}
chronoforms_fields_events();

And I'm currently adding this javascript  before the HTML (Render form) but it doesn't work
 function validatecountry(){
 if ($("#custom").prop("selectedIndex", 'United_States')){
          $(':input[name="state"]').prop('disabled', false);
    if($(':input[name="state"]').closest('.gcore-subinput-container').length > 0){
                     $(':input[name="state"]').closest('.gcore-subinput-container').show();
                }else if($(':input[name="state"]').closest('.gcore-form-row').length > 0){
                $(':input[name="state"]').closest('.gcore-form-row').show();
            }

 }
 }
 validatecountry();

Any help will be greatly appreciated

A: If you call this function before the form renders, $("#custom"), $('input[name="state"]'), etc will not return anything & hence your code would not work. Add the call into a ready event:
$(document).ready(function() {
  validatecountry();
}

To the first part of your question, you can manually trigger a change on the input fields after DOM is ready which would call the change routine:
$(document).ready(function() {
  $('input[name="custom"]').trigger("change");
}


text:
Q: If $m^2+n^2=40$, where $m<0
If $m^2+n^2=40$, where $m<0<n$ and $m,n \in \mathbb{Z}$. What's
$(m+n)^2$?
I'm trying to see if there's a better approach to mine so that I can generalize the problem.
By primality test, $m,n < \lfloor{\sqrt{40}\rfloor}=6$ so $|m|,|n| \in \{1,2...6\} \stackrel{m^2, n^2}{\rightarrow} \{1,4,...,36\}$
By observation $4+36=40 \implies (m+n)^2=(-2+6)^2=(-6+2)^2=16$

A: Being $m,n\in\mathbb Z$ where $m\lt0\lt n$, we have $m^2+n^2=40\iff(|m|,n)=(\pm6,2),(\pm2,6)$ so $(m+n)^2=64 \text { and }16$.


text:
Q: Inline Devise Signup form using Turbo Frames I'm having trouble setting up a Devise sign-up form using Turbo Frames. I'd like to have the Devise sign up form set up as a "gradual engagement" form that only requires email to register the new user from the homepage.
Here's how I've set this up so far:

*

*First, I used this workaround to get the default Devise views working with Hotwire.

*Then, I used this approach to get the devise signup form working on my homepage

*Finally, I used this method to set up email-only signup with Devise.

That is all working as expected, but when the user complete's sign up it redirects and shows a flash page. Instead, I'd like to use Turbo Frames to just replace the form with a message like "Thank you for signing up" without reloading any page or doing a redirect.
Also, if there are any errors in the form (such as the email being blank) it redirects to the default devise sign up view and displays the errors there. I'd prefer this happens within the homepage frame so that there's no page reload when there's an error to display.
So, how would I do this with Devise and Turbo Frames?
Here's the form that's working on the homepage:
<%= form_for resource, :as => resource_name, :url => registration_path(resource_name), html: { class: "sm:flex" } do |form| %>
  <%= form.label :email, class: "sr-only" %>
  <%= form.email_field :email %>
  <div class="mt-3 rounded-md shadow sm:mt-0 sm:ml-3 sm:flex-shrink-0">
    <%= form.submit "Subscribe" %>
  </div>
<% end %>

And, to get that working I created a confirmations_controller.rb that overrides the default Devise::ConfirmationsController like this:
class ConfirmationsController < Devise::ConfirmationsController
  private
  def after_confirmation_path_for(resource_name, resource)
    sign_in(resource) # In case you want to sign in the user
    root_path
  end
end

Do I need to create a UsersController that overrides some parts of Devise to use turbo frames? How would I do this?

A: You're not going to be able to use after_X_path_for to accomplish this with Turbo. By the time you hit after_confirmation_path_for, my understanding is that Devise has already initiated a redirect, so it's too late to change to a Turbo response. These steps should get you closer:

*

*You need to enable Turbo on your form by adding the option data: { turbo: true }, or wrapping it in a turbo-frame element. You are seeing the full page reload and the flash message because this is missing.

*Your form (or a parent turbo-frame) need an ID for the Turbo response to target (i.e. the controller action needs to know which element to update).

*It appears that your form submission is handled by RegistrationsController. You will need to adjust the controller action (probably #create?) to have a block that actually renders a Turbo response, something like the following:
respond_to do |fmt|
  fmt.turbo_stream do
    render turbo_stream: turbo_stream.replace(
      form_element_id,
      partial: 'your_html_partial/here',
      locals: {
        current_user: your_user,
        other: "data"
      }
    )
  end
end

Lastly, this doesn't answer your question, but it will be much simpler to implement this without Devise, mainly because you're doing so much customization. Devise is best for limited customization (because, like Rails, it comes with very strong conventions). Implementing this flow should only involve a couple of controller actions (render the sign-in/sign-up form, handle form submission with Turbo stream).


text:
Q: Difference between `Marshal.load Marshal.dump array` and `array.map(&:dup)` I read in another answer It's preferred to use array.map(&:dup):

Don't use the marshalling trick unless you really want to deep copy an entire object graph. Usually you want to copy the arrays only but not the contained elements.

Would love to see an example illustrating the difference between these two methods.
Besides the syntax it looks to me like they are doing the same thing.
Curious to learn more about the differences between Marshal and #dup.
    arr = [ [['foo']], ['bar']]
    foo = arr.clone
    p arr #=> [[["foo"]], ["bar"]]
    p foo #=> [[["foo"]], ["bar"]]
    foo[0][0] = 42
    p arr #=> [[42], ["bar"]]
    p foo #=> [[42], ["bar"]]

    arr = [ [['foo']], ['bar']]
    foo = Marshal.load Marshal.dump arr
    p arr #=> [[["foo"]], ["bar"]]
    p foo #=> [[["foo"]], ["bar"]]
    foo[0][0] = 42
    p arr #=> [[["foo"]], ["bar"]]
    p foo #=> [[42], ["bar"]]

    arr = [ [['foo']], ['bar']]
    foo = arr.map(&:dup)
    p arr #=> [[["foo"]], ["bar"]]
    p foo #=> [[["foo"]], ["bar"]]
    foo[0][0] = 42
    p arr #=> [[["foo"]], ["bar"]]
    p foo #=> [[42], ["bar"]]

A: The marshal trick also clones the elements of the array
array = [[Object.new]]

Check object_id of the element before and after the copy
array.first.first.object_id
# => 70251489489120

array.map(&:dup).first.first.object_id
# => 70251489489120 -- the same

(Marshal.load Marshal.dump array).first.first.object_id
# => 70251472965580 -- different object!

Don't use the marshalling trick unless you really want to deep copy an entire object graph. Usually you want to copy the arrays only but not the contained elements.


text:
Q: Box nao flutua a esquerda(float:left nao funciona) entao pessoal, estou começando a estudar html e css, estou tentando fazer uma pagina com um menu lateral com a homescreen ao lado, porem a box da homescreen nao sobe para o lado da barra de menu, nao sei se o codigo ta errado, se alguem puder ajudar... agradeço, segue o html e css abaixo:

* {
  margin: 0;
  padding: ;
  font-family: roboto;
}
.menu {
  background-color: #052e40;
  width: 200px;
  height: 100vh;
  text-align: right;
  vertical-align: middle;
  display: table-cell;
  line-height: 50px;
  padding-right: 50px;

}
a {
  text-decoration: none;
    color: #15b6ff;
}
li {
   list-style-type: none;
}
@font-face {
    font-family: 'roboto';
    src: url('roboto.ttf');
    font-weight: normal;
    font-style: normal;
}
.menu nav ul li a:hover {
  color: white;
}
hr {
  color: #15b6ff;
}
.home {
  background-color: red;
  width: 300px;
  height: 100vh;
  float: left;
}
<!DOCTYPE HTML>

  <meta charset="utf-8">
  <meta name="author" content="Nil">
  <meta name="description" content="Site Simples">
  <link rel="stylesheet" href="este.css">

Pagina Inicial

Quem Somos Nós

Cursos

Pré-Matricula

Fale Conosco

  Pagina Inicial

A: Cara o principal problema é que vc simplesmente colocou o float no elemento errado, vc tem colocar o float no primeiro elemento, assim o segundo elemento "flutua" ao lado do primeiro entende.
O problema é que ando vc coloca float em um elemento ele muda de escopo, e perde seus valores de referência no fluxo de conteúdo da página, então eu tive que fazer uns ajustes no seu código.
Veja abaixo como ficou, repare que o float:left é na barra da esquerda.
EDIT: Mudei um pouco o código devido ao comentário do autor da pergunta. Agora o Menu fica fixo a esquerda, e durando o scroll só as Sessões vão se mover a direita do Menu. Para fixar o Menu basta colocar o position:fixed assim ele não vai se mover durante o scroll. Já ppara afastar as Sessões e não deixa-las ficar por baixo do Menu basta adicionar nelas um margin-left: 250px;, onde 250px é equivalente a largura da coluna do Menu.

html, body {
    width: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
}

* {
    margin: 0;
    padding: 0;
    font-family: roboto;
}

.menu {
    background-color: #052e40;
    width: 200px;
    height: 100vh;
    text-align: right;
    line-height: 50px;
    float: left;
    /* vertical-align: middle;
    display: table-cell; */
    display: flex;
    align-items: center;
    padding-left: 50px;
    position: fixed;
}

a {
    text-decoration: none;
    color: #15b6ff;
}

li {
    list-style-type: none;
}

@font-face {
    font-family: 'roboto';
    src: url('roboto.ttf');
    font-weight: normal;
    font-style: normal;
}

.menu nav ul li a:hover {
    color: white;
}

hr {
    color: #15b6ff;
}

.home {
    background-color: red;
    /* width: 300px; */
    height: 100vh;
    margin-left: 250px;
}
.home2 {
    background-color: green;
    /* width: 300px; */
    height: 100vh;
    margin-left: 250px;
}

Pagina Inicial

Quem Somos Nós

Cursos

Pré-Matricula

Fale Conosco

        Pagina Inicial

        Pagina 2


text:
Q: How can I inject context when testing components? The issue I'm facing is that when I inject the context, my test is seeing the default context I set in MahContext. I've tried using Shallow, I've tried it without the context wrapper around the values and it doesn't matter. Shallow gives me an empty object, which is odd. I've also tried adding childContextTypes: { mahContext: PropTypes.object } to the second parameter in mount and shallow to no avail.
My Context (with default):
const MahContext= React.createContext({ id: 0, name: '' })

My Provider:
const MahProvider = props => (
    <MahContext.Provider value={props.value}>
        {props.children}
    </MahContext.Provider>
)

The component tree (in app.js):
<MahProvider value=({9, "Johnny Utah"})>
    <ParentOfMahComponent />
</MahProvider>

My component to test:
class MahComponent extends Component {
    ...
    async componentDidMount() {
        // for my test, results in 0 and '', the defaults
        // which causes my test to fail as there is a validity check
        // following
        const { id, name } = this.context
    }
}

MahComponent.contextType = MahContext

My test:
const component = mount(
    <MahComponent />,
    {
        context: {
            id: 7,
            name: "John Wick"
        }
    }
}


text:
Q: What is referenceId in Oracle database We create some column named referenceId but when we do a simple select on this column we must to add double quote. If we don't specify double quote with have an invalid identifier exception from Oracle database. Why?
I see this post which has the same problem. But no response.
In order to correct this we must to generate the column in upper case. (In fact when we have create the column we use double quote on column name)
What is referenceId? Is it a Oracle keyword?

A: No it is not a keyword. You did not mention which tool you used to create that column. I think this is most important to mention. Oracle object names are case-sensitive - sometimes. They are case sensitive when used in double quotes - otherwise the case does not matter.
So:
alter table add column test number; -- will add column named TEST
alter table add column TEST number; -- will add column named TEST
alter table add column "Test" number; -- will add column named Test

So the 3rd one column name is case-sensitive and must use double-quotes whenever referenced. The column name "TEST" is then different from "Test".
PS: Using case-sensitive object names can lead to various problems. Avoid it.


text:
Q: Subscribe - Angular 2 I have a file where I code my whole connection with the REST service, and it works.
From another file, I am executing the following lines (everything works)
 this.baseService.getCars(ID)
    .subscribe(cars=> this.cars= cars);

To access to the values of the response I was using HTML. For example: *ngIf="cars"
Now, I would like to access by Javascript to the variable doing this:
this.baseService.getCars(ID)
        .subscribe(cars=> this.cars= cars);
console.log(this.cars)

but I get undefined but I can access by HTML. I know that it is a stu**d question, but how should I do it? Which variable does contain the variable?

A: The execution order of those lines of code is not what you think it is.
To see cars in console, change your function to this:
this.baseService.getCars(ID)
        .subscribe(cars=>{
    this.cars= cars;
    console.log(this.cars);
});

A: You need to place the console.log inside subscribe
  this.baseService.getCars(ID)
  .subscribe(
    cars=> {
      this.cars= cars;
      console.log(this.cars);
    },
    error => {
      console.log(error);
    }
  );

A: Subscribe is asynchronous, like a Promise, but isn't a Promise so, when you execute the code, the subscribe is fired, then the console log. But When the console.log is executing, subscribe is running yet, so that's why you get undefined.
You can do the console.log inside the callback function in subscribe
this.baseService
    .getCars(ID)
    .subscribe(cars=> {
        this.cars = cars
        console.log(this.cars)
    });

Another solution is to use async/await. You can't use async/await directly with subscribe, because IT'S NOT A PROMISE. Fortunately Observers can be converted to a Promise.
So, in you service you can return a promise, like this:
getCars() {
    // your service stuff
    return this.api.get(url).toPromise().then( res => res.data); // This is the important part.
}

Then, in your component, call it with async/await:
async yourFunction() {
    this.cars = await this.baseService.getCars(ID);
    console.log(this.cars);
}

Now you can log this.cars after the getCars()
Hope this helps you.


text:
Q: Format datetime php A.M and P.M I have it this way AM/PM
I would like to know if the AM / PM format can put a point in between
this is the code that I use
$pm =$format->format('d/m/Y H:i:s.00 a.');

result A.M or P.M

A: You can change in below code as per you want.
$currentDateTime=date('m/d/Y H:i:s');
$newDateTime = date('h:i A', strtotime($currentDateTime));
echo $newDateTime;


text:
Q: storybook doesn't work with node7 with webpack + babel? I am using node7.2.1 and npm 5.6.0 in a react project. The project is managed by webpack2. I tried to add storybook in this project but failed on compilation. The error I got when run storybook is:
TheFrontEnd/node_modules/@storybook/core/dist/server/build-static.js:31
async function compileManager(managerConfig, managerStartTime) {
      ^^^^^^^^
SyntaxError: Unexpected token function
    at Object.exports.runInThisContext (vm.js:78:16)
    at Module._compile (module.js:543:28)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:488:32)
    at tryModuleLoad (module.js:447:12)
    at Function.Module._load (module.js:439:3)
    at Module.require (module.js:498:17)
    at require (internal/module.js:20:19)

I know there is something to do with es6 syntax. But I have created a .babelrc file under .storybook/ directory but it doesn't seem to help. The babel file I added is:
{
  "presets": [
    "es2015",
    "stage-2",
    "react"
  ],
  "plugins": [
    "transform-decorators-legacy",
    "transform-class-properties",
    "transform-async-to-generator",
    "transform-object-rest-spread",
    "add-module-exports",
    "react-hot-loader/babel"
  ]
}

The webpack file for storybook is: (.storybook/webpack.config.js)
module.exports = {
  plugins: [
    // your custom plugins
  ],
  module: {
    rules: [
      // add your custom rules.
    ],
  },
};

A: Storybook unfortunately requires Node 8.6+: https://github.com/storybooks/storybook/blob/next/package.json#L190-L193
https://github.com/storybookjs/storybook/issues/6510
Storybook has required at least Node 8+ since version 3.0 at the beginning of 2018:
https://github.com/storybookjs/storybook/blob/89af8fe76f21bd89d7c86c6134bce030873122bc/package.json
Node 7, Node 6 and below are therefore out of the picture for a long time now.


text:
Q: WPF: Command hindering button to enable I have 2 buttons.. at the beginning one of them is enabled and the other is not. Then I have 2 commands for these buttons which I need to implement keybindings for them. These commands should also replace the click-methods for the buttons.
When the first button is clicked the second button should become enabled. But it is not working. If I remove the command of the second button and add a click-method instead it works..
xaml:
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication1"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <RoutedUICommand x:Key="first" />
        <RoutedUICommand x:Key="second" />
    </Window.Resources>
    <Window.CommandBindings>
        <CommandBinding Command="{StaticResource first}" Executed="CommandBinding_Executed_1" />
        <CommandBinding Command="{StaticResource second}" CanExecute="CommandBinding_CanExecute" Executed="CommandBinding_Executed" />
    </Window.CommandBindings>
    <Window.InputBindings>
        <KeyBinding Key="F4" Command="{StaticResource first}" />
        <KeyBinding Key="F5" Command="{StaticResource second}" />
    </Window.InputBindings>
    <Grid>
        <Button Command="{StaticResource first}" x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="154,146,0,0" VerticalAlignment="Top" Width="75"/>
        <Button Command="{StaticResource second}" IsEnabled="False" x:Name="button1" Content="Button" HorizontalAlignment="Left" Margin="312,146,0,0" VerticalAlignment="Top" Width="75"/>
    </Grid>
</Window>

xaml.cs
using System.Windows;
    using System.Windows.Input;

    namespace WpfApplication1 {
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window {
            public MainWindow() {
                InitializeComponent();
            }

            private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e) {
                MessageBox.Show("Test");
            }

            private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
                e.CanExecute = button1.IsEnabled;
            }

            private void CommandBinding_Executed_1(object sender, ExecutedRoutedEventArgs e) {
                button1.IsEnabled = true;
            }
        }
    }

A: When CanExecute is defined, the button is en- or disabled based on the value of e.CanExecute, therefor setting IsEnabled explicitly has no effect, since it is set implicitly.
You could introduce a variable that is returned by CommandBinding_CanExecute - this would have the desired effect as far as I can tell.
public partial class MainWindow : Window {

    // other details elided

    bool _enableButton1 = false;

    private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e) {
        e.CanExecute = _enableButton1;
    }

    private void CommandBinding_Executed_1(object sender, ExecutedRoutedEventArgs e) {
        enableButton1 = true;
    }
}

Anyway, you could elide the CanExecute-action altogether and just set IsEnabled explicitly. This will do the trick as well.
public partial class MainWindow : Window {

    // elided

    private void CommandBinding_Executed_1(object sender, ExecutedRoutedEventArgs e) {
        button1.IsEnabled = true;
    }
}

A: Why Button.IsEnabledDoesNotWork? Thought it was setting in XAML
because Command Overrides the IsEnabled functionality.

  public partial class SampleWindow : Window
    {
        private bool _isButton1Enabled = false;
        public SampleWindow()
        {
            InitializeComponent();
        }

        private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("Test");
        }

        private void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            try
            {
                e.CanExecute = _isButton1Enabled;
            }
            catch (Exception)
            {

                throw;
            }
        }

        private void CommandBinding_Executed_1(object sender, ExecutedRoutedEventArgs e)
        {
            _isButton1Enabled = true;

        }
    }


text:
Q: In bash, how do I set a variable to encompass a variable number of command line arguments? I'm using bash shell.  I'm writing a script and I would like to capture a variable number of arguments passed to my script after and including argument #5.  So far I have this …
#!/bin/bash
…
declare -a attachments
attachments=( "$5" )

But what I can't figure out is how to write the "attachments" line to encompass argument #5 and any arguments that follow that.  So in the following example
sh my_script.sh arg1 arg2 arg3 arg4 "my_file1.csv" "my_file2.csv"

I would want attachments to consist of "my_file1.csv" and "my_file2.csv," whereas in this example …
sh my_script.sh arg1 arg2 arg3 arg4 "my_file1.csv" "my_file2.csv" "my_file3.csv"

I would want attachments to contain "my_file1.csv," "my_file2.csv," and "my_file3.csv."

A: srcdir=$1
destdir=$2
optflag=$3
barflag=$4
attachments=( "${@:5}" )

A: The usual idiom is to capture the fixed arguments into variables, and then the remainder are available as "$@":
srcdir="$1"; shift
destdir="$1"; shift
optflag="$1"; shift
barflag="$1"; shift

(cd "$destdir" && mv -t "$destdir" "-$optflag" "$@" )

This idiom easily extends should you find the need for a variable number of arguments preceding the list:
while [ "${1#-}" != "$1" ]
do
    case "$1" in
      -foo) foo="$2";shift 2 ;;
      -bar) bar="$2";shift 2 ;;
      -baz) bar=true;shift 1 ;;
      --) shift; break;
    esac
done
# rest of arguments are in "$@"


text:
Q: My website is not showing the lock (SSl Certificate) i am using wordpress, i have changed all website urls and images to https but the lock screen is not showing. I am using comodo ssl. Also i use a https redirect plugin. Any ideas? My website is www.tsigaradiko.com. Seems i have mixed http with https content but if you open all the images all direct to an https address

A: it seems like you are using there "http://" assets. take a look in the developer's console and you'll see few errors like this one:

Mixed Content: The page at 'https://www.tsigaradiko.com/' was loaded
  over HTTPS, but requested an insecure image
  'http://www.tsigaradiko.com/wp-content/uploads/2016/05/to-tsigaradiko-email.jpg'.
  This content should also be served over HTTPS.

When it will be switched, everything will be ok and the green lock sign will appear.
To open the console, click Ctrl + Shift + J or  Cmd + Opt + J, depends on your OS.
If you have a lot of pages, i recommend using This tool for fast crawling of your website.
Good luck!


text:
Q: Why is axios returning a different responseURL than the request url? I am making an Axios GET request from my React Native app to my locally served backend.
The response "config" object shows a "baseURL" of "http://192.168.1.68:8080/api" and a "url" of "inventory?status=ALL&barcode=127035838".
The response "request" object shows a "_url" of "http://192.168.1.68:8080/api/inventory?status=ALL&barcode=127035838".
However! the response "responseURL" attribute shows a value of "http://192.168.1.68:8080/api/inventory?status=ALL&barcode=127035838%1D".
The request from the app is not finding the barcode, returning 204. Making the same request from Postman, I am able to find the barcode with a 200 status. This makes me believe the issue is not on the backend. I switched from Axios to fetch and found the same result.
It is my guess the additional "%1D" on the end of the barcode is the cause of frustration. Why is the rsponseURL different from the request url. Why is axios adding "1%D", and how can I make it stop? Is there something else going on?
My solution:
let uriSN = serialNumber;
uriSN = encodeURIComponent(serialNumber);
uriSN = uriSN.replace('%1D', '');

Encoding the barcode and then stripping it of the "1%D" solves the issue. I do not know if it is the best or complete solution.

A: %1D is the url-encoded hex for 29 which is an ASCII control character called the "group seperator" so your serialNumber might have this character which is being parsed accordingly (by design) through the encodeURIComponent function. This is known as "GIGO" (garbage in garbage out).


text:
Q: How to collect the responses from aiohttp sessions I'm working with asyncio and aiohttp to call an API many times.  While can print the responses, I want to collate the responses into a combined structure - a list or pandas dataframe etc.
In my example code I'm connecting to 2 urls and printing a chunk of the response. How can I collate the responses and access them all?
import asyncio, aiohttp

async def get_url(session, url, timeout=300):
    async with session.get(url, timeout=timeout) as response:
        http = await response.text()
    print(str(http[:80])+'\n')
    return http    # becomes a list item when gathered

async def async_payload_wrapper(async_loop):
    # test with 2 urls as PoC
    urls = ['https://google.com','https://yahoo.com']
    async with aiohttp.ClientSession(loop=async_loop) as session:
        urls_to_check = [get_url(session, url) for url in urls]
        await asyncio.gather(*urls_to_check)

if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()
    event_loop.run_until_complete(async_payload_wrapper(event_loop))

I've tried printing to a file, and that works but it's slow and I need to read it again for further processing. I've tried appending to a global variable without success. E.g. using a variable inside get_url that is defined outside it generates an error, eg:
NameError: name 'my_list' is not defined or
UnboundLocalError: local variable 'my_list' referenced before assignment

A: Thanks @python_user that's exactly what I was missing and the returned type is indeed a simple list. I think I'd tried to pick up the responses inside the await part which doesn't work.
My updated PoC code below.
Adapting this for the API, JSON and pandas should now be easy : )
import asyncio, aiohttp

async def get_url(session, url, timeout=300):
    async with session.get(url, timeout=timeout) as response:
        http = await response.text()
    return http[:80]    # becomes a list element

async def async_payload_wrapper(async_loop):
    # test with 2 urls as PoC
    urls = ['https://google.com','https://yahoo.com']
    async with aiohttp.ClientSession(loop=async_loop) as session:
        urls_to_check = [get_url(session, url) for url in urls]
        responses = await asyncio.gather(*urls_to_check)
    print(type(responses))
    print(responses)

if __name__ == '__main__':
    event_loop = asyncio.get_event_loop()
    event_loop.run_until_complete(async_payload_wrapper(event_loop))


text:
Q: How to pass AWS secret key and id in jenkins build pipeline script? I am trying to pass the AWS secret key and password into jenkins script (which creates the env file)
My code:
node {

    writeFile file: 'temp_env.txt', text: """
    AWS_ACCESS_KEY= << Access Key >>
    AWS_SECRET_KEY= << password >>
  """
docker.withRegistry('https://quay.io', 'c5234316dc-dqwqwda1-415645452-b343-406bf8332edb') {

        sh 'docker pull quay.io/docker_image'
        docker.image ('quay.iodocker_image').run('-it --env-file temp_env.txt --name test quay.io/docker_image:develop ./code/test1.py test-service')
        sh 'rm temp_env.txt'
    }
}

I am using the actual secret key and id, i would rather have the credentials injected here. How can I achieve it? I read the entire instructions here but was not able to figure out.
I know how to use the credentials binding plug-in, but not sure how I can add the user_name and password credentials variables to my code.

A: The idea of those instructions is to first store those credentials in the Credentials section of Jenkins, from the Jenkins Credential Biding plugin, as shown here

Once there are safely stored there, you can declare them in an environment step:
environment {
    AWS_ACCESS_KEY_ID     = credentials('jenkins-aws-secret-key-id')
    AWS_SECRET_ACCESS_KEY = credentials('jenkins-aws-secret-access-key')
}

A: Solution: The best practice for storing credentials, api tokens and secret keys is to store it on global credentials in jenkins ( this applies to all scope of credentials in the project/item/object) and get it pipeline code. This methodology prevents users storing sensitive data in plain-text insecurely on their code/project.

I'll demonstrate it with short example: On this example I'll store an api token of my app in Jenkins credentials ,get it in my pipeline step and curl it to perform some rest api HTTP operation on my server.

First Store it:

Jenkins -> Credentials -> Global -> Add Credentials -> Select your
  type and fill in the details

In my example I create secret text with secret xxx, the ID would be MY_SECRET_TOKEN and the description would be my secret token for my api service. Than I'll save it and my pipeline would be like below...
script{
   withCredentials([
      string(
         credentialsId: 'MY_SECRET_TOKEN',
         variable: 'TOKEN_VARIABLE')
      ]) {
      sh """#!/bin/bash
         curl -k -L -H 'Authorization: Token ${TOKEN_VARIABLE}'
         https://myservice/api/users/someaction/
      """
  }
}

For more information look on the documentation


text:
Q: How program find global variable inside stack? As far as I know, when I declare global variable int my_var;,
It's at fixed address in <bss>(uninitialized global data) or <.rodata>(initialize global data) section.
ex)
int my_var;          // <= It is at <.bss> section
int my_var = 0x1337; // <= It is at <.rodata> section

So, program can find those static values using fixed address.

Problem: However, I heard about global variable located in <stack>.

C runtime startup initialize global variable: __environ, program_invocation_name
And They are located in <stack>.... which means its address is not fixed.
Question. How program can finds global variable inside stack (non-fixed region) ?

A: __environ, etc... are not located within the stack; they are normal global variables which are pointers (that is, a variable whose value is an address) to locations within the stack.   The fact that the initial program environment, arguments, etc... are in the stack is an implementation detail.  They could just as easily be allocated in the heap, or in some other area to suit the runtime.
The only thing that is important is that the runtime startup and operating system agree on where to find them.
[ responding to comment ]
The program below should illustrate:
#include <stdio.h>
extern char **environ;

int main() {
 int x;
 printf("&envrion  = %p\n", &environ);
 printf("environ   = %p\n", environ);
 printf("*environ  = %p [%s]\n", *environ, *environ);
 printf("&x        = %p\n", &x);
 return 0;
}

on my system, when run (cc -static x.c; ./a.out), generates:
&envrion  = 0x6bbda8
environ   = 0x7ffdd6edb3e8
*environ  = 0x7ffdd6edb9a2 [CLUTTER_IM_MODULE=xim]
&x        = 0x7ffdd6edb2a4

Notice how &environ is at a much different address than environ, *environ and &x.  That is because the latter are within the stack, while environ itself is not.

A: Can you provide an example or reference to a book indicating a global variable stored on the stack?
The point of the stack is to allocate memory according to the scope of the (temporal) variables, so it doesn't make sense to use the stack for an "always-alive" variable (as you said, there are another sections for that purpose).
Regarding your example (int my_var = 0x1337;), an initialised variable may not be allocated on a read-only section, because it doesn't mean that it won't be modified at some moment (besides of compiler's decisions).

Question. How program can finds global variable inside stack (non-fixed region) ?

The stack is a LIFO queue, in which a pointer indicates the lastest position, and each temporal variable gets an address (when it is created, within stack boundaries) that indicates its location, until it is destroyed (out of scope) and the stack pointer is updated. But environment variables are not stored on the stack, they are above it: https://www.thegeekstuff.com/2012/03/linux-processes-memory-layout/


text:
Q: Cannot see project.clj in leiningen project using intelliJ idea? I am using IntelliJ Idea 12.14 Community Edition on Windows 7.
I have installed leiningen separately.
I was trying to create a new project using idea.
I have also installed the La Clojure plugin and re started Idea several times.
Neither do I find options to create a Clojure project nor is the "project.clj" being visible to  open project dialogue in intelliJ for an existing  project.

A: Seems the project won't be openable until you also install the Leiningen plugin.  The wiki shows it as browsable in the default repository but I didn't find it.  I wound up just downloading it from here:
http://plugins.jetbrains.com/plugin/?id=5029
After install, the .clj file was openable as a project.

A: There is no integration with leiningen, so you cannot open a project.clj directly. If you really want to use IDEA, I would recommend to either:

*

*Use maven and the clojure-maven-plugin

*Use lein pom to generate a pom.xml and then import that pom. This will give you a project with the proper dependencies and LaClojure will give you a repl, autocomplete, code navigation, etc. You will need to run lein pom when you change dependencies and use the command line for any other build commands.


text:
Q: Procurar o índice de um array que case com uma expressão regular De acordo com o Manual do PHP, a função preg_grep retorna as entradas de um array que combinam com a expressão regular.
Exemplo
$array = [
    'Banana',
    'Maçã',
    'Café',
    'Biscoito',
];

$array_com_B = preg_grep('/^B/i', $array);

Resultado:
['Banana', 'Biscoito']

Porém não existe nenhuma função com essa funcionalidade para procurar os índices de um array que casem com uma expressão regular.
Eu gostaria de retornar as chaves do array exemplificado abaixo que casem com a expressão regular /^(id|nome)$/i.
[
   'id' => 3,
   'idade' => 25,
   'nome'  => 'Wallace de Souza',
   'profissão' => 'Programador',

]

A: Se você combinar as funções array_keys, array_intersect_keys e array_flip, vai conseguir o que quer:
$dados = [
    'id'        => 3,
    'idade'     => 25,
    'nome'      => 'Wallace de Souza',
    'profissão' => 'Programador',
];

$chaves = preg_grep('/^(id|nome)$/', array_keys($dados));
$dados = array_intersect_key($dados, array_flip($chaves));

Retorno:
Array
(
    [id] => 3
    [nome] => Wallace de Souza
)


text:
Q: Converting java.sql.Timestamp to java.util.Calendar without losing precision I'm trying to fetch timestamp values from a database, convert them to Calendar, and convert them back to Timestamp, but they lose their precision.
Here's the code to reproduce the problem
import java.sql.Timestamp;
import java.util.Calendar;

public class Test {
    public static void main(String[] args)
    {
        Timestamp timestamp = new Timestamp(112, 10, 5, 15, 39, 11, 801000000);
        System.out.println("BEFORE "+timestamp.toString());
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(timestamp.getTime());
        timestamp = new Timestamp(calendar.getTimeInMillis());
        System.out.println("AFTER "+timestamp.toString());
    }
}

Here is the sample result of conversion
BEFORE 2012-10-18 14:30:13.362001
AFTER 2012-10-18 14:30:13.362

It loses its precision.
What do I do to keep the decimal value as it is?

A: java.time
In Java 8 and later we now have a solution: the new java.time framework is built in. Defined by JSR 310, inspired by Joda-Time, extended by the ThreeTen-Extra project.
This new framework has nanosecond resolution. That's enough to handle the old java.util.Date values, Joda-Time values, both being milliseconds. And it's enough to handle the microseconds used by some databases such as Postgres. Some databases such as H2 use nanoseconds. So java.time can handle it all, or least all the mainstream situations. The only exceptions would be niche scientific or engineering situations.

With Java 8, the old classes got new methods for converting to/from java.time. On java.sql.Timestamp use the new toInstant and fromInstant methods. The Instant class contains a count of nanoseconds from epoch, first moment of 1970 UTC (basically, see class doc for details).
From an Instant you can get a ZonedDateTime object.
java.sql.Timestamp ts = myResultSet.getTimestamp( 1 );
Instant instant = ts.toInstant();
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( zoneId );

A: You are setting the time in milliseconds, but your input precision is in microseconds, so of course you are going to lose any precision finer than milliseconds.
Calendar doesn't support finer granularity than milliseconds. There is no work-around.


text:
Q: How to get 2 numbers from user input and display the sum in the console? Using Swift     import Foundation

    print("Type your age: ")

    if let input = readLine() {
        print("You typed \(input)\n")
    }

**I used that before but I dont know how to add them and display it in the console.

A: import Foundation

print("enter number one: ")
var sum = 0
if let num1 = Int(readLine()!) {
  sum += num1
}
print("enter number two: ")
if let num2 = Int(readLine()!) {
  sum += num2
}

print(sum)

start by creating a sum variable, then for each operand, take an input and cast it to an integer which you can add to the sum via the addition assignment operator.

A: Create macos command line tool project.
import Foundation

print("Type two input: ")

if let input1 = readLine(), let input2 = readLine(), let value1 = Int(input1), let value2 = Int(input2) {
    print("Sum=\(value1+value2)")
}

Step 1

Step 2


text:
Q: How do I validate that a listbox is not empty in C# winforms using an errorProvider I have an errorProvider control. I would like to use it to validate if a listbox contains at least an element.
Here's my code to register the validating event:
this.selectedFieldsArea.Validating +=new CancelEventHandler(selectedFieldsArea_Validating);

And here is my validating function:
private void selectedFieldsArea_Validating(object sender, CancelEventArgs e)
{
    if (this.selectedFieldsArea.Items.Count == 0)
    {
        errorProvider1.SetError(selectedFieldsArea, "Need to select at least 1 field");
        e.Cancel = true;
    }
    else
        errorProvider1.SetError(selectedFieldsArea, "");
}

Although I registered the method it is never called. Have I forgotten to do something?

A: In order for the _validating event to be fired, the Validate() or ValidateChildren() method has to be called. I added this in my button_Click() event and it now works.


text:
Q: HTTP status code for "never going to exist" I'm building a service where resources are divided into categories, e.g. example.com/category/foo would represent "foo" (think: similar to SO tags).
New categories may be added at any time and, when attempting to view a category that doesn't yet exist, users would be able to suggest it added.
However, I'd like to just outright ban some category names (e.g. NSFW terms). This means that (assuming "bar" is one such name) example.com/category/bar not only never existed, but is guaranteed never to exist in the future.
Which HTTP status code is appropriate for this situation?
Several ideas come to mind:

*

*410 Gone - while this makes it clear the resource will not be available in the future, I'm not sure if it's appropriate as it also seems to imply it used to exist in the past.

*400 Bad Request - the request is technically not malformed, so this is probably not the way to go.

*404 Not Found initially seemed like the logical option, but doesn't convey the permanence of the ban, especially since I plan to use 404 for categories that don't yet exist, but can be suggested.

*301 Moved Permanently and redirect to another page, either the home page or some other page explaining that some category names are banned.

A: I don't think there's such a thing as "will never exist" in the specs of HTTP. Let's think about it slightly differenly :

*

*the resource is created through your website (and only through your website). If a resource is created, that means that whatever validation you put in place succeeded.

So to keep it simple stupid, you should stick to HTTP semantics. If someone hits a URL : example.com/category/{cat}, either you know {cat} (it's in your DB and has a valid name, right?) and process the request safley, or you have never seen {cat} before and you just return 404.
After all there's an infinity of possible values that one could use for {cat} and all of them would be valid URLS.
Hope it helps

A: I would suggest a 410 Gone is an appropriate response, assuming that your web clients are common and implement the http spec correctly (most popular ones do).
When looking on this page here: Status Code Definitions
The section about 410 gone says:

10.4.11 410 Gone
The requested resource is no longer available at the server and no
  forwarding address is known. This condition is expected to be
  considered permanent. Clients with link editing capabilities SHOULD
  delete references to the Request-URI after user approval. If the
  server does not know, or has no facility to determine, whether or not
  the condition is permanent, the status code 404 (Not Found) SHOULD be
  used instead. This response is cacheable unless indicated otherwise.
The 410 response is primarily intended to assist the task of web
  maintenance by notifying the recipient that the resource is
  intentionally unavailable and that the server owners desire that
  remote links to that resource be removed. Such an event is common for
  limited-time, promotional services and for resources belonging to
  individuals no longer working at the server's site. It is not
  necessary to mark all permanently unavailable resources as "gone" or
  to keep the mark for any length of time -- that is left to the
  discretion of the server owner.

I take that to mean the resource definitely does not exist now and will not exist in the future, giving the permanence that you want, and it is also cachable unless stated otherwise.
Usually I would not need to know that it had "never existed before", I just know that it doesn't exist right now when i'm requesting information about it, and it is not going to exist in the future if i request it again.  If I did need to learn that certain categories never existed in the past (e.g. a blacklist of categories), i would probably want a separate explicit request that I could use to get all of those categories rather than having to check each category one at a time at run time.


text:
Q: Adding duplicate values in sql I'm just a newbie in programming and I'm having a problem with this (see table below).
    DocNum  DocDate   Quantity  ItemGroupCode   ItemGroupName
    89226   7-Nov-12    10     103            Fish-Fillet
    88768   8-Nov-12    1      104            Fish-Regular
    88856   6-Nov-12    2      104            Fish-Regular
    88678   20-Nov-12   12     109            Value Added
    89415   5-Nov-12    12     109            Value Added
    88642   5-Nov-12    1      112          Other Charges
    88646   5-Nov-12    20     112          Other Charges
    88729   7-Nov-12    5.64   112          Other Charges
    88804   12-Nov-12   10     112           Other Charges
    88992   12-Nov-12   1      112             Other Charges

I want to combine similar Code of ItemGroupCode column then Add its Quantity.
EX.
Quantity    ItemGroupCode   ItemGroupName
10              103          Fish-Fillet
3               104          Fish-Regular
24              109          Value Added
38.64           112          Other Charges

Thanks ...
Pipay

A: Try this:
select sum(quantity) quantity, itemgroupcode, itemgroupname
from table_name
group by itemgroupcode, itemgroupname

For your question if I understand correctly, you need from the select you provide in your comments, to have the output of the first question. If this is the case then try something like this:
SELECT SUM(quantity), ItemGroupCode, ItemClass
FROM
(SELECT A.DocNum, A.DocDate, B.Quantity,B.Price,B.Linetotal, A.Doctotal, C.ItemName, C.ItmsGrpCod as ItemGroupCode,
       D.ItmsGrpnam as ItemClass
FROM OINV as A LEFT outer JOIN INV1 As B ON A.DocEntry = B.DocEntry
               LEFT OUTER JOIN OITM As C ON B.ItemCode = C.ItemCode
               LEFT OUTER JOIN OITB As D ON C.ItmsGrpCod = D.ItmsGrpCod
WHERE A.DocDate >= '11/01/2012'
group by A.DocNum, A.DocDate, B.Quantity,B.Price,B.Linetotal, A.Doctotal, C.ItemName, C.ItmsGrpCod, D.ItmsGrpnam
order by C.ItmsGrpCod ASC) X
GROUP BY X.ItemGroupCode, X.ItemClass


text:
Q: get the logged in RDP user in Python I don't know much about RDP, so this question may not make sense but:
What is the correct way to detect, in Python, which user is currently logged into the server through RDP?
Would the answer to this question: Is there a portable way to get the current username in Python? work as well on a remoted log in?


text:
Q: How To Disable M2E Lifecycle Validation With Eclipse Mars comes the feature that M2E does not work like it used to. Lifecycle plug-ins are not found or are found twice, bringing curious error messages like this:

Plugin execution not covered by lifecycle configuration: org.acme.something:maven-plugin:1.0.0:compile (execution: default-compile, phase: compile)
Conflicting lifecycle mapping (plugin execution "org.acme.something:maven-plugin:1.0.0:compile (execution: default-compile, phase: compile)"). To enable full functionality, remove the conflicting mapping and run Maven->Update Project Configuration.

Since the Tycho integration never worked (and knowing these guys, never will) I want to disable the lifecycle validation for good. We only ever really need the M2E feature "Run as... -> Maven Build" anyways.
How do I do this?
(Just to be clear: I'm a professional, I have dozens of workspaces with dozens of projects each - using the "quickfix" on all of these to ignore them is out of the question, as is defiling my //pom.xml// with Eclipse specific ignore instructions.)

A: You have 2 solutions

*

*Open the Markers view, Quick Fix, then select "Mark goal run as ignored in Eclipse build in Eclipse Preferences". This will be a global for the workspace, won't defile any of your pom.xml files. You can then go a step further and open Preferences > Maven > Licefycle Mappings, change the mapping file location so that it can be shared by multiple workspaces.

*Open Preferences > Maven > Errors/Warnings, set Plugin Execution not covered... level to whatever works for you (and hope it doesn't cause unexpected side effects)


text:
Q: A mapping $T:\mathbb{R^n}\rightarrow \mathbb{R^m}$ is one-to-one if each vector in $\mathbb{R^n}$ maps onto a unique vector in $\mathbb{R^m}$. I'm reading Linear Algebra and Its Applications by David C. Lay, Steven R. Lay and Judi J. McDonald.
In section 1.9 exercise 24 there's a following statement

d) A mapping $T:\mathbb{R^n}\rightarrow \mathbb{R^m}$ is one-to-one if each vector in $\mathbb{R^n}$ maps onto a unique vector in $\mathbb{R^m}$.

According to Solutions Manual for the book this statement is false and I struggle to see why this is the case.

A: The statement is misleadingly phrased. What truly meant is

A mapping $T:\mathbb{R^n}\rightarrow \mathbb{R^m}$ is one-to-one if every vector $\mathbf{x}\in$ $\mathbb{R^n}$ maps onto some vector $\mathbf{b}\in$ $\mathbb{R^m}$.

, or in other words,

Is it true that if transformation $T:\mathbb{R^n}\rightarrow \mathbb{R^m}$ is consistent for every vector $\mathbf{x}\in$ $\mathbb{R^n}$ it is also a one-to-one mapping from $\mathbb{R^n}$ to $\mathbb{R^m}$?