text:
Q: insert multiple input fields before running scrapy I'm referencing a stackoverflow answer that is similar to my GUI app. My scrappy application is a bit different. When exectuing the app, a user is prompt to enter keywords for scrapy to search for
looks like this

im trying to put this logic on the GUI, but im unsure how to do it.
here is what the gui looks like as of now.

I want to be able to input fields where a user can input the information need before processing the scrapy script.
here is a bit of the scrapy script
my_spider.py
import scrapy
import sys
import random
import csv
from scrape.items import Item
from var_dump import var_dump

search_item = input("Input The Search Item: ")
location = input("Location:")
second_location = input("Second Location:")
third_location = input("Third Location:")
fourth_location = input("Fourth Location:")
fifth_location = input("Fifth Location:")
sixth_location = input("Sixth Location:")

# city = [
#     "Los Angeles", "Chicago", "Houston", "Phoenix", "Philadelphia", "San Antonio", "Fort Worth",
#     "San Diego", "Dallas", "San Jose", "Austin", "Columbus", "Indianapolis",  "Seattle", "St. Paul", "Nashville",
#     "Louisville", "Plano"
# ]

# rancity = random.choice(city)

class YellowSpider(scrapy.Spider):

    name = "yellow"

    # start_urls = [
    #     "https://www.yellowpages.com/search?search_terms=" + search_item + "&geo_location_terms=" + location
    #     # "https://www.yellowpages.com/search?search_terms=" + search_item + "&geo_location_terms=" + third_location,
    #     # "https://www.yellowpages.com/search?search_terms=" + search_item + "&geo_location_terms=" + fourth_location
    # ]

    def start_requests(self):
        yield scrapy.Request("https://www.yellowpages.com/search?search_terms=" + search_item + "&geo_location_terms=" + location, self.parse)
        yield scrapy.Request("https://www.yellowpages.com/search?search_terms=" + search_item + "&geo_location_terms=" + second_location, self.parse2)
        yield scrapy.Request("https://www.yellowpages.com/search?search_terms=" + search_item + "&geo_location_terms=" + third_location, self.parse3)
        yield scrapy.Request("https://www.yellowpages.com/search?search_terms=" + search_item + "&geo_location_terms=" + fourth_location, self.parse4)
        yield scrapy.Request("https://www.yellowpages.com/search?search_terms=" + search_item + "&geo_location_terms=" + fifth_location, self.parse5)
        yield scrapy.Request("https://www.yellowpages.com/search?search_terms=" + search_item + "&geo_location_terms=" + sixth_location, self.parse6)
        # yield scrapy.Request('http://www.example.com/3.html', self.parse)

    def __init__(self):
        self.seen_business_names = []
        self.seen_phonenumbers = []
        self.seen_websites = []
        self.seen_emails = []

    def parse(self, response):
        for href in response.css('div.v-card a.business-name::attr(href)'):
            yield response.follow(href, self.businessprofile)

        for href in response.css('div.pagination a::attr(href)'):
            yield response.follow(href, self.parse)

    def parse2(self, response):
        for href in response.css('div.v-card a.business-name::attr(href)'):
            yield response.follow(href, self.businessprofile2)

        for href in response.css('div.pagination a::attr(href)'):
            yield response.follow(href, self.parse2)

    def parse3(self, response):
        for href in response.css('div.v-card a.business-name::attr(href)'):
            yield response.follow(href, self.businessprofile3)

        for href in response.css('div.pagination a::attr(href)'):
            yield response.follow(href, self.parse3)
        ........

here is the GUI
main.py
from functools import partial
from PyQt5 import QtCore, QtGui, QtWidgets

class ScrapyWorker(QtCore.QObject):
    logChanged = QtCore.pyqtSignal(str)
    started = QtCore.pyqtSignal()
    finished = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(ScrapyWorker, self).__init__(parent)
        self._process = QtCore.QProcess(self)
        self._process.setProcessChannelMode(QtCore.QProcess.MergedChannels)
        self._process.readyReadStandardOutput.connect(self.on_readyReadStandardOutput)
        self._process.setProgram('scrapy')
        self._process.started.connect(self.started)
        self._process.finished.connect(self.finished)

    def run(self, project, spider):
        self._process.setWorkingDirectory(project)
        self._process.setArguments(['crawl', spider])
        self._process.start()

    @QtCore.pyqtSlot()
    def on_readyReadStandardOutput(self):
        data = self._process.readAllStandardOutput().data().decode()
        self.logChanged.emit(data)

    @QtCore.pyqtSlot()
    def stop(self):
        self._process.kill()

    def spiders(self, project):
        process = QtCore.QProcess()
        process.setProcessChannelMode(QtCore.QProcess.MergedChannels)
        process.setWorkingDirectory(project)
        loop = QtCore.QEventLoop()
        process.finished.connect(loop.quit)
        process.start('scrapy', ['list'])
        loop.exec_()
        return process.readAllStandardOutput().data().decode().split()

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.project_le = QtWidgets.QLineEdit()
        self.project_button = QtWidgets.QPushButton('Select Project')
        self.spider_combobox = QtWidgets.QComboBox()
        self.start_stop_button = QtWidgets.QPushButton("Start", checkable=True)
        self.text_edit = QtWidgets.QTextBrowser()
        self.input = QtWidgets.QLineEdit()
        self.input1 = QtWidgets.QLineEdit()
        self.input2 = QtWidgets.QLineEdit()
        self.input3 = QtWidgets.QLineEdit()
        self.input4 = QtWidgets.QLineEdit()
        self.input5 = QtWidgets.QLineEdit()
        self.input6 = QtWidgets.QLineEdit()
        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)

        lay = QtWidgets.QVBoxLayout(central_widget)
        hlay = QtWidgets.QHBoxLayout()
        hlay.addWidget(self.project_le)
        hlay.addWidget(self.project_button)
        lay.addLayout(hlay)
        hlay2 = QtWidgets.QHBoxLayout()
        hlay2.addWidget(QtWidgets.QLabel("Input The Search Item :"))
        hlay2.addWidget(self.input, 1)
        hlay3 = QtWidgets.QHBoxLayout()
        hlay4 = QtWidgets.QHBoxLayout()
        hlay5 = QtWidgets.QHBoxLayout()
        hlay6 = QtWidgets.QHBoxLayout()
        hlay7 = QtWidgets.QHBoxLayout()
        hlay8 = QtWidgets.QHBoxLayout()
        hlay3.addWidget(QtWidgets.QLabel("Location :"))
        hlay3.addWidget(self.input1, 1 )
        hlay4.addWidget(QtWidgets.QLabel("Location 2 :"))
        hlay4.addWidget(self.input2, 1 )
        hlay5.addWidget(QtWidgets.QLabel("Location 3 :"))
        hlay5.addWidget(self.input3, 1 )
        hlay6.addWidget(QtWidgets.QLabel("Location 4 :"))
        hlay6.addWidget(self.input4, 1 )
        hlay7.addWidget(QtWidgets.QLabel("Location 5 :"))
        hlay7.addWidget(self.input5, 1 )
        hlay8.addWidget(QtWidgets.QLabel("Location 6 :"))
        hlay8.addWidget(self.input6, 1 )
        lay.addLayout(hlay2)
        lay.addLayout(hlay3)
        lay.addLayout(hlay4)
        lay.addLayout(hlay5)
        lay.addLayout(hlay6)
        lay.addLayout(hlay7)
        lay.addLayout(hlay8)
        lay.addWidget(self.start_stop_button)
        lay.addWidget(self.text_edit)

        self.start_stop_button.setEnabled(False)

        self.scrapy_worker = ScrapyWorker(self)
        self.scrapy_worker.logChanged.connect(self.insert_log)
        self.scrapy_worker.started.connect(self.text_edit.clear)
        self.scrapy_worker.finished.connect(partial(self.start_stop_button.setChecked, False))

        self.start_stop_button.toggled.connect(self.on_checked)
        self.project_button.clicked.connect(self.select_project)
        self.resize(640, 480)

    @QtCore.pyqtSlot(bool)
    def on_checked(self, state):
        if state:
            filename = self.project_le.text()
            finfo = QtCore.QFileInfo(filename)
            directory = finfo.dir().absolutePath()
            self.scrapy_worker.run(directory, self.spider_combobox.currentText())
            self.start_stop_button.setText('Stop')
        else:
            self.start_stop_button.setText('Start')
            self.scrapy_worker.stop()

    @QtCore.pyqtSlot()
    def select_project(self):
        filename, _ = QtWidgets.QFileDialog.getOpenFileName(
            self,
            "Select .cfg file",
            QtCore.QDir.currentPath(),
            "Configure File (*.cfg)"
        )
        if filename:
            self.project_le.setText(filename)
            finfo = QtCore.QFileInfo(filename)
            directory = finfo.dir().absolutePath()
            spiders = self.scrapy_worker.spiders(directory)
            self.spider_combobox.clear()
            self.spider_combobox.addItems(spiders)
            self.start_stop_button.setEnabled(True if spiders else False)

    @QtCore.pyqtSlot(str)
    def insert_log(self, text):
        prev_cursor = self.text_edit.textCursor()
        self.text_edit.moveCursor(QtGui.QTextCursor.End)
        self.text_edit.insertPlainText(text)
        self.text_edit.setTextCursor(prev_cursor)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    app.setStyle('fusion')
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())

A: First you have to modify your spider to accept arguments directly by the console avoiding using the input() method:
yellowpage_spider.py
import json
import scrapy
from scrape.items import Item

class YellowSpider(scrapy.Spider):
    name = "yellow"

    def __init__(self, *args, **kwargs):
        super(YellowSpider, self).__init__(*args, **kwargs)
        self.seen_business_names = []
        self.seen_phonenumbers = []
        self.seen_websites = []
        self.seen_emails = []

    def start_requests(self):
        if not hasattr(self, 'parameters'):
            return
        parameters = json.loads(self.parameters)
        search_item = parameters['search_item']
        locations = parameters['locations']
        for location in locations:
            url = "https://www.yellowpages.com/search?search_terms={}&geo_location_terms={}".format(search_item, location)
            yield scrapy.Request(url=url, callback=self.parse, meta={'location': location})

    def parse(self, response):
        location = response.meta['location']
        for href in response.css('div.v-card a.business-name::attr(href)'):
            yield response.follow(href, self.businessprofile, meta={'location': location})

        for href in response.css('div.pagination a::attr(href)'):
            yield response.follow(href, self.parse, meta={'location': location})

    def businessprofile(self, response):
        location = response.meta['location']
        for business in response.css('header#main-header'):
            item = Item()
            item['business_name'] = business.css('div.sales-info h1::text').extract()
            w = business.css('a.secondary-btn.website-link::attr(href)').extract()

            item['website'] = str(w).strip('[]')

            item['location'] = location

            s = business.css('a.email-business::attr(href)').extract()
            item['email'] = [item[7:] for item in s]

            item['phonenumber'] = business.css('p.phone::text').extract_first()
            for x in item['email']:
                #new code here, call to self.seen_business_names
                if x not in self.seen_emails:
                    if item['email']:
                        if item['phonenumber']:
                            if item['website']:
                                self.seen_emails.append(x)
                                yield item

Then the previous code expects a parameter called parameters:
scrapy crawl yellow -a parameters='{"search_item": "house", "locations": ["usa", "germany", "brazil"]}'

So in the GUI we must now form the entry using the GUI inputs:
gui.py
import os
import json
from functools import partial
from PyQt5 import QtCore, QtGui, QtWidgets
import utils

dir_path = os.path.dirname(os.path.abspath(__file__))
icons_dir = os.path.join(dir_path, 'assets', 'icons')

class ScrapyWorker(QtCore.QObject):
    logChanged = QtCore.pyqtSignal(str)
    started = QtCore.pyqtSignal()
    finished = QtCore.pyqtSignal()

    def __init__(self, parent=None):
        super(ScrapyWorker, self).__init__(parent)
        self._process = QtCore.QProcess(self)
        self._process.setProcessChannelMode(QtCore.QProcess.MergedChannels)
        self._process.readyReadStandardOutput.connect(self.on_readyReadStandardOutput)
        self._process.started.connect(self.started)
        self._process.finished.connect(self.finished)

    def run(self, project, program, arguments):
        self._process.setWorkingDirectory(project)
        self._process.setProgram('scrapy')
        self._process.setArguments(arguments)
        self._process.start()

    @QtCore.pyqtSlot()
    def on_readyReadStandardOutput(self):
        data = self._process.readAllStandardOutput().data().decode()
        self.logChanged.emit(data)

    @QtCore.pyqtSlot()
    def stop(self):
        self._process.kill()

class LocationWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(LocationWidget, self).__init__(parent)
        self.lay = QtWidgets.QVBoxLayout(self)
        self.lay.setContentsMargins(0, 0, 0, 0)
        self.lay.addStretch()
        self.setContentsMargins(0, 0, 0, 0)
        self.widgets = []
        self.create_row()

    def create_row(self):
        widget = QtWidgets.QWidget()
        widget.setContentsMargins(0, 0, 0, 0)
        hlay = QtWidgets.QHBoxLayout(widget)
        hlay.setContentsMargins(0, 0, 0, 0)
        lineedit = QtWidgets.QLineEdit()
        button = QtWidgets.QToolButton(clicked=self.on_clicled)
        button.setFocusPolicy(QtCore.Qt.NoFocus)
        hlay.addWidget(lineedit)
        hlay.addWidget(button)
        button.setIconSize(QtCore.QSize(24, 24))
        button.setIcon(QtGui.QIcon(os.path.join(icons_dir, 'add.png')))
        self.widgets.append(widget)
        self.lay.insertWidget(-1, widget)

    @QtCore.pyqtSlot()
    def on_clicled(self):
        button = self.sender()
        widget = button.parentWidget()
        if self.lay.indexOf(widget) == (self.lay.count()-1):
            self.create_row()
        else:
            self.lay.removeWidget(widget)
            widget.deleteLater()
            self.widgets.remove(widget)
        for widget in self.widgets:
            button = widget.findChild(QtWidgets.QToolButton)
            button.setIcon(QtGui.QIcon(os.path.join(icons_dir, 'remove.png')))
        self.widgets[-1].findChild(QtWidgets.QToolButton).setIcon(QtGui.QIcon(os.path.join(icons_dir, 'add.png')))

    def get_locations(self):
        locations = []
        for widget in self.widgets:
            le = widget.findChild(QtWidgets.QLineEdit)
            if le.text():
                locations.append(le.text())
        return locations

class YellowWidget(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(YellowWidget, self).__init__(parent)
        self.setWindowTitle('Yellow Pages Scrapper')
        self.scrapy_worker = ScrapyWorker(self)
        self.search_item_le = QtWidgets.QLineEdit()
        self.location_widget = LocationWidget()
        self.start_stop_button = QtWidgets.QPushButton("Start", checkable=True)
        self.text_edit = QtWidgets.QTextBrowser()

        central_widget = QtWidgets.QWidget()
        self.setCentralWidget(central_widget)
        lay = QtWidgets.QGridLayout(central_widget)
        lay.addWidget(QtWidgets.QLabel("Search:"), 0, 0)
        lay.addWidget(self.search_item_le, 0, 1)
        lay.addWidget(QtWidgets.QLabel("Locations:"), 1, 0, alignment=QtCore.Qt.AlignTop|QtCore.Qt.AlignLeft)
        lay.addWidget(self.location_widget, 1, 1, alignment=QtCore.Qt.AlignTop)
        lay.addWidget(self.start_stop_button, 2, 0, 1, 2)
        lay.addWidget(self.text_edit, 3, 0, 1, 2)

        self.start_stop_button.toggled.connect(self.on_checked)
        self.scrapy_worker.logChanged.connect(self.insert_log)
        self.scrapy_worker.started.connect(self.text_edit.clear)
        self.scrapy_worker.finished.connect(partial(self.start_stop_button.setChecked, False))

    @QtCore.pyqtSlot(bool)
    def on_checked(self, state):
        if state:
            # crapy crawl yellow -a parameters='{"search_item": "house", "locations": ["usa", "germany"]}'
            search_item = self.search_item_le.text()
            locations = self.location_widget.get_locations()
            directory, program, args = utils.create_arguments(search_item, locations)
            self.scrapy_worker.run(directory, program, args)
            self.start_stop_button.setText('Stop')
        else:
            self.start_stop_button.setText('Start')
            self.scrapy_worker.stop()

    @QtCore.pyqtSlot(str)
    def insert_log(self, text):
        prev_cursor = self.text_edit.textCursor()
        self.text_edit.moveCursor(QtGui.QTextCursor.End)
        self.text_edit.insertPlainText(text)
        self.text_edit.setTextCursor(prev_cursor)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    app.setStyle('fusion')
    w = YellowWidget()
    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

I used a function that is in the utils.py file:
import os
import json

def create_arguments(search_item, locations):
    program = 'scrapy'
    dir_path = os.path.dirname(os.path.abspath(__file__))
    directory = os.path.join(dir_path, 'scrape')
    d = {"search_item": search_item, "locations": locations}
    argument = 'parameters={}'.format(json.dumps(d))
    return directory, program, ['crawl', 'yellow', "-a", argument]

Obtaining the following:

The complete project is here.


text:
Q: Django filtering models in Foreign Key Models.py
class AdmissionStudent(models.Model):
   studentlabel = models.CharField(max_length = 100, null = False, blank = False)

   def __str__(self):
       return self.studentlabel

class AdmissionRequirement(models.Model):
   requirementstudent = models.ForeignKey(AdmissionStudent, on_delete = models.CASCADE, null =
     False, blank = False)
   requirementparagraph = models.TextField(null = False, blank = False)

   def __str__(self):
       return '{} - {}'.format(self.requirementstudent, self.requirementparagraph)

Views.py
def admission(request):
   header = AdmissionHeader.objects.first()
   student = AdmissionStudent.objects.all()
   requirement = AdmissionRequirement.objects.all()

   context = {
       'header': header,
       'student': student,
       'requirement': requirement,
       'title':'Admissions'
       }

   return render(request, 'pages/admission.html', context)

Admission.html (template)
{% for student in student %}
   {{ student.studentlabel }}

   {% if {{ student.studentlabel}} == {{requirement.requirementstudent }} %}
       {% for requirement in requirement %}
           {{ requirement.requirementparagraph }}

       {% endfor %}
{% endfor %}

I know what I did in my template is stupid, but i really don't know how to filter Admission Requirements for enrollment.
Below is an example of how I want it to appear:
Transferee
-1st requirement
-2nd requirement
-3rd requirement
Foreign Student
-1st requirement
-2nd requirement
-etc

A: You can just get the all the AdmissionStudents, and prefetch all of the related AdmissionRequirement per student.
With that, you don't need requirement = AdmissionRequirement.objects.all(). You just need to pass your student list in the template like this:
student = AdmissionStudent.objects.all().prefetch_related('admissionrequirement_set')
context = {
    ...
    'student': student,
    ...
}

And then in your template, use the related data for requirements from student to display:
{% for student in student %}
   {{ student.studentlabel }}

   {% for requirement in student.admissionrequirement_set.all %}
       {{ requirement.requirementparagraph }}

   {% endfor %}
{% endfor %}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get timing information from MFCC generated with librosa.feature.mfcc I am extracting MFCCs from an audio file using Librosa's function (librosa.feature.mfcc) and I correctly get back a numpy array with the shape I was expecting: 13 MFCCs values for the entire length of the audio file which is 1292 windows (in 30 seconds).
What is missing is timing information for each window: for example I want to know what the MFCC looks like at time 5000ms, then at 5200ms etc.
Do I have to manually calculate the time? Is there a way to automatically get the exact time for each window?

A: The "timing information" is not directly available, as it depends on sampling rate. In order to provide such information, librosa would have create its own classes. This would rather pollute the interface and make it much less interoperable. In the current implementation, feature.mfcc returns you numpy.ndarray, meaning you can easily integrate this code anywhere in Python.
To relate MFCC to timing:
import librosa
import numpy as np

filename = librosa.util.example_audio_file()
y, sr = librosa.load(filename)

hop_length = 512 # number of samples between successive frames
mfcc = librosa.feature.mfcc(y=y, n_mfcc=13, sr=sr, hop_length=hop_length)

audio_length = len(y) / sr # in seconds
step = hop_length / sr # in seconds
intervals_s = np.arange(start=0, stop=audio_length, step=step)

print(f'MFCC shape: {mfcc.shape}')
print(f'intervals_s shape: {intervals_s.shape}')
print(f'First 5 intervals: {intervals_s[:5]} second')

Note that array length of mfcc and intervals_s is the same - a sanity check that we did not make a mistake in our calculation.
MFCC shape: (13, 2647)
intervals_s shape: (2647,)
First 5 intervals: [0.         0.02321995 0.04643991 0.06965986 0.09287982] second


text:
Q: Run ClojureScript using nodejs while using another lein project I am writing a clojurescript program called "gpqgame" that evolves pieces of code; it evaluates the "accuracy" of a piece of code by running it on a simulator, called "qgame", which is a leiningen project in another directory.
So far, I have been manually loading all qgame code into a repl, and then testing my evolution code using that. However, I want to be able to run the code from the terminal, so I set up my gpqgame as a lein project, and have been trying to use nodejs. I promptly started running into trouble.
Gpqgame can't seem to load qgame and I don't know why, I've included the project.clj files for both. I've tried loading the full project as a lib and foreign-lib inside the cljs-build, and I've tried copying the "src" of qgame into the "src" of gpqgame while including the libraries that qgame needs inside the resources of gpqgame. My gpqame.core has the following ns declaration:
(ns gpqgame.core
 (:require [clojure.string :as st]
              [qgame.simulator.interpreter :as inter]
              [qgame.gp.evaluator :as ev]
              [qgame.simulator.qgates :as qg]
              [clojure.browser.repl :as repl]))

and it contains (enable-console-print!) and (set! *main-cli-fn* -main).
Each time, the compilation will succeed but will give warnings about:
  1) use of undeclared vars in the qgame code
  2) keywords and reserved words are not allowed as unquoted property names        in older javascript
When I run node out/gpqgame.js, I get a reference error saying "mathjs is not defined". One thing I noticed is that qgame uses 0.0-2156, while my gpqgame uses 0.0-2913. If I change the version of one of them to be the same as the other, they don't work anymore.
Is there an easy way to have gpqgame load the whole qgame project without me having to include it inside the gpqgame project?
Is this the best way to do it, or should I include it in the src of qgame? Why didn't it work when I did this, even though I included the libraries it needed? I'm not sure how much of this has to do with nodejs, and how much is due to bad setup by myself. Any help would be greatly appreciated.
(defproject gpqgame "0.1.0-SNAPSHOT"
  :description "FIXME: write this!"
  :url "http://example.com/FIXME"

  :dependencies [[org.clojure/clojure "1.6.0"]
                 [org.clojure/clojurescript "0.0-2913"]]

  :node-dependencies [[source-map-support "0.2.8"]]

  :plugins [[lein-cljsbuild "1.0.4"]
            [lein-npm "0.4.0"]]

  :hooks [leiningen.cljsbuild]

  :source-paths ["src" "target/classes"]

  :clean-targets ["out" "out-adv"]

  :cljsbuild {
    :builds [{:id "dev"
              :source-paths ["src"]
              :compiler {
                :main gpqgame.core
                :target :nodejs
                :output-to "out/gpqgame.js"
                :output-dir "out"
                :optimizations :simple
                :foreign-libs [{:file "http://cdnjs.cloudflare.com/ajax/libs/mathjs/0.18.1/math.min.js"
                                  :provides ["math.js"]}
                               {:file "./resources/arndt.js"
                                  :provides ["arndt.js"]}]
                :pretty-print true
                :cache-analysis true
                :source-map "out/gpqgame.js.map"}}]})

And the qgame project.clj looks like:
(defproject org.clojars.hippiccolo/qgame "0.4.4"
  :description "Quantum Gate And Measurement Emulator, or qgame. A machine-instruction-level quantum computing simulator. Ported from Lee Spector's QGAME (written in Common Lisp)."
  :license {:name "MIT License"
            :url "http://http://en.wikipedia.org/wiki/MIT_License"}
  :url "https://github.com/omriBernstein/qgame"
  :dependencies [[org.clojure/clojure "1.5.1"]
                 [org.clojure/clojurescript "0.0-2156"]] ;2156
  :plugins [[lein-cljsbuild "1.0.2"]]
  :cljsbuild {:builds
              {:dev {:source-paths ["src"]
                     :compiler {:output-to "static/qgame.js"
                                :optimizations :whitespace
                                :pretty-print true
                                :libs ["~/computer/javascript/prototype.js"]
                                :foreign-libs [{:file "http://cdnjs.cloudflare.com/ajax/libs/mathjs/0.18.1/math.min.js"
                                                :provides ["math.js"]}
                                               {:file "./resources/arndt.js"
                                                :provides ["arndt.js"]}
                                               {:file "./resources/prototype.js"
                                                :provides ["prototype.js"]}]}}
               :prod {:source-paths ["src/qgame"]
                      :compiler {:output-to "static/qgame.min.js"
                                 :optimizations :whitespace ;Eventually do :advanced here
                                 :pretty-print false
                                 :libs ["~/computer/javascript/prototype.js"]
                                 :foreign-libs [{:file "http://cdnjs.cloudflare.com/ajax/libs/mathjs/0.18.1/math.min.js"
                                                 :provides ["math.js"]}
                                                {:file "./resources/arndt.js"
                                                 :provides ["arndt.js"]}
                                                {:file "./resources/prototype.js"
                                                 :provides ["prototype.js"]}]}}}
              :repl-listen-port 9000}
  :min-lein-version "2.0.0")


text:
Q: How to avoid browser caching of CSS, JS and image files using .htaccess? RewriteCond %{REQUEST_URI} ^/[images|css|js]/
RewriteRule ^/(.*)$ /$1?ver=2 [L]

Now am using this code. But its not working.

A: Htaccess solution :
You might want to use mod_headers functions Cache-Control and Expires, for the file types you want the browser to not cache :
<filesMatch "\.(js|css|jpg|jpeg|png|gif)$">
FileETag None
<ifModule mod_headers.c>
Header unset ETag
Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
Header set Pragma "no-cache"
Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
</ifModule>
</filesMatch>

Source
PHP solution :
You could also load each resource with a different timestamp each time your page is shown :
 <script type="text/javascript" src="myfile.js?time=<?php echo mktime(); ?>" />
 <link rel="stylesheet" media="screen" href="/myfile.css?time=<?php echo mktime(); ?>">

A: A few other options too:
Browser hard refresh (Chrome)

Ctrl + F5 (or Ctrl + refresh button)

Time stamp after the CSS files (instead of time, use some sort of version control)
<script src="myjsfile.js?t=<?php echo time(); ?>"></script>

HTML meta no cache
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">

.Htaccess (thanks to top answer here: How to prevent http file caching in Apache httpd (MAMP))
<filesMatch "\.(html|htm|js|css)$">
  FileETag None
  <ifModule mod_headers.c>
     Header unset ETag
     Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
     Header set Pragma "no-cache"
     Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"
  </ifModule>
</filesMatch>


text:
Q: Error 1054 - Variable used as field in WHERE is taken as column i'm trying to update a mysql db but when i execute the query i get an error where var id (used as filed in WHERE) is used as column name.
Am i reading it wrong? what i have to fix to let this work?
Console Log

var message = '';
var id = req.session.user.id;
console.log(req.session.user.id);
var post  = req.body;
var worker= post.worker;
var farmer= post.farmer;
var soldier= post.soldier;
var defender= post.defender;

var sql= "UPDATE stats SET worker = `"+worker+"`, farmer = `"+farmer+"`, soldier = `"+soldier+"`, defender = `"+defender+"` WHERE `stats`.`id` = `"+id+"` ";

db.query(sql, function(err, results){
  if(results){
    res.send('/home/dashboard.ejs')
  };

  if(err){console.log(err)};
 });
}

A: The immediate cause of your error is that you are trying to escape literal values using backticks instead of single quotes.  The error message you see is hinting at this.  But, rather than just replacing those backticks with single quotes, you should instead use a prepared statement:
var sql = "UPDATE stats SET worker = ?, farmer = ?, soldier = ?, defender = ? WHERE id = ?";
db.query(sql, [worker, farmer, soldier, defender, id], function(err, results) {
    if (results) {
        res.send('/home/dashboard.ejs')
    }

    if (err) {
        console.log(err)
    }
});

A: Try this:
var sql= "UPDATE stats SET worker = '"+worker+"', farmer = '"+farmer+"', soldier = '"+soldier+"', defender = '"+defender+"' WHERE id = "+id+" ";

I removed the back ticks from the id column name at the end (unnecessary) and properly surrounded the strings with single quote instead of back ticks. Also no need for the table name.


text:
Q: Running sums for every row of the previous 25 rows I've been trying for a while now to produce a code that brings me a new vector of the sum of the 25 previous rows for an original vector.
So if we say I have a variable Y with 500 rows and I would like a running sum, in a new vector, which contains the sum of rows [1:25] then [2:26] for the length of Y,  such as this:
y<-1:500
runsum<-function(x){
   cumsum(x)-cumsum(x[26:length(x)])
}

new<-runsum(y)

I've tried using some different functions here and then even using the apply functions on top but none seem to produce the right answers....
Would anyone be able to help? I realise it's probably very easy for many of the community here but any help would be appreciated
Thanks

A: This function calculates the sum of the 24 preceding values and the actual value:
 movsum <- function(x,n=25){filter(x,rep(1,n), sides=1)}

It is easy to adapt to sum only preceding values, if this is what you really want.

A: In addition to Roland's answer you could use the zoo library
library ( zoo )
y <- 1:500
rollapply ( zoo ( y ), 25, sum )

HTH

A: I like Roland's answer better as it relies on a time series function and will probably be pretty quick. Since you mentioned you started going down the path of using apply() and friends, here's one approach to do that:
y<-1:500
#How many to sum at a time?
n <- 25
#Create a matrix of the appropriate start and end points
mat <- cbind(start = head(y, -(n-1)), end = tail(y, -(n-1)))
#Check output
rbind(head(mat,3), tail(mat,3))
#-----
       start end
           1  25
           2  26
           3  27
[474,]   474 498
[475,]   475 499
[476,]   476 500

#add together
apply(mat, 1, function(x) sum(y[x[1]]:y[x[2]]))

#Is it the same as Roland's answer after removing the NA values it returns?
all.equal(apply(mat, 1, function(x) sum(y[x[1]]:y[x[2]])),
          movsum(y)[-c(1:n-1)])
#-----
[1] TRUE


text:
Q: Can't change font-color on hover li by using a href I want change the font-color on hover the whole li tags, not only on hover the a tag. The background-color should be the same as before (no hover) Can't find where the mistake is. Please help me out! Thank's!

nav {
  background: #000;
  min-height: 85px;
  position: fixed;
  z-index: 20;
  width: 100%;
  margin-top: 35px;
  transition: 0.35s all ease;
  max-width: 1800px;
}

nav ul {
  float: right;
  text-align: left;
  display: inline;
  margin: 0;
  list-style: none;
  padding: 1rem;
  transition: 0.35s all ease;
}

nav ul li {
  font: 700 18px sans-serif;
  margin-right: -4px;
  position: relative;
  cursor: pointer;
  -webkit-transition: all 0.2s;
  -moz-transition: all 0.2s;
  -ms-transition: all 0.2s;
  -o-transition: all 0.2s;
  transition: all 0.2s;
  letter-spacing: 0.1rem;
  display: inline-block;
  color: white;
  padding: 1rem 2rem;
  text-transform: uppercase;
  /*font-family: sans-serif;*/
}

nav ul li a:hover {
  color: #BD1521;
  transition: 0.35s all ease;
}

nav ul li:hover {
  color: #BD1521;
  transition: 0.35s all ease;
}

nav ul li a {
  text-decoration: none;
  font-weight: 700;
  text-transform: uppercase;
  letter-spacing: 0.1rem;
  color: #fff;
}

Leistungen

Reparatur & Instandsetzung

Lackierung & Folierung

Restauration & Sonderumbau

Autoglas & Folie

Fahrzeugaufbereitung

Service Plus

Über Uns

Unternehmen

Unser Team

Karierre

Impressum

AGB's

Datenschutz

Kontakt

<button class="nav_button">Angebote</button>

Öffnungszeiten: 9:00-18:00 Uhr

176 311 81 41 8

example@example.de

A: You need to specifically change the anchor color on li:hover.
nav ul li:hover a {
color: #BD1521;
transition: 0.35s all ease;
}


text:
Q: Angular: uncaught in promise error when using pipe and mergemap I am working with Angular 6, and I just found out about pipe and mergemap.
Basically, I am calling one service to read one of two different csv's (user chooses which one to read) from assets folder, get the date from each csv and use that date to select data from database, which will be used to create graphs.
So, what I did was
this.service.getCsv().pipe(
    mergeMap((data) => {
        let dtLst = getDate(data);
        return this.service.getDB(dtLst);
    })
).subscribe((result) => {
    switch(csvType) {
        // create first line graph
        // create another line graph
    }
})

Both csv's are turned into line graphs, and the first one works fine, but the second one throws Uncaught (in promise) error.
The error is:
ERROR Error: Uncaught (in promise):
TypeError: Cannot read properties of undefined (reading 'type')
TypeError: Cannot read properties of undefined (reading 'type')
    at Function.value (apexcharts.common.js:6)
    at t.value (apexcharts.common.js:14)
    at t.create (apexcharts.common.js:6)
    at apexcharts.common.js:14
    at new ZoneAwarePromise (zone.js:910)
    ...

I am using apexchart and the same template for both line graphs.
The thing is even though it throws that Uncaught (in promise) error, both graphs show up (in dev). It's not like a part is missing or not showing. It works as it's supposed to.
But, what I am worried about is if I publish, and it runs in prod, then it might crash or something else happens. So, before I publish, I want to fix this error, but I have no idea how to go about it.
I tried to catch error, but since the graphs show up, I don't think I can catch useful error logs.

A: For future references,
I defined chartDataArray as undefined:
public chartDataArray;

and that threw Uncaught (in promise) error.
I just defined that variable as empty (empty array and empty strings), and the error disappeared.
public chartDataArray = {data: [], name: '', type: 'line'};


text:
Q: Linux send with MSG_DONTWAIT blocks? in my multithreaded linux server application, a thread gets stuck forever in send function, which I believe should be nonblocking. The code looks like this:
while(size) {
    const ssize_t sent = send(unixSocketFD, data, size, MSG_NOSIGNAL | MSG_DONTWAIT);
    if(sent > 0) {
        size -= sent;
        data += sent;
    } else {
        if(-1 == sent) {
            if(EINTR == errno) {
                continue;
            }
            if(EWOULDBLOCK == errno || EAGAIN == errno) {
                return 0; // need to be called again later
            }
        }
        return -1; // indicate error ...
    }
}

... and the stacktrace:
(gdb) bt
#0  0x00007ffff7bca9ff in __libc_send (fd=5, buf=0x7fffedd25880, n=87643, flags=16448) at ../sysdeps/unix/sysv/linux/x86_64/send.c:26
#1  0x00000000004076cf in Output::sendBlock (this=0x7fffdc0a3190, unixSocketFD=5) at OutputBlock.cpp:24
...

I believe that the send should return immediately when flags contain MSG_DONTWAIT. What's wrong with my code/assumptions? Thanks you for any suggestions.

A: I'm sorry, this was my mistake: the send was not blocking, instead it was enterered again and again even if it indicated that the socket is not ready to accept more data.


text:
Q: How to arrive at one unified test framework which will run tests on all presentation layers - Web,Mobile App & desktop App Problem Statement: Being in Test Automation arena for quite some time, I always ran into this puzzle of how to design one integrated Test Strategy to run automated scripts across all the 3 UI layers which most latest apps support

*

*Mobile App - Hybrid

*Wed App - accessed through browsers

*Desktop Apps

More Details
Any modern application supports all the above listed platforms and their are diverse tools to test each platform

*

*Desktop - QTP, AutoIt libraries ....

*Web - Selenium and selenium extensions like Protractor so on, QTP ...

*Mobile App - Appium so on ..

But how do we design an effective Test Automation Framework which will involve writing the functional test case flow at one place - language agnostic and make it work across any platform that we want to execute on?
I have summarized my work so far as an answer below. Please feel free to throw around any ideas !!

A: The best way to achieve this as per my analysis is to write language agnostic cases in BDD Style using Cucumber and have separate implementations based on the platform the tests need to run
I have summarized the complete architecture below.I have named it Panacea Framework :) I have blogged low level details here

A: As noted above, you can use Cucumber for writing your tests - it has versions for Ruby, Java, JavaScript, and many other language flavors. The Cucumber/BDD approach does give you high-level language independence for the Cucumber Scenarios, but you still have to write your step definitions in your language of choice.
The Cucumber framework can run tests against any application: mobile app, mobile web, or desktop applications, regardless of the language those applications are written in (we use ruby/cucumber with various plugins to test across all three).
The support elements of Cucumber will need some customization for any broad-reaching framework (env, hooks, etc.) so that you can get good reports and make things as easy as possible for testing, but the basics are already there.
You'll need support for actually driving the tests at the low level (i.e., making clicks, swipes, etc. work): that would be selenium-webdriver, or Watir if you prefer. There may well be other approaches. There are language-specific plugins for Selenium, so for ruby, you just add the selenium-webdriver gem.
All tests can be run locally (I have implemented a series of shell scripts/functions to make this easy). Then you can use Jenkins to run Basic Acceptance Tests on a regular basis, and also for automating the CI Pipeline.
In addition, you can use Appium and friends to automate your tests across Apple and Android with simulators or using real devices.
It's all open-source which is nice (if you like that sort of thing) and it meets your criteria. Most importantly its available now (and it works for us).

A:
design one integrated Test Strategy to run automated scripts across all the 3 UI

BDD is not intended to be 1 to 1 with your test code implementation, otherwise, the business team won't take ownership.  Instead, link an identifier using spec/test properties to match up tests to the BDD definition.
You need page objects to be as compositional as they exist in the real application. This allows developers to create derivative tests (positive/negative) testing than just having a bag of helpers.  Example: a view contains 1 or more components, so, a feature spec could look like:
web desktop:
it('', () => {
  // protractor sample:
  const view = new View();
  const sidebar = await view.newRecord();
  const apiresult = sidebar.save({neverset: true});

  apiresult.then((data) => fail('expected bad request not a 200 from api.'), () => {});
}

hybrid (media queries):
If you are building a hybrid app define multiple configs for chromeOptions { args: ['--window-size=1920x1080'] } so you can test your various media query stock sizes.
native + desktop:
I would put my bet on the webdriver protocol,  https://www.w3.org/TR/webdriver/#privacy , to be the magic sauce you are looking for.  Chrome browser or some mobile simulator will interpret the protocol to actions inside the mobile simulator.  Checkout how electron uses the webdriver protocol to test a desktop app: http://electron.atom.io/docs/tutorial/using-selenium-and-webdriver/#setting-up-with-webdriverjs

A: In either of the interface viz., Web App or Mobile App or Desktop(Standalone App), the main bottleneck is the maintenance effort if not designed properly.
I would use Page Object Pattern and maintain page classes and abstract the behaviour of the app from Tests.This way it makes my work easy.
Separation Of Concerns. Single Responsibility Principle.


text:
Q: Angular 2: How to make
* tag to work with key events without Jquery I have a dropdown like this

How to make this to work with key events(top arrow and down arrow) without Jquery?
I need li to work like select. How do I do this?


text:
Q: How Datastax implements its async API driver for Cassandra? I'm trying to convince a coworker of the benefits of using the Session#executeAsync.
However, since we are using the driver from Scala, it would be rather easy to wrap the sync call Session#execute in a Future and that would be all to transform it in an async call. This will be already an improvement because it will give us the opportunity of avoid blocking the current thread (in our case that would represent blocking the threads that handles http requests in play with a huge impact on the number of requests that can be handled concurrently)
I argue that if the work needed to implement an async driver will be wrap it in a Future it won't exist implementations like ReactiveMongo an the Async Api for Cassandra from Datastax.
So,

*

*What are the benefits of using the async api?

*How is the async api implemented in Datastax driver and it what libraries and OS features relies on?

*What kind of problems were to be solved beyond the asynchronous networks calls? (I mean, implement the async driver must be more than just using java nio)

A:
How is the async api implemented in Datastax driver and it what libraries and OS features relies on?

Datastax java driver based on Netty networking framework. Netty itself based on Event Driven model. Also for some operating systems  Netty provides native transports to improve performance e.g. epoll for Linux.

What are the benefits of using the async api?

I'm not a Scala expert but as I know Scala Future based on Threads model (Execution contexts). It means you need to submit a request to another thread to execute  the request asynchronously. For IO tasks you just need request another system and wait response from this system. If you have a big number of requests, all threads in your pool will be busy but will not do anything useful. Thread is a fairly expensive resource and it can be a problem to have thousands threads in the same physical resource. Threads are good for parallel calculation tasks but not for IO tasks.
From other hand Datastax java driver based on Event Driven model (Netty). It means the each request will be submitted in event loop queue. For each iteration of event loop, Netty will define the state of request and will execute handlers associated with this request.
This approach avoids of memory usage overhead for threads and allows you to perform thousands of IO requests in the same time. But in this case you should define slow or blocking request callbacks in another thread to avoid blocking of event-loop.


text:
Q: problema al enviar una petición post usando la opcion RAW en POSTMAN hace días estaba probando y todo funcionaba bien, estoy utilizando la opción RAW porque estoy enviando un objeto que esta embebido dentro de otra, a continuación dejo la imagen d como lo estoy haciendo:

El problema es que cuándo imprimo el body en node.js me la estó mostrando vacío, en cambio si envío los datos usando la opción x-www-form-urlencodedsi los recibo en el BACK, pero como mencioné anteriormente, hace unas horas me funcionaba con la opción RAW y ahora no, lo que si noto es que el objeto en la imágen me lo muestro de color gris, y cuándo me funcionaba hace unas horas marcaba las claves y los valores con un color rojo. No se si es que toqué algo que no debía y por eso ahora no funciona. En el back estoy trabajando con express.js por si sirve de algo.
Gracias de antemano al que me pueda ayudar.


text:
Q: Ajax to PHP, not updating? Here is my index.php file:

update ID 928 with 1 click

Here is my addclick.php
$id = $_POST['id'];
mysql_query("UPDATE `table` SET `x` = `x` + '1' WHERE `id` = '" . $id . "'");

If I have WHERE id = '1' it updates row 928 perfectly, but when it is set as the post variable, it doesn't. The only thing I can think of is that the ajax call is not parsing the ID properly.
What is wrong with this?

A: Not a 100% sure, but it could be because in jquery you didn't put the the id in quotes like this:
$.post("http://www.site.com/addclick.php", { 'id': str })

It's considering that you id is a var and not the name of the variable...
Hope it helps.

A: WHy not check what $_POST is before blindly inserting it into your database? I could hack up a script that sets id = 'Robert\'; drop table students -- and kill your database.
$id = intval($_POST['id']);
$sql = "UPDATE `table` SET x=x+1 WHERE id=$id";
$result = mysql_query($sql);
if ($result === FALSE) {
    die("query failed: " . mysql_error());
}


text:
Q: Block matrix determinant formula I have encountered an statement several times while proving determinant of a block matrix.

$$\det\pmatrix{A&0\\0&D}\; = \det(A)\det(D)$$

where $A$ is $k\times k$ and $D$ is $n\times n$ matrix. How to prove this?
Thanks in advance.

A: If your matrices have coefficients in an integral domain, you can pass to the field of fractions and take an algebraic closure to use the Jordan canonical form, in which case this equation becomes trivial since both sides of the equation are the product of the products of the eigenvalues of $A$ and $D$.
Otherwise you can use Laplace expansion and notice that the sum goes over all the permutations of $S_{k+n}$, in which case the only terms which "survive" are the permutations which map $\{ 1,\cdots, k\}$ to itself and $\{k+1,\cdots,k+n\}$ to itself. Then you can split the sum in two parts and obtain $\det(A) \det(D)$. This proof works over any (commutative) ring.
Hope that helps,

A: This is more general result
$$\det\pmatrix{A&B\\0&D} = \det A\det D$$
and to prove it notice that
$$\pmatrix{A&B\\0&D}=\pmatrix{I_k&0\\0&D}\pmatrix{A&B\\0&I_n}$$
and we develop along the $k$ first rows we find
$$\det\pmatrix{I_k&0\\0&D}=\det D$$
and along the last $n$ rows we find
$$\det\pmatrix{A&B\\0&I_n}=\det A$$
and the result follows.


text:
Q: kubernetes jenkins plugin does not create 2 containers I have 2 Jenkins instances, one use version 1.8 and second version 1.18.
Oldest version is able to create both containers.
Agent specification [Kubernetes Pod Template] (mo-aio-build-supplier):
* [jnlp] mynexus.services.com/mo-base/jenkins-slave-mo-aio:1.8.2-ca(resourceRequestCpu: 0.25, resourceRequestMemory: 256Mi, resourceLimitCpu: 1, resourceLimitMemory: 1.5Gi)
* [postgres] mynexus.services.com:443/mo-base/mo-base-postgresql-95-openshift

Newest version are not able to create postgres container
Container postgres exited with error 1. Logs: mkdir: cannot create directory '/home/jenkins': Permission denied
Both use same podTemplate
 podTemplate(
            name: label,
            label: label,
            cloud: 'openshift',
            serviceAccount: 'jenkins',
            containers: [
                    containerTemplate(
                            name: 'jnlp',
                            image: 'mynexus.services.theosmo.com/jenkins-slave-mo-aio:v3.11.104-14_jdk8',
                            resourceRequestCpu: env.CPU_REQUEST,
                            resourceLimitCpu: env.CPU_LIMIT,
                            resourceRequestMemory: env.RAM_REQUEST,
                            resourceLimitMemory: env.RAM_LIMIT,
                            workingDir: '/tmp',
                            args: '${computer.jnlpmac} ${computer.name}',
                            command: ''
                    ),
                    containerTemplate(
                            name: 'postgres',
                            image: 'mynexus.services.theosmo.com:443/mo-base/mo-base-postgresql-95-openshift',
                            envVars: [
                                envVar(key: "POSTGRESQL_USER", value: "admin"),
                                envVar(key: "POSTGRESQL_PASSWORD", value: "admin"),
                                envVar(key: "POSTGRESQL_DATABASE", value: "supplier_data"),
                            ]
                    )
            ],
            volumes: [emptyDirVolume(mountPath: '/dev/shm', memory: true)]
    )

Also, I've noticed YAML created by newest version is a bit weird
apiVersion: "v1"
kind: "Pod"
metadata:
  annotations:
    buildUrl: "http://jenkins.svc:80/job/build-supplier/473/"
  labels:
    jenkins: "slave"
    jenkins/mo-aio-build-supplier: "true"
  name: "mo-aio-build-supplier-xfgmn-qmrdl"
spec:
  containers:
  - args:
    - "********"
    - "mo-aio-build-supplier-xfgmn-qmrdl"
    env:
    - name: "JENKINS_SECRET"
      value: "********"
    - name: "JENKINS_TUNNEL"
      value: "jenkins-jnlp.svc:50000"
    - name: "JENKINS_AGENT_NAME"
      value: "mo-aio-build-supplier-xfgmn-qmrdl"
    - name: "JENKINS_NAME"
      value: "mo-aio-build-supplier-xfgmn-qmrdl"
    - name: "JENKINS_AGENT_WORKDIR"
      value: "/tmp"
    - name: "JENKINS_URL"
      value: "http://jenkins.svc:80/"
    - name: "HOME"
      value: "/home/jenkins"
    image: "mynexus.services.com/mo-base/jenkins-slave-mo-aio:1.8.2-ca"
    imagePullPolicy: "IfNotPresent"
    name: "jnlp"
    resources:
      limits:
        memory: "1.5Gi"
        cpu: "1"
      requests:
        memory: "256Mi"
        cpu: "0.25"
    securityContext:
      privileged: false
    tty: false
    volumeMounts:
    - mountPath: "/dev/shm"
      name: "volume-0"
      readOnly: false
    - mountPath: "/tmp"
      name: "workspace-volume"
      readOnly: false
    workingDir: "/tmp"
  - env:
    - name: "POSTGRESQL_DATABASE"
      value: "supplier_data"
    - name: "POSTGRESQL_USER"
      value: "admin"
    - name: "HOME"
      value: "/home/jenkins"
    - name: "POSTGRESQL_PASSWORD"
      value: "admin"
    image: "mynexus.services.com:443/mo-base/mo-base-postgresql-95-openshift"
    imagePullPolicy: "IfNotPresent"
    name: "postgres"
    resources:
      limits: {}
      requests: {}
    securityContext:
      privileged: false
    tty: false
    volumeMounts:
    - mountPath: "/dev/shm"
      name: "volume-0"
      readOnly: false
    - mountPath: "/home/jenkins/agent"
      name: "workspace-volume"
      readOnly: false
    workingDir: "/home/jenkins/agent"
  nodeSelector: {}
  restartPolicy: "Never"
  serviceAccount: "jenkins"
  volumes:
  - emptyDir:
      medium: "Memory"
    name: "volume-0"
  - emptyDir: {}
    name: "workspace-volume"

As you are able to see above:

*

*postgres container is under an env tree

Any suggestion? Thanks in advance

A: As far as I checked there
The problem

Since Kubernetes Plugin version 1.18.0, the default working directory of the pod containers was changed from /home/jenkins to /home/jenkins/agent. But the default HOME environment variable enforcement is still pointing to /home/jenkins. The impact of this change is that if pod container images do not have a /home/jenkins directory with sufficient permissions for the running user, builds will fail to do anything directly under their HOME directory, /home/jenkins.

Resolution
There are different workaround to that problem:
Change the default HOME variable
The simplest and preferred workaround is to add the system property -Dorg.csanchez.jenkins.plugins.kubernetes.PodTemplateBuilder.defaultHome=/home/jenkins/agent on Jenkins startup. This requires a restart.
This workaround will reflect the behavior of kubernetes plugin pre-1.18.0 but on the new working directory /home/jenkins/agent
Use /home/jenkins as the working directory
A workaround is to change the working directory of pod containers back to /home/jenkins. This workaround is only possible when using YAML to define agent pod templates (see JENKINS-60977).
Prepare images for Jenkins
A workaround could be to ensure that the images used in agent pods have a /home/jenkins directory that is owned by the root group and writable by the root group as mentioned in OpenShift Container Platform-specific guidelines.

Additionaly there is the issue on jenkins.

Hope this helps.


text:
Q: Calculating time difference using a colon Im trying to calculate the time difference between 18:00 & 06:00 and display the result in the same format. Both times are entered manually.

A: First create two NSDates from the string inputs and get the interval between the two then pass the interval through a formatting function we will create:
let date1:String = "12:00"
let date2:String = "13:00"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "HH:mm"
let date3 = dateFormatter.dateFromString(date1)
let date4 = dateFormatter.dateFromString(date2)

let interval = date4!.timeIntervalSinceDate(date3!)
print("\(stringFromTimeInterval(interval))")

now we need to format the interval which is the number of seconds between the two so create a function which returns a string:
func stringFromTimeInterval(interval: NSTimeInterval) -> String {
  let interval = Int(interval)
  let minutes = (interval / 60) % 60
  let hours = (interval / 3600)
  return String(format: "%02d:%02d", hours, minutes)
}

in your case you will set the date1 and date2 from I'm guessing the text fields in your program.


text:
Q: Row in listview not preserve the makeover and appears repeated I have a list that when you click on the row on the right side the layout with the icon is changed by other. This makes it well but when I scrolling in the list, I notice there are rows with the same icon without do click. Also, if I scroll quickly these same icons are lost and are built differently. I think it's on the reuse of cells but I can not find the solution. What I want is that the image stays active only in the row where clicka.
Thanks!!
Adapter class:
public class ListadoVotantesArrayAdapter extends ArrayAdapter<Votante> {

    private Context context;
    private LayoutInflater inflater;
    private ArrayList<Votante> listaVotantes;
    private int rowLayout;
    private View mConverView;

    public ListadoVotantesArrayAdapter(Context context, int resource, ArrayList<Votante> objects) {
        super(context, resource,objects);
        this.context = context;
        this.inflater = LayoutInflater.from(context);
        this.listaVotantes = objects;
        this.rowLayout = resource;
    }

    public int getCount(){
        return this.listaVotantes.size();
    }

    public Votante getVotante(int position){
        return this.listaVotantes.get(position);
    }

    private static class ViewHolder {
        public TextView lblName;
        public TextView lblLastName;
        public TextView lblDni;
        public TextView lblVoterNumber;
        public RelativeLayout lytVoted;
        public RelativeLayout lytCanVote;
        public RelativeLayout lytUndo;
    }

    public View getView(int position, View converView, ViewGroup parent) {

        final ViewHolder viewHolder;
        mConverView = converView;
        if (mConverView == null){
            viewHolder = new ViewHolder();

            this.mConverView = inflater.inflate(this.rowLayout, parent, false);

            if (mConverView != null){
                viewHolder.lblName = (TextView) mConverView.findViewById(R.id.lblVoterName);
                viewHolder.lblLastName = (TextView) mConverView.findViewById(R.id.lblVoterLastName);
                viewHolder.lblDni = (TextView) mConverView.findViewById(R.id.lblDni);
                viewHolder.lblVoterNumber = (TextView) mConverView.findViewById(R.id.lblNumber);
                viewHolder.lytVoted = (RelativeLayout) mConverView.findViewById(R.id.lytVoted);
                viewHolder.lytCanVote = (RelativeLayout) mConverView.findViewById(R.id.lytCanVote);
                viewHolder.lytUndo = (RelativeLayout) mConverView.findViewById(R.id.lytUndo);
                mConverView.setTag(viewHolder);
            }
        }else{
            viewHolder = (ViewHolder) mConverView.getTag();
        }

        Votante votante = getVotante(position);

        viewHolder.lblName.setText(votante.getNombre());
        viewHolder.lblLastName.setText(votante.getApellidos());
        viewHolder.lblDni.setText(votante.getDni());
        viewHolder.lblVoterNumber.setText(""+votante.getNumVotante());

        if (votante.getVotado()){
            viewHolder.lytVoted.setVisibility(View.VISIBLE);
            viewHolder.lytCanVote.setVisibility(View.GONE);
        }else{
            viewHolder.lytVoted.setVisibility(View.GONE);
            viewHolder.lytCanVote.setVisibility(View.VISIBLE);
        }
        mConverView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                viewHolder.lytUndo.setVisibility(View.VISIBLE);
                notifyDataSetChanged();
            }
        });
        return mConverView;
    }
}

Layout Row:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/lyt_voter"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="1dp">

    <RelativeLayout
        android:id="@+id/lytVoterNumber"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignParentLeft="true"
        android:background="@color/lightBlueItemList">

        <TextView
            android:id="@+id/lblNumber"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:text="1999"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </RelativeLayout>

    <LinearLayout
        android:id="@+id/lytVoterData"
        android:layout_width="wrap_content"
        android:layout_height="70dp"
        android:layout_alignParentTop="true"
        android:layout_toLeftOf="@+id/lytCanVote"
        android:layout_toRightOf="@+id/lytVoterNumber"
        android:layout_toStartOf="@+id/lytCanVote"
        android:background="@color/whiteItemList"
        android:orientation="vertical"
        android:padding="5dp">

        <TextView
            android:id="@+id/lblVoterLastName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Suarez Garcia de la Serna"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/lblVoterName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="José Carlos"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <TextView
            android:id="@+id/lblDni"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="44950962S"
            android:textAppearance="?android:attr/textAppearanceMedium" />
    </LinearLayout>

    <RelativeLayout
        android:id="@+id/lytCanVote"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignParentRight="true"
        android:background="@color/yellowItemList"
        android:minHeight="30dp"
        android:minWidth="30dp">

        <ImageView
            android:id="@+id/imgVote"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:src="@drawable/flecha" />

    </RelativeLayout>

    <RelativeLayout
        android:id="@+id/lytVoted"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:layout_alignParentRight="true"
        android:background="@color/grrenAcceptList"
        android:minHeight="30dp"
        android:minWidth="30dp"
        android:visibility="gone">

        <ImageView
            android:id="@+id/imgAccept"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:src="@drawable/aceptar"
             />
    </RelativeLayout>

    <RelativeLayout
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:minHeight="30dp"
        android:minWidth="30dp"
        android:background="@color/redD3"
        android:id="@+id/lytUndo"
        android:layout_alignParentRight="true"
        android:visibility="gone">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imgUndo"
            android:layout_centerVertical="true"
            android:layout_centerHorizontal="true"
            android:src="@drawable/undo"/>
    </RelativeLayout>

</RelativeLayout>

A: You need to follow below Idea
1) this line of code mConverView = converView; doesn't makes sense. directly use converView(View from getView param). Remove mConvertView from the adapter.
2) Add some mechanism which can tell you which row is clicked and save that variable.
Example:- Have an boolean Array of size Rows.size . and set them in onClick.
Boolean[] array = new Boolean[getSize()];

in onClick that you already have in your getview set this.
public void onClick(View v) {
     array[position] = !array[position];
     viewHolder.lytUndo.setVisibility(View.VISIBLE);
     //You do not need to call notifyDatasetChange.

3) in getView(), when you are setting data in to row items/or just before onClick. have a check like below.
if(array[position])// this will tell you if you need to show or hid lytUndo thing
     viewHolder.lytUndo.setVisibility(View.VISIBLE); // Show it
else
     viewHolder.lytUndo.setVisibility(View.GONE); // hide it or do whatever you want

You might need to set some params as final
I have written this as simple as possible, comment back with your result.


text:
Q: How to calculate the maximum voltage of square signal from Erms?
How do you calculate the maximum  oltage from Erms when you have dc and ac component?

A: As you pointed out the equation for RMS is as follows:
\$V_{RMS} = \sqrt{V_{P}^2 + V_{DC}^2}\$
Where \$V_{P}\$ is voltage peak value of the AC component (half of \$V_{PP}\$), and \$V_{DC}\$ is the DC bias.
Because there are three variables there you can not simply determine the peak voltage of a DC square wave from its RMS alone. The amplitude of a wave with AC and DC components would be:
\$y = V_{P} + V_{DC}\$
So you would need to know one of these two values to determine the amplitude from the RMS. Lets assume you know the DC offset, then we can use our RMS equation and solve for \$V_P\$:
\$V_{P} = \pm \sqrt{V_{RMS}^2 - V_{DC}^2}\$
Next solve for \$V_P\$ in our displacement equation:
\$y = V_{P} + V_{DC}\$
\$V_{P} = y - V_{DC}\$
Now substitute this into the earlier equation and isolate:
\$V_{P} = \pm \sqrt{V_{RMS}^2 - V_{DC}^2}\$
\$y - V_{DC} = \pm \sqrt{V_{RMS}^2 - V_{DC}^2}\$
\$y = V_{DC} \pm \sqrt{V_{RMS}^2 - V_{DC}^2}\$
Thats as good as you get, that is the equation that will let you know the amplitude of the square wave from its RMS value and DC offset.


text:
Q: How to define a \newparencite producing year before author in the authoryear-comp style? First an MWE and its output are as follows.
\documentclass{article}
\usepackage[style = authoryear-comp]{biblatex}
\usepackage{hyperref}
\usepackage{filecontents}
\begin{filecontents}[overwrite]{\jobname.bib}
@ARTICLE{jensen1916,
    AUTHOR = {A. Jensen and B. Bonus and N. Loretan and D. Yong},
    TITLE = {Bemerkninger til dagligtalen i Kristiania},
    JOURNALTITLE = {Maal og Minne},
    YEAR = {1916},
    NUMBER = {1--2},
    PAGES = {60--89}}
\end{filecontents}
\addbibresource{\jobname.bib}

\begin{document}

\parencite{jensen1916}
\printbibliography
\end{document}

As you see, the \parencite produces author before year. Then how to define a \newparencite producing year before author while acting the same as \parencite in other aspects, for example the hyper links?
With such \newparencite we could have texts as follows.

*

*(1916 Jensen) ....

*(1981, 2010 Knuth) ....

*(2020 Green) ...


text:
Q: Is schema.rdfs.org dead? What alternatives exist? schema.rdfs.org is still linked from the schema.org documentation page as the source for structured representations of schema.org data.  They used to scrape the site daily, but now it appears that the most recent update was in April 2014.  I found a link on their site to the GitHub project with all the scraping code, and could run it as needed, but I would rather access a web service or static representation if a current one exists.
What is my best option for retrieving up-to-date schema.org semantic metadata?

A: On http://schema.org/docs/datamodel.html it says:

The canonical machine representation of schema.org is in RDFa:
schema_org_rdfa.html

It seems to include the latest additions.


text:
Q: redirect users based on their browsers - htaccess or any other way I am designing a website and want to have different pages for different browsers since my page looks very bad in Firefox and IE
Can you please suggest me how to redirect users to different pages based on their browsers.
I would be grateful if you can provide me ready to use script since I am not a professional programmer but designing website for my personal use.
I would like my different pages for different browsers, such as
http:// mysite1 .com/IE.htm
http:// mysite1 .com/Chrome.htm
http:// mysite1 .com/Firefox.htm
http:// mysite1 .com/Safari.htm
Please provide the script for all browsers.
Thank you very very much.

A: There are many, many web browsers, and many versions of browsers as some of the comments have highlighted, and it would be impossible to develop for all of them.
With that said, since this is a personal project, and since you asked, here's a way to do it in PHP:
First, grab the useragent to pinpoint the browser using $_SERVER['HTTP_USER_AGENT']. By comparing their useragent with those of common browsers, it may be possible to identify their browser. A list of common useragents may come in useful.
Specifically, an example for Google Chrome (you may want to refine it to differentiate between chrome versions):
if(strpos($_SESSION['HTTP_USER_AGENT'],"Chrome") !== False){
    header("Location: http://mysite1.com/Chrome.htm");
    //redirects the browser
}

Basically, we use strpos() to search the useragent for any occurrence of the string Chrome, which would strongly suggest a Chrome browser.
Do note that useragents are notoriously unreliable and that it is very easy to fake a useragent, so they should not be trusted.

A: Most of the "my site looks bad in browser X" can be solved by CSS alone. There are multiple techniques that can help you with that, but i will explain two: one suggested by a blog post by Paul Irish and the other one explained right here on in a SO post.
Browser sniffing
HTML:
<!--[if lt IE 7]>      <html class="ie6"> <![endif]-->
<!--[if IE 7]>         <html class="ie7"> <![endif]-->
<!--[if IE 8]>         <html class="ie8"> <![endif]-->
<!--[if gt IE 8]><!--> <html>         <!--<![endif]-->

CSS:
div.foo { color: inherit;}
.ie6 div.foo { color: #ff8000; }

The basic idea is to use conditional comments to add a class to the root element indicating the IE version, allowing you to write specific rules for that version.
CSS reset
The default values for some properties in CSS are different between browsers. A CSS reset is a set of rules that makes these default values the same.

The advantage of using CSS to make your page look the same in different browsers is that the HTML is the same, making it much easier to maintain than having to update who knows how many pages whenever you need to add some text on the site.


text:
Q: Howto write form_for without :url for multiple object editing? I am following http://railscasts.com/episodes/52-update-through-checkboxes. There a form can be written like this: <% form_tag update_multiple_products_path, :method => :put do %>. This does not generate the right action (action="/products") so i have to manually setup the action url.
Is there a away to write form_for without :url parameter?
My setup:
# index.html.erb
<%= form_for update_multiple_products_path, :url => {:action => 'update_multiple'}, :method => :put do %>

# routes.rb
resources :products do
    collection do
      put :update_multiple
    end
  end

# productscontroller
class ProductsController < ApplicationController
  ...
  def update_multiple


text:
Q: Is this lagrangian a possible one in field theory? As far as I know, there are some prerequisites for an action to be preferable in classical field theory like relativistic invariance, locality, real-valueness, derivatives up to first order and internal symmetries invariance.
There's given a lagrangian density which is called "the simplest scalar field lagrangian" in my book (and several others i've checked out): $\mathcal{L} = \frac{1}{2}(\partial_{\mu} \phi)^2 - \frac{1}{2}m^2\phi^2$. My question concerns lagrangian of the form $\mathcal{L} = \frac{1}{2}(\partial_{\mu} \phi)^2 - m^2\phi$. Isn't it a possible one? If it is not, then for what reason (it looks like it satisfies all the conditions written above)? If it is, then isn't it simpler than the first one?
It seems to be quite a stupid question, so I am sorry if ones of its kind are not welcome here. I will be thankful for any help.

A: The problem with having a linear term as the highest order term in the potential energy is that the Hamiltonian won't have a stable ground state. All realistic quantum field theories have to have a state of minimum energy about which small fluctuations can occur, otherwise the vacuum just instantly explodes in a gas of particles with amplitude of oscillations increasing in amplitude (particle number) exponentially with time. One of the Wightman axioms handles just this fact:

There is also a stability assumption which restricts the spectrum of the four-momentum to the positive light cone (and its boundary).

Incorrect old version follows:
Is the only difference the factor of $\frac{1}{2}$ in the mass term? If so, follow @drN's advice and look at the equations of motion, and you'll see why the original one is regarded as simpler than the second.
Formally, both of the Lagrangian densities presented in the question are identical, up to a rescaling of the parameter $m$; do the substitution $m\rightarrow \sqrt{2}m$ in the first Lagrangian density to see. You can also redefine field strength by a scale with $\phi \rightarrow \sqrt{2} \phi$ to get a Lagrangian density with no numerical factors at all:
$\partial_\mu \phi \partial^\mu \phi - m^2 \phi^2,$
and it would correspond to a change in units for how the field $\phi$ is measured, classically, and a rescaling of the units in $\hbar$ in QFT.

A: As far as I understand the difference in Lagrangians is the potential term. One is quadratic and the other is linear.
Theoretically the Lagrangian is just a fancy way of formalizing the equation of motion. Some people right out reject the veracity of the least action formalism.
Having said that the quadratic potential gives rise to the Klein-Gordon EOM.  KG is largely understood as the simplest case of EOM since basically they say that E^2-p^2=m^2.
Another thing to consider is the idea that in QM eigenfunctions are defined up to a global overall phase.
The quadratic Lagrangian implements this symmetry.  The linear potential doesn't.


text:
Q: Attaching an entity of type '' failed because another entity has the same primary key value I have one little problem with my WebApi application.
This problem occurs when i add new entity into my database.
Entities:
public sealed class Lot : Entity
{
    [Required, DefaultValue(false)]
    public bool IsActive { get; set; }

    [Required, DefaultValue(false)]
    public bool IsDelete { get; set; }

    [Required, DefaultValue(false)]
    public bool InCredit { get; set; }

    [DefaultValue(1), Range(1, 10)]
    public int PhaseNumber { get; set; }

    [Required]
    public decimal DesiredPrice { get; set; }

    public Guid? AcceptedBetId { get; set; }

    [Required]
    public DateTime CreationDate { get; set; }

    public DateTime ExpirationDateTime { get; set; }

    [Required]
    public string City { get; set; }

    public User User { get; set; }

    public Car Car { get; set; }

    public ICollection<Bet> Bets { get; set; }

    public Lot()
    {
        Bets = new List<Bet>();
    }
}

public sealed class Bet : Entity
{
    [Required, Range(0.0, double.MaxValue)]
    public decimal Price { get; set; }

    [Required]
    public DateTime CreationDate { get; set; }

    [Range(0, int.MaxValue)]
    public int BetNumber { get; set; }

    public Lot Lot { get; set; }

    public User User { get; set; }
}

Code where i want to add new Bet entity into my database:
Lot lot;
using (LotsManager lotsManager = new LotsManager())
{
     lot = await lotsManager.GetLotAsync(model.LotId);
}

User user;
using (UserManager userManager = new UserManager())
{
      user = await userManager.GetUserAsync(model.UserInfoId);
}

var bet = new Bet
{
      Id = Guid.NewGuid(),
      Price = model.Price,
      CreationDate = DateTime.Now,
      BetNumber = lastBetNumber + 1,
      Lot = lot,
      User = user
 };

 await _betsManager.SaveBetAsync(bet);

On this place a add my entity into DB (db: my SQL)
protected async Task Save<T>(T entity) where T : Entity
    {
        using (var dbContextTransaction = _context.Database.BeginTransaction())
        {
            try
            {
                var dbEntity = await _context.Set<T>().SingleOrDefaultAsync(x => x.Id == entity.Id);

                _context.Set<T>().Attach(entity);
                _context.Entry(entity).State = dbEntity != null ? EntityState.Modified : EntityState.Added;

                await _context.SaveChangesAsync();
                dbContextTransaction?.Commit();
            }
            catch (DbEntityValidationException ex)
            {
                dbContextTransaction?.Rollback();

                var error = ex.EntityValidationErrors.First().ValidationErrors.First();
                throw new InvalidModelException(error.ErrorMessage);
            }
            catch (Exception ex)
            {
                dbContextTransaction?.Rollback();

                throw new InvalidDbOperationException(ex.Message);
            }
        }
    }

When i call my save method, my code throw this exception:

Attaching an entity of type 'WebCar.Domain.Entities.Lot' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.

I am try to use
_context.Set<T>().Attach(entity);
_context.Entry(entity).State = EntityState.Unchanged;
or
_context.Entry(entity).State = EntityState.Unchanged;

But the code still throws an error.

A: This is the code that is causing the problem:
  var dbEntity = await _context.Set<T>().SingleOrDefaultAsync(x => x.Id == entity.Id);
  _context.Set<T>().Attach(entity);

In this scenario, if you find an existing entity, it just got stored in the context.  If you try to add one that already exists, EF can't handle that.  There are a couple of ways you can get around this.  I'll show two:
 var dbEntity = await _context.Set<T>().AsNoTracking().SingleOrDefaultAsync(x => x.Id == entity.Id);

In theory, if you don't track it, then you should be able to add the other one.
However, I think this way is better:
bool doesEntityExist = await _context.Set<T>().Any(x => x.Id == entity.Id);
_context.Set<T>().Attach(entity);
_context.Entry(entity).State = doesEntityExist ? EntityState.Modified : EntityState.Added;


text:
Q: How to get munin to monitor and show CPU temperatures Ubuntu 18.04 system has kernel module coretemp kernel module installed:
% lsmod | grep coretemp
coretemp               20480  0

It also has command-line utilities lm-sensors to check temperatures installed:
% which sensors
/usr/bin/sensors

% dpkg -S /usr/bin/sensors
lm-sensors: /usr/bin/sensors

Calling sensors works + shows all temperatures (package + 4 CPU core temps):
% sensors
coretemp-isa-0000
Adapter: ISA adapter
Package id 0: +44.0°C (high = +100.0°C, crit = +100.0°C) ALARM (CRIT)
Core 0:    +42.0°C (high = +100.0°C, crit = +100.0°C) ALARM (CRIT)
Core 1:    +41.0°C (high = +100.0°C, crit = +100.0°C) ALARM (CRIT)
Core 2:    +44.0°C (high = +100.0°C, crit = +100.0°C) ALARM (CRIT)
Core 3:    +41.0°C (high = +100.0°C, crit = +100.0°C) ALARM (CRIT)

However, looking at munin output in my browser, I see only the HDD temperature chart:

How can I make munin also monitor & display the CPU core temperatures?
things I tried (which didn't help)
% sudo munin-node-configure

% sudo ln -s /usr/share/munin/plugins/sensors_ /etc/munin/plugins/sensors_temp

A: Found the solution. Answer for the benefit of future users.
Make sure plugin output matches supported regexes
Looking at the plugin implementation: /usr/share/munin/plugins/sensors_ I noticed that the plugin has detailed regexes in a global hash called %config.  There are 4 supported sensor categories:

*

*fan (Fan speeds in RPM)

*temp (Temperature in Celsius)

*volt (Voltage in Volts)

*power (Power in Watts)

Since the regexes are very specific, it is important to make sure that the output of the sensors command-line utility, matches these regexes exactly.  You cannot call sensors -u when the munin plugin expects output in the format generated by sensors (without the -u option).
Make sure symlink name matches a sensors category
The name of the symlink from /etc/munin/plugins to /usr/share/munin/plugins/sensors_ must match a supported category. The category name is used as the %config key which defines each regex. Extensions like fan or temp, which match a supported category are good:
sensors_fan -> /usr/share/munin/plugins/sensors_
sensors_temp -> /usr/share/munin/plugins/sensors_

But using tmp or cpu_temp instead of temp will not work.
Restart the munin-node service
Another detail that I missed, was the need to restart the munin-node service after every change in configuration or adding a plugin symlink:
sudo systemctl restart munin-node

Remove empty charts of unsupported/missing devices
If you see empty graphs for non-existent devices. It is also recommended to remove reports on non-exiting devices:
munin-node-configure --suggest --remove-also --shell | bash

Result
Now munin shows my CPU temperatures:


text:
Q: how to solve "dynamic sql generation is not supported against multiple base tables" Error? I got this error "dynamic sql generation is not supported against multiple base tables" in my project.
i got the error on "da.update(dt)" line.
this is the code which i got the error...`so help me how can i solve it..
OleDbDataAdapter da;
    DataSet ds = null;
    BindingSource bsource = new BindingSource();
    OleDbCommand cmd;
    public void BindData()
    {
        cmd = new OleDbCommand("select t.srno,c.AccNumber2,c.Name,t.Admission_Fee,t.Family_fund,t.MonthlyCollection,t.MonthlyDeposit from transDemand t inner join Customer c on t.AccNumber=c.AccNumber where t.IssueDate=@IssueDate and c.Dismember=false", con);
        cmd.Parameters.Add("@IssueDate", OleDbType.Date).Value = datesearch.Value.ToString("dd-MM-yyyy");
        da = new OleDbDataAdapter(cmd);
        ds = new DataSet();
        //dt = new DataTable();
        //da.Fill(dt);
        OleDbCommandBuilder cmdbuild = new OleDbCommandBuilder(da);
        da.Fill(ds, "A");
        bsource.DataSource = ds.Tables["A"];
        dataGridView1.DataSource = bsource;

    }

    private void btnupdate_Click(object sender, EventArgs e)
    {
        DataTable dt = ds.Tables["A"];
        this.dataGridView1.BindingContext[dt].EndCurrentEdit();

        da.Update(dt);

        BindData();
    }


text:
Q: Ask user for partial PIN I'm developing an additional security module for a web application, which asks the user to enter a PIN code randomly generated at user signup. The PIN is stored AES-128 encrypted in a db and sent by sms to the new user.
The user will be ask to provide his PIN when certain situations occur (i.e. "strange" accesses, or unusual operations) - and i'd like the user not to enter the entire PIN code, but just 2 digit (for example: the 1st and the 6th).
2 4 6 2 9 1 8 3    -> entire PIN
^---------^----    -> digits i'm asking

My question is: is the a more secure way to choose which digits to ask? Should i choose them randomly (but an eventual attacker who owns part of the pin could retry until the digits he owns are requested) or should i ask each user always for the same digits - maybe storing their indexes encrypted with the PIN, or generate them with a function parametrized with the PIN itself?
Thanks.

A: The way I find most online banking software implements this is that once it's asked for two digits it will keep asking for the same until the user either blocks the account (from too many wrong attempts) or answers it correctly.  After this another 2 digits is randomly selected for next time.
As far as I know this is the only way to mitigate an attacker simply reloading until they get a combination they desire.

A: If you have secondary, more secure way of authentication, then do ask for random digits but lock the account after a few failed attempts. That way, the chance that an attacker has the correct digits is very small, yet the implications of the same two digits leaking are also mitigated.
[Edit: As @m.edmondson suggests, only change the pair after a successful login, not before.]
If you just ask for the same two digits over and over, you might as well just have a two-digit PIN.
If a user inadvertently locks herself out, you can always fall back on the secondary authentication to recover the account.


text:
Q: Host an apache web server locally on Ubuntu machine I want to host an Apache web server and want to upload files on it .
can someone please give me a broad idea to getting started and basic mechanism behind local Apache server. Related links will be highly appreciated.
PS: I am not an expert Linux user, so please respond on a basic level about Linux commands.

A: This is a nice guide to get started: http://www.howtoforge.com/ubuntu_lamp_for_newbies


text:
Q: Dynamic backgroundColor UIImageView does not update iOS When I move the view cursor of first UIImageView, I get output the color of the point rgb using a UIPanGestureRecognizer. With this color I have to create a gradient in the second uiview that starts from the left of the starting color and comes to the right to the white. I noticed that after calculating the first rgb the color of the backgroundColor of second UIView is corrected but after moving the cursor of the first UIView and getting changes in rgb the color but the backgroundColor of second uiview remains unchanged.

  @objc func wasDragged(gestureRecognizer: UIPanGestureRecognizer) {

    if gestureRecognizer.state == .began || gestureRecognizer.state == .changed {

        let translation = gestureRecognizer.translation(in: self.view)

        gestureRecognizer.view!.center = CGPoint(x: gestureRecognizer.view!.center.x + translation.x, y: gestureRecognizer.view!.center.y + translation.y)
        gestureRecognizer.setTranslation(CGPoint.zero, in: self.view)
        let color = self.imageView.getPixelColorAt(point: gestureRecognizer.view!.center)
       // color is correct

        UIView.animate(withDuration: 1, delay: 0.0, options:[.repeat, .autoreverse], animations: {
             self.gradientview.backgroundColor = UIColor.clear
             self.gradientview.gradientBackground(from: color, to:   UIColor.white, direction: GradientDirection.leftToRight)
       // color is correct only first time, after remains unchanged
        }, completion:nil)

    }
 }

In extensions
I create gradient starting from this example
Programmatically create a UIView with color gradient
  enum GradientDirection {
     case leftToRight
     case rightToLeft
    case topToBottom
    case bottomToTop
 }

 extension UIView {
     func gradientBackground(from color1: UIColor, to color2: UIColor, direction: GradientDirection) {
    let gradient = CAGradientLayer()
    gradient.frame = self.bounds
    gradient.colors = [color1.cgColor, color2.cgColor]

    switch direction {
    case .leftToRight:
        gradient.startPoint = CGPoint(x: 0.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 1.0, y: 0.5)
    case .rightToLeft:
        gradient.startPoint = CGPoint(x: 1.0, y: 0.5)
        gradient.endPoint = CGPoint(x: 0.0, y: 0.5)
    case .bottomToTop:
        gradient.startPoint = CGPoint(x: 0.5, y: 1.0)
        gradient.endPoint = CGPoint(x: 0.5, y: 0.0)
    default:
        break
    }

    self.layer.insertSublayer(gradient, at: 0)
 }
}

A: You have to set to nil all sublayer
 self.gradientview.backgroundColor = UIColor.clear
 self.gradientview.layer.sublayers = nil

 UIView.animate(withDuration: 1, delay: 0.0, options:[.repeat, .autoreverse], animations: {

            self.gradientview.gradientBackground(from: color, to: UIColor.white, direction: GradientDirection.leftToRight)

   }, completion:nil)


text:
Q: Enable SSO login in Oracle APEX Need help enabling SSO login in Oracle APEX application, my company supports SAML 2.0, they are asking me what nameid will be used. I don't know if SSO is an option in APEX or not? Any help is appreciated guys. Thanks.

A: This article should give you some guidance:
https://insum.ca/saml2-single-sign-on-with-oracle-application-express/
TL;DR

*

*Use Apache HTTPD as a web proxy for APEX.

*Install and configure the mod_auth_mellon module for the web server.

*Set up the application on the identity management system of choice.

*For the APEX application, use the HTTP Header Authentication Scheme. The HTTP Header variable should have been configured when mod_auth_mellon was installed and set up.

HTH.

A: I don't know SAML, but - as far as SSO in Apex is concerned, here's how to do that. See if it helps.
Suppose that there's an application which is used as a "menu" that lets you navigate through different Apex applications. In that menu application, go to
Shared Components
  > Authentication Schemes
  > choose Current scheme (e.g. "My menu auth. Scheme")
  > Session Cookie Attributes > type MY_MENU_COOKIE into  "Cookie name" field

If application menu is the list item, its query might look like this: it selects all applications available to user logged in as :APP_USER (those user:application pairs are stored in the oper_x_app table). Pay attention to &SESSION. - without it, it won't work:
select
  null,
  app_name labelValue,
  'http://szg01lcp1.data.centar:8084/apex/f?p=' || id_app ||':1:&SESSION.' targetValue,
  null is_current                                        --     ^^^^^^^^^
from applications                                        --     This!
where id_app in (select id_app from oper_x_app
                 where username = :APP_USER
                )
order by app_name

Now, for all those applications, you have to do the same: navigate to
Shared Components
  > Authentication Schemes
  > choose Current scheme (e.g. "Copy of My menu auth. Scheme")
  > Session Cookie Attributes
  > type MY_MENU_COOKIE into "Cookie name" field

Go to that application's
Navigation menu
  > Create list entry
  - name the entry "My apex menu"
  - target type URL should look like this; &SESSION. is again important!

    http://your_server:8084/apex/f?p=118:1:&SESSION.
                                           ^^^^^^^^^
                                           This!

That's all; using the "My apex menu" navigation menu entry, you can go to the central place of your applications and switch among them without having to log on all over again.


text:
Q: antlr grammar for triple quoted string I am trying to update an ANTLR grammar that follows the following spec
https://github.com/facebook/graphql/pull/327/files
In logical terms its defined as
StringValue ::
   - `"` StringCharacter* `"`
   - `"""` MultiLineStringCharacter* `"""`

StringCharacter ::
  - SourceCharacter but not `"` or \ or LineTerminator
  - \u EscapedUnicode
  - \ EscapedCharacter

MultiLineStringCharacter ::
  - SourceCharacter but not `"""` or `\"""`
  - `\"""`

(Not the above is logical - not ANTLR syntax)
I tried the follow in ANTRL 4 but it wont recognize more than 1 character inside a triple quoted string
string : triplequotedstring | StringValue ;

triplequotedstring: '"""' triplequotedstringpart?  '"""';

triplequotedstringpart : EscapedTripleQuote* | SourceCharacter*;

EscapedTripleQuote : '\\"""';

SourceCharacter :[\u0009\u000A\u000D\u0020-\uFFFF];

StringValue: '"' (~(["\\\n\r\u2028\u2029])|EscapedChar)* '"';

With these rules it will recognize '"""a"""' but as soon as I add more characters it fails
eg: '"""abc"""' wont parse and the IntelliJ plugin for ANTLR says
line 1:14 extraneous input 'abc' expecting {'"""', '\\"""', SourceCharacter}

How do I do triple quoted strings in ANTLR with '\"""' escaping?

A: Some of your parer rules should really be lexer rules. And SourceCharacter should probably be a fragment.
Also, instead of EscapedTripleQuote* | SourceCharacter*, you probably want ( EscapedTripleQuote | SourceCharacter )*. The first matches aaa... or bbb..., while you probably meant to match aababbba...
Try something like this instead:
string
 : Triplequotedstring
 | StringValue
 ;

Triplequotedstring
 : '"""' TriplequotedstringPart*? '"""'
 ;

StringValue
 : '"' ( ~["\\\n\r\u2028\u2029] | EscapedChar )* '"'
 ;

// Fragments never become a token of their own: they are only used inside other lexer rules
fragment TriplequotedstringPart : EscapedTripleQuote | SourceCharacter;
fragment EscapedTripleQuote : '\\"""';
fragment SourceCharacter :[\u0009\u000A\u000D\u0020-\uFFFF];


text: Q: Instagram Basic Display API, can we skip the "Save Your Login Info? step? Using the Instagram Basic Display API, is there a way to have the oauth log-in process skip the "Save Your Login Info?" step? That screen has links to many pages where the users of our application are not allowed to access. We have a kiosk application that is using Instagram Basic Display API to allow the user to retrieve their Instagram images. The user should not be allowed to visit their feed or many of the other links on that screen.


text:
Q: I have the below code that does not seem to work at all ..I keep getting: Microsoft JScript runtime error: Object expected I was tring to create a simple datepicker control using JQuery, but i was getting that error.
I have no clue why i am getting that error. Trying from 3 hrs but couldn't find the solution.
Can anyone plz help me with this.
Here is my code which i placed in masterpage.
 <head runat="server">
<title></title>
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href="~/Styles/DevExMenu.css" rel="stylesheet" type="text/css" />
<link href="~/Styles/jquery-ui-1.8.10.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="/Scripts/jquery-1.4.4.js"></script>
<script type="text/javascript" src="/Scripts/jquery-ui-1.8.10.custom.min.js" ></script>
<asp:ContentPlaceHolder ID="HeadContent" runat="server">
</asp:ContentPlaceHolder>
   </head>

this is the code i am using in my source file:
<asp:Content ID="Content4" ContentPlaceHolderID="MainContent" runat="server">
    <script type="text/javascript">
        $(function () {
            $("#datepicker1").datepicker();
        });

    </script>
<p>
 <asp:TextBox ID="datepicker1" runat="server"></asp:TextBox>
                                                                                </p>
</asp:Content>

I dont know what the problem is but when i am trying the same code without a master page it is working fine.
Please help.

A: .NET could be renamaing the id of datepicker1.
After the DOM is ready, you could try to get the runtime id and setting to a js var:
textboxDatePick = '<%= datepicker1.ClientID %>';

Then in your scipt change  $("#datepicker1").datepicker();
to: $("#" + textboxDatePick).datepicker();


text:
Q: Add field to solr managed-schema by sorj is not working I use SOLR 8.5.0 and solrj client. I managed to create new core in standalone mode by solrj and I wanted to add fields to my schema. The code is the following:
//General solrClient not including core name
CoreAdminRequest.Create.createCore(this.name, this.name, solrClient);

//other solrClient including the created core name as a part of the baseUrl
SolrClient solrC=new HttpSolrClient.Builder("http://localhost:8983/solr/petshop").build();

for(SolrField field : solrFields) {
        Map<String, Object> fieldAttributes = new HashMap<String,Object>();
        fieldAttributes.put("name", field.getFieldName());
        fieldAttributes.put("type", field.getDataType().getSolrType());
        fieldAttributes.put("stored", field.isStored());
        fieldAttributes.put("indexed", field.isIndexed());
        fieldAttributes.put("multiValued", field.isMultiValued());
        fieldAttributes.put("omitNorms", field.isOmitNorms());
        fieldAttributes.put("docValues", field.isDocValues());
        fieldAttributes.put("required", false);
        fieldAttributes.put("uninvertable", false);
        try {
            SchemaRequest.AddField schemaRequest = new SchemaRequest.AddField(fieldAttributes);
            SchemaResponse.UpdateResponse response =  schemaRequest.process(solrC);
            System.out.println("Schema request url: "+response.getRequestUrl());
          } catch (Exception e) {
            e.printStackTrace();
          }
    }

When I check the admin UI, the core was created properly. Only modifying the schema was not succeeded.
Unfortunately, I get a very useless exception:  org.apache.solr.client.solrj.impl.HttpSolrClient$RemoteExecutionException: Error from server at http://localhost:8983/solr/petshop: error processing commands.
Does anybody have idea what goes wrong with this code?
Thanks in advance,
Roland


text:
Q: What's the recommended control naming convention for XAML markup? When working with WPF or Silverlight, how should one use control naming conventions? Do you name the controls in XAML markup? I have seen samples of projects at codeplex with control names such  as "selectButton" or "btnSelect". What would you recommend?

A: Microsoft has guidelines published here on their web site.  The bottom line is that Hungarian naming conventions are out.
EDIT
To make this more clear, Microsoft has dropped Hungarian notation from all of their naming conventions, including UI elements.  HOWEVER, MS has not documented any recommendations for UI elements.  There are lots of links out there that note this and offer their suggestions but the bottom line is that with UI elements, you're on your own.  Example link.
In our standard we've dropped Hungarian notation and are using explicit naming, meaning a button called OK would be named ButtonOK, a textblock called Comments would be TextblockComments.  The downside is that names can get kind of long, the positive is that EVERYONE knows exactly what the element is.
As long as you establish what works for you and use that standard consistently, you can't go wrong.

A: I usually dont name my controls in XAML, as it would be, most of the time, unused considering everything is set or controlled through bindings. Source : Pete Brown

A: I don't know about XAML but for regular old ASP.NET the conventions I've seen are:

*

*Good old Hungarian (e.g. txtFirstName, ddlState, chkAcceptsTerms)

*Explicit naming (e.g. TextFirstName, DropdownState, CheckAcceptsTerms)

Not sure which I prefer, honestly.  I used to see a lot of code like #2 but reversed (e.g. FirstNameTex, StateDropdown, AcceptsTermsCheck) but I like the other way since it groups related controls together.