text:
Q: Sed replacing number within curly braces with regex I am trying to write a script to automate the process of generating multiple output files with different parameters. This requires replacing the number in curly braces after CONFIG.c_mm2s_burst_size and CONFIG.c_s2mm_burst_size in the following code statement.
  set_property -dict [ list CONFIG.c_include_mm2s {1} CONFIG.c_include_mm2s_dre {0} CONFIG.c_include_s2mm_dre {0} CONFIG.c_include_sg {0} CONFIG.c_m_axi_mm2s_data_width {32} CONFIG.c_m_axis_mm2s_tdata_width {32} CONFIG.c_micro_dma {0} CONFIG.c_mm2s_burst_size {2} CONFIG.c_s2mm_burst_size {2} CONFIG.c_sg_length_width {23}  ] $axi_dma_0

The code is in tcl. I tried variable substitution but it doesn't interpret correctly for something like
CONFIG.c_mm2s_burst_size {$var}
So I think it shouldn't be difficult with sed and perl to replace the number in text. However, I have searched and tried all night without success.
I have tried:
sed -r 's/burst_size\>\s\{(\d+)\}/256/g'

sed -r 's/burst_size\s\{(\.+)\}/256/g'

sed -r 's/burst_size#\{(\d+)\}/256/g'

sed -r 's/burst_size\s\\{(\d+)\\}/256/g'

and many more, none of them works. I am using Ubuntu with GNU 4.2.2. Other one liner in other languages are welcomed to as long as I change the number systematically.
Many thanks

A: You can simply use the following Perl one-liner.
perl -pe 's/burst_size\s+{\K\d+/256/g'

A: To replace the partcular number inside {} brackets which was preceded by the string burst_size, you could use the below sed command. sed won't support \s or \d. Instead of \s you could use the POSIX notation [[:space:]] and instead of \d, you could use [0-9]
sed 's/\(burst_size \+{\)[0-9]\+}/\1256}/g'
sed -r 's/(burst_size +\{)[0-9]+\}/\1256}/g'

Example:
$ echo 'CONFIG.c_mm2s_burst_size {2} CONFIG.c_s2mm_burst_size {2} CONFIG.c_sg_length_width {23}  ] $axi_dma_0' | sed 's/\(burst_size \+{\)[0-9]\+}/\1256}/g'
CONFIG.c_mm2s_burst_size {256} CONFIG.c_s2mm_burst_size {256} CONFIG.c_sg_length_width {23}  ] $axi_dma_0
$ echo 'CONFIG.c_mm2s_burst_size {2} CONFIG.c_s2mm_burst_size {2} CONFIG.c_sg_length_width {23}  ] $axi_dma_0' | sed -r 's/(burst_size +\{)[0-9]+\}/\1256}/g'
CONFIG.c_mm2s_burst_size {256} CONFIG.c_s2mm_burst_size {256} CONFIG.c_sg_length_width {23}  ] $axi_dma_0

A: \s and \d and not recognized by sed
You can use either
sed -r 's/(burst_size )\{[0-9]+\}/\1{256}/g' input

or
sed -r 's/(burst_size[[:space:]])\{[[:digit:]]+\}/\1{256}/g' input


text:
Q: Draw a circle over a line I want to draw a circle over a line.
I am using e.Graphics.DrawLine(blackPen, x1, y1, x2, y2); to draw line and e.Graphics.DrawArc(greenPen, rect1, 0, 360); to draw the circle.
Here  is output of my program. I want that green circle to be over the black line.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can we create an object outside of methods but inside the class? If yes then what's the purpose of creating an object outside the class? public class C
{
    public void p() { System.out.println(" method p"); }

    public static void main(String[] args) {System.out.println(" main method");}

    C c1 = new C(); // Why java allows this? that is, creating object outside of
                 //the methods but inside the class?
                 //For what purpose does Java allowed this? when is this needed?

    c1.p(); //This generates error, Why is this not allowed?
}

A: C c1 = new C(); is a field declaration.
During the field declaration, it is valid to assign to it a value.
The c1.p(); statement is not invoked inside a method or a block (static or instance block).
It is valid to do it in a method or a block without other requirements.
But if you do it in another place, it has to be necessarily be used to assign a field you are declaring.
For example, this is legal :
public class C
{
    public void p() { System.out.println(" method p"); }

    public C newC(){
       return new C();
    }

    public static void main(String[] args) {System.out.println(" main method");}

    C c1 = new C(); // Why java allows this? that is, creating object outside of
                 //the methods but inside the class?
                 //For what purpose does Java allowed this? when is this needed?

    C c2 = c1.newC();

   public void myMethod(){
      c1.p();
   }
}

A: This part
C c1 = new C();

It's an attribute to class C
c1.p();

is a call to some method, it's not allowed to call it in the scope, you could call the method in other class method or in this class but inside a method. it's just the scope

A: C c1 = new C();

Means you create class variable of type C named c1 and initialize it. You could instead initialize it to null
C c1 = null;

Or not at all
C c1;

However you can't use it out of a method scope, like calling the p() method.

A:
Can we create an object outside of methods but inside the class?

Yes. Of Course

If yes then what's the purpose of creating an object outside the class method (I think you mean method)?

If you want instances of your class to maintain the state of another object, then how else would you expect to do so.
Consider the following class:
class C
{
    // member of C instances
    private List<String> list = new ArrayList<>();

    // constructor
    public C ()
    {}

    // How else would you add to the member list if
    // it wasn't declared outside of methods?
    public void addString (String s)
    {
        list.add (s);
    }

    // return the size of the list
    public int count ()
    {
        // Should I create a new list in here... No, that wouldn't make
        // sense. I should return the size of the member list that
        // strings may have been added to with the addString method.
        return list.size();
    }
}

Let's see this in action:
public static void main (String[] args)
{
    // Create a new C instance
    C c = new C();

    // I sure hope C is keeping track of all these strings??
    c.addString( "1" );
    c.addString( "2" );

    // Should print 2
    System.out.println( "Number of strings: " + c.count() );
}


text:
Q: Configuring JBehave to run multithread TestNG tests I'm trying to create a Proof-of-Concept of using JBehave and TestNG together. What I want to do, is to run a story simultaneously in multiple threads in order to test my codes thread safety.
I have a simple class that only does one thing, calculates modulo 7 on a given integer value. I've created a simple BDD test for this class. I've set up my BDD test as described in JBehave "Getting started" documentation. The only difference is, that in my JUnitStory file, instead of using JUnit's @Test annotation, I've used TestNG's
@org.testng.annotations.Test(threadPoolSize = 10, invocationCount = 100, timeOut = 10000)

When I run the test, everything goes fine for the first 70-90% of the cases, then an exception occurs and the rest of the runs fail
===============================================
    Default test
    Tests run: 100, Failures: 11, Skips: 0
===============================================

The exception that occurs is
FAILED: run
java.util.concurrent.RejectedExecutionException
    at java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:1774)
    at java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:768)
    at java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:656)
    at java.util.concurrent.AbstractExecutorService.submit(AbstractExecutorService.java:92)
    at org.jbehave.core.embedder.StoryManager.submit(StoryManager.java:203)
    at org.jbehave.core.embedder.StoryManager.runningStory(StoryManager.java:138)
    at org.jbehave.core.embedder.StoryManager.filterRunning(StoryManager.java:122)
    at org.jbehave.core.embedder.StoryManager.runningStoriesAsPaths(StoryManager.java:107)
    at org.jbehave.core.embedder.StoryManager.performStories(StoryManager.java:93)
    at org.jbehave.core.embedder.StoryManager.runStories(StoryManager.java:81)
....

I'm relatively new to both JBehave and TestNG, so I was wondering if this could be simply a configuration issue or is it actually a bug in JBehave.

A: Could it be that the thread pool has been shutdown and you (or JBehave) is trying to submit tasks to it?

A: It looks to me like you just need to have 2 or more test classes, and configure your testing.xml file to run all classes in that package as a group.  Because TestNG generally forks threads  "by class" (this is the default configuration??), you need to have multiple classes or else it will run all 10 of your method invocations inline, one at a time.


text:
Q: Importing javascript into React How would I import this https://codepen.io/aecend/pen/WbONyK javascript fluid simulation into a react component?

Click and drag!

<canvas id="c"></canvas>

A: There are a couple ways to do this, for example

*

*Create a .js (javascript file) which houses the script

*Include the script in a  tag in your index.html

*Execute it on the window object within the script

I created a quick codesandbox.. I had to make some edits on the variable declarations in the fluidSim.js file.
See here
Wait about 30s and click the refresh on the inner browser window once loaded


text:
Q: Java Array returns Null So when I use this to pick a String of random events it returns a null:
public static List<String> pickNRandom(List<String> lst, int n) {
    List<String> copy = new LinkedList<String>(lst);
    Collections.shuffle(copy);
    return copy.subList(0, n);
}

static List<String> randomP;
public List<String> items(){
    List<String> teamList = new LinkedList<String>();
    teamList.add("team1");
    teamList.add("team2");
    teamList.add("team3");
    teamList.add("team4");
    teamList.add("team5");
    teamList.add("team6");
    List<String> randomPicks = pickNRandom(teamList, 3);
    randomPicks = randomP;
    return randomPicks;
}

public static void Store() {
    Random rand = new Random();
    int people = rand.nextInt(50) + 1;
    List<String> itemsIn = randomP;
    System.out.println("People in store: "+people + "\nItems in store: "+itemsIn);
}

public static void main(String[] args) {
    Store();

}

Why is it returning null and what can I do to fix this?

A: In this line   List<String> itemsIn = randomP; you assign list that was not initialized its default value is null. I think that's how your line should look like: List<String> itemsIn = items(); remember to change method items() to static.

A: Issue is clear, but not question (it can have different solutions)... I've added small changes.
public static List<String> pickNRandom(List<String> lst, int n) {
    List<String> copy = new LinkedList<String>(lst);
    Collections.shuffle(copy);
    return copy.subList(0, n);
}

public static List<String> items(){
    List<String> teamList = new LinkedList<String>();
    teamList.add("team1");
    teamList.add("team2");
    teamList.add("team3");
    teamList.add("team4");
    teamList.add("team5");
    teamList.add("team6");
    return pickNRandom(teamList, 3);
}

public static void Store() {
    Random rand = new Random();
    int people = rand.nextInt(50) + 1;
    List<String> itemsIn = items();
    System.out.println("People in store: "+people + "\nItems in store: "+itemsIn);
}

public static void main(String[] args) {
    Store();
}

People in store: 10
Items in store: [team6, team2, team3]

In your code randomP was useless (never initialized, never filled in)

A: You haven't initiated List<String> randomP at any point.

A: It doesn't return null. You immediately overwrite what the function returns with an uninitialized variable here:
randomPicks = randomP;

It's not clear why you have that... but don't do that.

A: randomP is declared but not initialized, items() is never called, same as pickNRandom
so you can initialize the list (but this doesnt mean that it will be populated...)
 static List<String> randomP = new ArrayList<>();

you will get an empty list instead of null

People in store: 12
Items in store: []


text:
Q: In an objective c ios project, where to find the database schema? I know virtually no objective c, but I'm working on rewriting an old ios project.
In Rails, in the database folder there's migrations and automatically generated schema. The schema is a representation of all the up to date tables with all migrations applied.
In the ios project, in ./resources/database/ there's updates (like migrations) and a .db file. Where's the schema?

A: I downloaded db browser for sqlite (https://sqlitebrowser.org/dl/) and used it to open the .db file. There I can find all information I might find in a Rails schema.


text:
Q: File transfer over VPN on VirtualBox I'm accessing a computer inside a VPN via SSH. This access is being done through a VM.
If I wanted to do file transfer and was in an actual machine inside the network I would do rsync from/path/filename username@hostname:to/path/. Although, on the VM, my machine has a name like filipe@filipe-VirtualBox, and doing rsync with that user and hostname doesn't work. Is it possible to transfer the files from the remote machine inside the VPN to my VM? If not through rsync, what's the easiest way to transfer them?

A: You don't mention what it is that fails. If it's just the hostname that doesn't resolve, you can use the IP address of the target machine instead of the name: fillipe@10.20.30.40 If there is a different issue, can you please elaborate on where it's failing?


text:
Q: Two kinds of prime gaps $$1361 - 1327 = 34$$
Between these two prime numbers there are no others. No prime gaps this big come before this one; i.e. this one is "maximal".
The largest prime not exceeding the square roots of any of them is $31.$ All prime numbers not exceeding $31$ divide some number between these two primes.
$$ 9587 - 9551 = 36 $$
Between these two prime numbers there are no others. No prime gaps this big come before this one, i.e. this one is "maximal".
The largest prime not exceeding the square roots of any of them is $97.$ Some prime numbers not exceeding $97$ divide no number between these two primes. In fact, $97$ is one of those. So are $83$ and $89.$
Are infinitely many maximal prime gaps like the first one mentioned above, in this respect? How are they distributed among maximal prime gaps? (I'd guess they occur less frequently than those like the second one.)

A: Consider a maximal gap that follows a very large prime $p$.

*

*Maximal gap sizes are $O(\log^2 p)$ (by  Cramer's conjecture).

*Almost all maximal gaps are asymptotically equivalent to $\log^2 p$ (a modified form of Shanks conjecture).

*Hence, there are $O(\log^2 p)$ composite integers inside our maximal gap.

*The expected number of distinct prime factors of one such composite integer is $\sim\log\log p$ (by the Erdos-Kac theorem).

*Therefore the expected total number of distinct prime factors dividing at least one integer inside the gap is $f(p)=O(\log\log p \cdot \log^2 p)$

*On the other hand, $\pi(\sqrt{p})\sim {\sqrt{p}\over\log \sqrt{p}}$ (by the prime number theorem).

*Thus $f(p) = o(\pi(\sqrt{p}))$, i.e. we expect only a zero proportion of primes below $\sqrt{p}$ to be factors of some integer inside the gap.
On probabilistic grounds we conclude that gaps of the second type are much more common. In fact we should expect that gaps of the first type are only a zero proportion of all maximal gaps.
Moreover, we should expect only finitely many gaps of the first type.
This is provable if Cramer's conjecture is true. Let $\Pi$ be the product of all  composites inside the gap. What's the order of magnitude of $\log\Pi$? Firstly, $\Pi$ is a product of $\sim\log^2p$ integers each of size $\sim p$; so
$$
\log\Pi \sim \log(p^{\log^2p}) \sim \log^2p \cdot \log p = \log^3p.
$$
 On the other hand, $\Pi$ is a product of all prime factors of these composites. By assuming that all primes below $\sqrt{p}$ participate in the product (and small primes participate many times) we would get a different asymptotic size for the same product:
$$
\log\Pi > \log(\sqrt{p}\#) \sim \sqrt{p} \quad (\# \mbox{ denotes primorial).}
$$
But $$\lim_\limits{p\to\infty}{\log^3 p \over \sqrt{p}}=0.$$
That's a contradiction -- unless there are only finitely many examples of a maximal gap near $p$, containing composites divisible by every prime below $\sqrt{p}$.

A: The short story is the divisor is larger than the gap and this may true for other maximal gaps.  The rest of the story:  $9587 / 83 = 115.5$ and the next prime number is $113$ or $127.$  $83 \times 127 = 10541$ or $83 \times 113 = 9379.$  $9587 / 89 = 107.7$ the next prime numbers are $107$ or $109.$  $9587 / 97 = 98.8$ and the next prime numbers are $97$ or $101.$  These calculations show how they were not related to the gap of $34$ between $9551$ and $9587.$


text:
Q: Action Failed on OpenStoredProcedure action in Access Project (ADP) macro In an Access Project (ADP), there is a macro set up the calls a stored procedure on a SQL Server 2005 database (which updates a table, but does not return any results). This macro is called when a user clicks on a button in a form.
It works when logged in as the database owner and the ADP is opened, but when opened by a user with more restrictions, but permissions set to execute, the stored procedure returns with Action Failed error, but does not give a reason for the failure.
Macro set up as:
Hourglass   Yes
SetWarnings    No
OpenStoredProcedure dbo.MyStoredProcedure
Requery
SetWarnings Yes
Hourglass No

A: Sounds like the user does not have privileges on the underlying tables.
Try logging in as the user from SQL Server Managerment Studio and run the Stored Procedure directly.


text:
Q: Open second window from main with pyqt5 and qt designer I'm creating an application with two windows using pyqt5 and QtDesigner. A button on the main window "MainWindow.ui" should open a second window from the file "age_entry.ui" but I seem to be missing something. Clicking the button on the first form produces this error":

Exception "unhandled TypeError"
  QDialog(parent: QWidget = None, flags: Union[Qt.WindowFlags, Qt.WindowType] = Qt.WindowFlags()): argument 1 has unexpected type 'bool'

Here is the code for the main window:
# -*- coding: utf-8 -*-

import sys
from PyQt5 import uic, QtWidgets

Ui_MainWindow, QtBaseClass = uic.loadUiType("MainWindow.ui")
LandingPageUI, LandingPageBase = uic.loadUiType("age_entry.ui")

class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):

    def __init__(self):
        QtWidgets.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)

        def showAgeEntryForm(self):
            self.child_win = AgeEntryForm(self)
            self.child_win.show()

        self.btnOpenAges.clicked.connect(showAgeEntryForm)

class AgeEntryForm(LandingPageBase, LandingPageUI):
    def __init__(self, parent=None):
        LandingPageBase.__init__(self, parent)
        self.setupUi(self)

if __name__ == "__main__":
    app=QtWidgets.QApplication.instance()
    if not app:
         app = QtWidgets.QApplication(sys.argv)

    window = MyApp()
    window.show()
    sys.exit(app.exec_())

Thanks in advance!
Here is the MainWindow and age_entry file in code form:
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'MainWindow.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(526, 338)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.label_9 = QtWidgets.QLabel(self.centralwidget)
        self.label_9.setGeometry(QtCore.QRect(90, 10, 341, 41))
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.label_9.setFont(font)
        self.label_9.setObjectName("label_9")
        self.btnOpenAges = QtWidgets.QPushButton(self.centralwidget)
        self.btnOpenAges.setGeometry(QtCore.QRect(130, 90, 181, 61))
        self.btnOpenAges.setObjectName("btnOpenAges")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 526, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)

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

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.label_9.setText(_translate("MainWindow", "Ageing Session Management"))
        self.btnOpenAges.setText(_translate("MainWindow", "Enter Ages"))

And the age_entry.ui
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'age_entry.ui'
#
# Created by: PyQt5 UI code generator 5.7
#
# WARNING! All changes made in this file will be lost!

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(350, 189)
        self.label_13 = QtWidgets.QLabel(Dialog)
        self.label_13.setGeometry(QtCore.QRect(90, 20, 451, 61))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_13.setFont(font)
        self.label_13.setObjectName("label_13")

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

    def retranslateUi(self, Dialog):
        _translate = QtCore.QCoreApplication.translate
        Dialog.setWindowTitle(_translate("Dialog", "Dialog"))
        self.label_13.setText(_translate("Dialog", "Age Entry Form"))

A: Two issues your indentation is wrong. Secondly your missing self. on showAgeEntryForm. Try this:
def __init__(self):
    QtWidgets.QMainWindow.__init__(self)
    Ui_MainWindow.__init__(self)
    self.setupUi(self)
    self.btnOpenAges.clicked.connect(self.showAgeEntryForm)

def showAgeEntryForm(self):
    self.child_win = AgeEntryForm(self)
    self.child_win.show()


text:
Q: Springboot security+JWT refresh token I have an Angular app with Spring boot as backend. I have implemented Spring security with JWT authentication. The workflow is as follows

*

*Angular will call a create token end point which will return a JWT token

*Client will use this token for any subsequent api calls.

*There is a filter in the backend which will parse the token and if it is valid, will allow the user to proceed further

My question is related to refresh token. Let's say the expiry of the token is 15 minutes. If the user is logged in, I want the session to be active by generating a refresh token and send it back to the angular app. What is the best way of doing this?
I am not using OAUTH here, just jjwt library and spring security starter.


text:
Q: Возможно ли создать объектные типы данных внутри пакета? Возможно ли создать объектные типы данных внутри пакета?
Нечто подобное:
create or replace package my_package as
    type my_type as object (
        id number(15)
     );
end;

Завершится ошибкой:

Error(3,9): PLS-00540: object not supported in this context.

В конечном итоге, хотел бы использовать полиморфизм, а также дать объектам доступ к таблицам и использовать PL/SQL, что недопустимо в типах, определенных вне пакетов.

Свободный перевод Possible to create Oracle Database object types inside of PL/SQL?
 от участника @jlpp

A: Основной упор при дизайне объектно ориентированных расширений БД был направлен на реализацию ORD (Object-oriented Database Model). Поэтому, пользовательские (или объектные) типы данных могут быть созданы только в SQL, но испольоваться они могут без всяких ограничений в PL/SQL контексте.
Например, определим два новых типа данных (UDT=user defined type) унаследованых (inheritance) от одного абстрактного (ADT=abstract data type):
create or replace type tbase force as object (
    msg varchar2 (16),
    member function print return varchar2) not instantiable not final
/
create or replace type tdate under tbase (
    overriding member function print return varchar2) instantiable final
/
create or replace type ttime under tbase (
    overriding member function print return varchar2) instantiable final
/

Вся логика этих типов данных реализуется в их теле (type body). Использовать можно всё, что доступно в пакетах или блоках PL/SQL, например, статический и динамический SQL, внутренние PL/SQL типы данных, исключения и т.п.:
create or replace type body tdate as
    overriding member function print return varchar2 is
    begin
        return self.msg||' '||to_char (sysdate, 'dd Mon'); end;
end;
/
create or replace type body ttime as
    overriding member function print return varchar2 is
    begin
        return self.msg||' '||to_char (sysdate, 'hh24:mi'); end;
end;
/

Не только небольшой функционал, но и полностью всё приложение может быть реализовано как пользовательский тип данных:
create or replace type tappl force as object (
    name  varchar2 (16),
    member function main return char) instantiable final
/
create or replace type body tappl is
    member function main return char is
        function print (what tbase) return varchar2 is
        begin return what.print;
        end;
    begin
        dbms_output.put_line (
            self.name||': '||print (tdate ('Сегодня'))||', '||print (ttime ('сейчас')));
        return 'ok';
    end;
end;
/

Выше простейший пример полиморфизма (polymorphism) -- для каждго из экземпляров по ссылке на базовый тип данных будет вызвана своя функция print.
Для запуска этого небольшого прилижения потребуется всего лишь анонимный блок:
var ret char
exec :ret := tappl ('Новости').main

Новости: Сегодня 15 Jul, сейчас 16:45

RET
--
ok

A: Цитата из главы 3.1 Declaring and Initializing Objects in PL/SQL книги официальной документации Object-Relational Developer's Guide:

Using object types in a PL/SQL block, subprogram, or package is a two-step process.

*

*You must define object types using the SQL statement CREATE TYPE, in SQL*Plus or other similar programs.
After an object type is defined and installed in the schema, you can use it in any PL/SQL block, subprogram, or package.

*In PL/SQL, you then declare a variable whose data type is the user-defined type or ADT that you just defined.

Так что, к сожалению, нет, создать объектные типы данных внутри пакета невозможно.

Свободные переводы ответа от участника @l0b0, обьединённого с ответом от участника @user272735


text:
Q: "No Artifacts" in Artifacts column after upgrading to new server with version 2017.2.1 I have setup a new server with Teamcity 2017.2.1 successfully. I have copied the artifacts folder over along with config and bin folder. I have successfully setup an agent and it is working great with Octopus Deploy 4.
The problem is that on my project overview page most of my projects have "no artifacts" indication. I can see the artifacts on the server(windows 2016) and also when I browse the Data Directory from the GUI but for some reason they are not mapping. I had also notices that I get this error in the server log :
jetbrains.buildServer.SERVER - JSP pre-compilation failed:

http://url/agentsList.jsp?jsp_precompile=true, error: java.net.ConnectException: Connection timed out: connect, will try again

Are the issues connected? How do I properly mount the artifacts?
I have already submitted a ticket with their forum but no reply yet.
Any help will be appreciated
Thank you

A: After 3 days in I managed to resolve this issue, the problem was created because I kept the restoration file in the Teamcity folder that Temcity automatically restore from. Therefore every time I restarted the Teamcity service my configuration would get wiped out and leave scorched land.
Hope this will help someone in the future. I definitely learned my lesson :)


text:
Q: Just installed ubuntu 14.04 but after restart it wont boot I used a live USB to install Ubuntu 14.04 and completely erase windows 8.1, the installation went fine but when I restarted the computer Ubuntu wouldn't boot from my HDD, instead it came up with try Ubuntu or install Ubuntu so I restarted without the live usb plugged in and I got an error message Reboot and select a proper boot device or insert boot media in selected boot device and press any key.
I read a lot of posts about people that had similar problems but so far none of the solutions that worked for them have worked for me.
I also ran boot-repair but that didn't fix the problem either.
Here is the link from boot-repair http://paste.ubuntu.com/7763898/
Please any help would be appreciated.
My laptop is a Toshiba Satellite U50D-A notebook with AMD A6-5200 processor

A: At the very top of boot repair info you posted it says you have two disks

*

*/dev/sda (apparently your hard drive)

*/dev/sdb (apparently your USB stick)

/dev/sda has an EFI boot partition and /dev/sdb has an MBR boot loader.
Check boot device
Boot your computer and go to BIOS by pressing one of:

*

*F1

*F2

*DEL

*ESC

*F10

And make sure you are booting from your hard disk.
Check EFI partition
According to
Ubuntu UEFI documentation, the EFI System partition should have a 'boot' flag. According to the boot repair info you posted, your partition does not have it.
To fix: boot from Live USB and run gparted. From there you can edit your partition table and add the 'boot' flag.

A: I had the same or a similar problem. Solution: When installing from the USB  select install alongside Ubuntu. I think I was actually reinstalling to the USB each time.
This worked for me after 3 days of reinstalling, changing boot options testdisk, and as many other things I could find.


text:
Q: How to display value from another Store in Grid cell? I have Cars grid which displays all my cars. It's bound to Cars store (which is bound to Car model).
Car model has brand_id field which points on certain Car brand.
So in the Grid I have numeric brand_id in my Brand column.
I have a store:
Ext.define('1.store.Brands', {

    extend: 'Ext.data.Store',
    fields: ['id', 'title'],
    data : [
        {'id':1, 'title':'AUDI'},
        {'id':2, 'title':'BMW'},
        {'id':3, 'title':'FIAT'}
    ]

});

How display real brand title instead of it's ID automatically pulling it from Brands store?

A: You can use your brands store in grid column renderer.
http://docs.sencha.com/ext-js/4-1/#!/api/Ext.grid.column.Column-cfg-renderer
{
    renderer: function(value){
        var rec = brandStore.findRecord('id', value);
        return rec.get("title");
    }
}


text:
Q: How to plot 3D maximum and minimum surfaces? I want to plot the maximum and minimum 3D surface for the following property:
Property[θ, ϕ, χ] := Module[{a, b},
  a = dirVector[θ, ϕ];
  b = dirVector2[θ, ϕ, χ]];

The following is a 2 parameter version of what I want:
SphericalPlot3D[Property[θ, ϕ], θ, ϕ, PlotRange -> All]

A: I am unsure what you are after, but I'll give it a try:
Given your vectors
dirVector[θ_, ϕ_] := {Sin[θ]*Cos[ϕ], Sin[θ]*Sin[ϕ], Cos[θ]};
dirVector2[θ_, ϕ_, χ_] := {Cos[θ]*Cos[ϕ]*Cos[χ]-Sin[ϕ]*Sin[χ],
                           Cos[θ]*Sin[ϕ]*Cos[χ]+Cos[ϕ]*Sin[χ],
                           -Sin[θ]*Cos[χ]};

only the second one has, when χ is varied, a minimum and maximum surface, with the minimum "surface" degenerating to a line at π/2, the maximum being the full sphere at 0 and π, respectively.
I plotted this with dirVector slightly scaled down so as to see the effects:

The plot was created using ParametricPlot3D:
Animate[Column[{"χ=" <> ToString@N@χ,
   ParametricPlot3D[{.9 dirVector[θ, ϕ],
     dirVector2[θ, ϕ, χ]}, {θ, 0,
     2 π}, {ϕ, 0, π}, PlotRange -> All, Boxed -> False,
    Axes -> False, PerformanceGoal -> "Quality", Mesh -> None,
    ImageSize -> Medium]}, Alignment -> Center], {χ,
  0, π, π/64}]


text:
Q: Update counter in Firebase with Angular Fire 2 I am building an app with Ionic 2 and AngularFire 2
I would like to update an object each time a user hits a "vote" button.
Updating a property with a fixed number is no problem with
  let userRate = 8
  this.currentBeer = this.af.database.object('/beers/' + scannedText);

  this.currentBeer.update({
    votes: 35,
    total: 642
  })

But I want to first get the current "votes" and "total" property, and then increment these values
I tried several options with .subscribe or .forEach methods, but I think the problem is in the async property of an observable?
Thanks a lot

A: I didn't know about the $ref possibilities...
Then you can use all the Firebase API
This code did the job for me :
  this.currentBeer = this.af.database.object('/beers/' + scannedText);

  this.currentBeer.$ref.once('value')
  .then(snapshot => {
      let obj = snapshot.val()
      this.currentBeer.update({
        total: obj.total + userRating,
        votes: obj.votes + 1
      })
  })


text:
Q: Network Interaction Problem I found this problem rather interesting, but I am not able to proceed.

Suppose a secondary school has $n$ classes with student number $a(1), a(2), \dots, a(n)$. One day, the school arranges for a picnic to increase the interaction among students. They have $m$ spots and they'd like to group students so that no more than $k$ students of the same class are seated at the same spot. For example, if $k=1$, there is at most one member form the same class at the spot. Is it possible to obtain a group arrangement that satisfies this requirement?

Kindly suggest me some way to proceed.

A: It's possible if $$k \ge \frac1m max \{ a(i) \}$$
That is, you find the class with the most students (call the number of students N) and they must be distributed at m spots, giving at least $\frac{N}{m}$ students per spot. If k is less than this number it cannot be done.


text:
Q: limit superior and inferior of measurable sets I am trying to prove the following:
Let $(A_n)_{n \geq 1}$ be a sequence of measurable sets, then
(i) $|\lim \inf_{n \to \infty} A_n| \leq \lim \inf_{n \to \infty} |A_n|$
(ii) If there is $n \in \mathbb N$, $|\bigcup_{k=n}^{\infty} A_k|< \infty$, then $|\lim_{n \to \infty} \sup A_n| \geq \lim_{n \to \infty} \sup |A_n|$.
I got stuck trying to show both inequalities.
In (i), on one hand we have
$$|\lim \inf_{n \to \infty} A_n|=|\bigcup_{n=1}^{\infty}\bigcap_{k=n}^{\infty}A_k|$$$$\leq \sum_{n=1}^{\infty} |\bigcap_{k=n}^{\infty}A_k|$$$$\leq\sum_{n=1}^{\infty}\sup_{k \leq n} |A_k|$$
In (ii), we have $$\lim_{n \to \infty} \sup |A_n|=\inf_{n \geq 0} \sup_{k \geq n}|A_k|$$$$\leq \sup_{k \geq n}|A_k| \space \forall n$$
I would appreciate some help where I got stuck, thanks in advance.

A: In your work for part $(i)$, the expression of the second line can be
$$\lim_{n\to \infty} \left|\bigcap_{k = n}^\infty A_k\right|$$
since the sequence $\{\cap_{k \ge n} A_k\}_{n = 1}^\infty$ increases to $\cup_{n\ge 1} \cap_{k\ge n} A_k$. Since, given $n$,
$$\bigcap_{k \ge n} A_k \subseteq A_m \quad \text{for all } \quad m \ge n,$$
we have
$$\left|\bigcap_{k \ge n} A_k\right| \le |A_m| \quad \text{for all}\quad m \ge n.$$
Hence
$$\left|\bigcap_{k\ge n} A_k\right| \le \inf_{m\ge n} |A_m|$$
for all $n\in \Bbb N$. Now
$$|\liminf_{n\to \infty} A_n| = \lim_{n\to \infty} \left|\bigcap_{k\ge n} A_k\right| \le \lim_{n\to \infty} \inf_{k\ge n} |A_k| = \liminf_{n\to \infty} |A_k|.$$
Part $(ii)$ follows from part $(i)$. Take $X = \cup_{n = 1}^\infty A_n$, and note $|X| < \infty$ since for some $N$, $|\cup_{n \ge N} A_n| < \infty$. Consider the sets $B_n = X\setminus A_n$, and use part $(i)$ to deduce $|\limsup A_n| \ge \limsup |A_n|$.


text:
Q: Fast search all triangles (3D space) that are intersected by a specified Z plane I have a complex 3D object all made of triangles(more than 1.000.000 triangles). I need to get (very fast) all triangles that are intersected by a specified Z plane.
For example there are 2 triangles
T1 = P1(0,0,0) P2(0,0,10) P3(0,10, 0)
T2 = P1(50,50,50) P2(50,50,60) P3(50,60,50)
Z plane = 3

in this example T1 is intersected by Z=3 , T2 not.
My big problem is to know what is the best structure tu use to store triangles (KD-Tree, AABB ...) and how to efficiently search only the triangles that have TZmin > Z > TZmax.
I have to do all in C# and I'm very new to this type of 3D problems.
Every help is very appreciated.
By GMG


text:
Q: can't set path for javac I've put in an embarrassing amount of time reading threads here and elsewhere, I cannot compile HelloWorldApp.java
Using Windows 7
the location of the script is C:\Users\Phil\Desktop
the location of javac is C:\Program Files\Java\jdk1.8.0_77\bin
In Environment Variables, in both User and System Variables, I have clicked NEW, and given the "Variable Name" as javac and "Variable Value" as `

C:\Program Files\Java\jdk1.8.0_77\bin;

`
I have tried to make this work based on the 2 different ways here (to no avail): https://docs.oracle.com/javase/tutorial/getStarted/problems/
I am failing to set a path, or tell computer where to find it from within cmd.  What am I doing wrong?

A: just you have to do set temporary path set path=C:\Program Files\Java\jdk1.7.0_45;
or
change your Environment variable path
to
variable name=%path%
variable value:\Program Files\Java\jdk1.7.0_45;
then open cmd and run javac command to check

A: Okay, so I have solved my problem:
In Environment Variables, the "Variable Name" must be: PATH
The Variable value is: C:\Program Files\Java\jdk1.8.0_77\bin
Now It works!


text:
Q: Possible consequences of duplicate ProgId for different classes In a software I'm maintaining I've observed COM classes marked with identical [ProgId]s.
AFAIK the ProgId is a human readable identifier for a component and it should map 1-to-1 with the component's CLSID.
So I'm wondering:

*

*Is there any good reason to have the same ProgId for different classes?

*What are the possible consequences? (except not being able to reach a component using this convenient way)
Thanks in advance.

A: A ProgId provides a friendly name for the CLSID guid of a coclass.  Important to scripting languages, no good way to know the guid.  Also used by languages that support late binding, like VB.NET and C#.  The conversion from the string to the guid happens at runtime.  The usual name of the factory function is CreateObject(), the language runtime implements it by looking at the registry entry stored in HKLM\Software\Classes.
Which is your cue to what will go wrong when you duplicate them.  The actual object the client program creates is random.  Whichever one happened to be registered last.  The client program calls a completely different method from the one it intended to call.  This might trigger a DISP_E_Xxxx error return but that's certainly no guarantee.  In general a very nasty and quite undebuggable mishap.
The only way you can not have this problem is when the client code uses early binding and uses the type library to know the guids.  That's not unusual but it is not in your control.  If you know that the client code doesn't use them then simply omit the [ProgId] attribute so no accidents can happen.


text:
Q: How do i add userextension js file to Selenium IDE 3.4.4 Older versions of Selenium IDE allowed users to add a .js file to the "Selenium Core extensions (user-extensions.js)" field on the "General" tab of the "Selenium IDE Options" dialog. Selenium IDE 3.4.4 doesn't display an Options menu. I've tried Alt+O and Ctrl+O and neither one displays the menu. How would I go about getting my custom extensions to appear in the Command drop down of
Selenium IDE 3.4.4?


text:
Q: Compass gem throwing error I'm trying to get started with Compass & Sass. I've installed the compass gem with three versions of ruby (1.9.1, 1.9.2, 1.9.3) and each time I get the same error:
martin@crunchbang:~$ compass
/home/martin/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.3/lib/bundler/shared_helpers.rb:22:in `default_gemfile': Could not locate Gemfile (Bundler::GemfileNotFound)
    from /home/martin/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.3/lib/bundler.rb:213:in `default_gemfile'
    from /home/martin/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.3/lib/bundler.rb:164:in `root'
    from /home/martin/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.3/lib/bundler.rb:123:in `load'
    from /home/martin/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.3/lib/bundler.rb:114:in `setup'
    from /home/martin/.rvm/gems/ruby-1.9.3-p194@global/gems/bundler-1.1.3/lib/bundler.rb:119:in `require'
    from /home/martin/.rvm/gems/ruby-1.9.3-p194/gems/compass-0.12.1/bin/compass:25:in `<top (required)>'
    from /home/martin/.rvm/gems/ruby-1.9.3-p194/bin/compass:19:in `load'
    from /home/martin/.rvm/gems/ruby-1.9.3-p194/bin/compass:19:in `<main>'
    from /home/martin/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper:14:in `eval'
    from /home/martin/.rvm/gems/ruby-1.9.3-p194/bin/ruby_noexec_wrapper:14:in `<main>'

How can I resolve this issue?
Any help is much appreciated.

A: I've found the answer here, there seems to be some sort of issue with the compass gem and the new version of bundler.
To resolve just run:
rubygems-bundler-uninstaller


text:
Q: How should I correctly handle exceptions in Python3 I can't understand what sort of exceptions I should handle 'here and now', and what sort of exceptions I should re-raise or just don't handle here, and what to do with them later (on higher tier). For example: I wrote client/server application using python3 with ssl communication. Client is supposed to verify files on any differences on them, and if diff exists then it should send this 'updated' file to server.

class BasicConnection:
    #blablabla
    def sendMessage(self, sock, url, port, fileToSend, buffSize):
        try:
            sock.connect((url, port))
            while True:
                data = fileToSend.read(buffSize)
                if not data: break
                sock.send(data)
            return True
        except socket.timeout as toErr:
            raise ConnectionError("TimeOutError trying to send File to remote socket: %s:%d"
                                  % (url,port)) from toErr
        except socket.error as sErr:
            raise ConnectionError("Error trying to send File to remote socket: %s:%d"
                                  % (url,port)) from sErr
        except ssl.SSLError as sslErr:
            raise ConnectionError("SSLError trying to send File to remote socket: %s:%d"
                                  % (url,port)) from sslErr
        finally:
            sock.close()

Is it right way to use exceptions in python? The problem is: what if file.read() throws IOError? Should I handle it here, or just do nothing and catch it later? And many other possible exceptions?

*

*Client use this class (BasicConnection) to send updated files to server:

class PClient():
    def __init__(self, DATA):
        '''DATA = { 'sendTo'      : {'host':'','port':''},
                    'use_ssl'     : {'use_ssl':'', 'fileKey':'', 'fileCert':'', 'fileCaCert':''},
                    'dirToCheck'  : '',
                    'localStorage': '',
                    'timeToCheck' : '',
                    'buffSize'    : '',
                    'logFile'     : ''}   '''
        self._DATA = DATA
        self._running = False
        self.configureLogging()

    def configureLogging(self):
        #blablabla

    def isRun(self):
        return self._running

    def initPClient(self):
        try:
            #blablabla

            return True
        except ConnectionError as conErr:
            self._mainLogger.exception(conErr)
            return False
        except FileCheckingError as fcErr:
            self._mainLogger.exception(fcErr)
            return False
        except IOError as ioErr:
            self._mainLogger.exception(ioErr)
            return False
        except OSError as osErr:
            self._mainLogger.exception(osErr)
            return False

    def startPClient(self):
        try:
            self._running = True
            while self.isRun():
                try :
                    self._mainLogger.debug("Checking differences")
                    diffFiles = FileChecker().checkDictionary(self._dict)

                    if len(diffFiles) != 0:
                        for fileName in diffFiles:
                            try:
                                self._mainLogger.info("Sending updated file: %s to remote socket: %s:%d"
                                    % (fileName,self._DATA['sendTo']['host'],self._DATA['sendTo']['port']))
                                fileToSend = io.open(fileName, "rb")
                                result = False
                                result = BasicConnection().sendMessage(self._sock, self._DATA['sendTo']['host'],
                                                                       self._DATA['sendTo']['port'], fileToSend, self._DATA['buffSize'])
                                if result:
                                    self._mainLogger.info("Updated file: %s was successfully delivered  to remote socket: %s:%d"
                                    % (fileName,self._DATA['sendTo']['host'],self._DATA['sendTo']['port']))
                            except ConnectionError as conErr:
                                self._mainLogger.exception(conErr)
                            except IOError as ioErr:
                                self._mainLogger.exception(ioErr)
                            except OSError as osErr:
                                self._mainLogger.exception(osErr)

                        self._mainLogger.debug("Updating localStorage %s from %s " %(self._DATA['localStorage'], self._DATA['dirToCheck']))
                        FileChecker().updateLocalStorage(self._DATA['dirToCheck'],
                                                         self._DATA['localStorage'])
                    self._mainLogger.info("Directory %s were checked" %(self._DATA['dirToCheck']))
                    time.sleep(self._DATA['timeToCheck'])
                except FileCheckingError as fcErr:
                    self._mainLogger.exception(fcErr)
                except IOError as ioErr:
                    self._mainLogger.exception(ioErr)
                except OSError as osErr:
                    self._mainLogger.exception(osErr)
        except KeyboardInterrupt:
            self._mainLogger.info("Shutting down...")
            self.stopPClient()
        except Exception as exc:
            self._mainLogger.exception(exc)
            self.stopPClient()
            raise RuntimeError("Something goes wrong...") from exc

    def stopPClient(self):
        self._running = False

Is it correct? May be someone spend his own time and just help me to understand pythonic style of handling exceptions? I can't understand what to do with such exceptions as NameError, TypeError, KeyError, ValueError...and so on.......They could be thrown at any statement, at any time... and what to do with them, if I want to logged everything.

*And what information should people usually log? If error occurs, what info about it I should log? All traceback, or just relevant message about it or something else?

*I hope somebody helps me.
Thanks a lot.

A: To start with, you don't need any _mainLogger.
If you want to catch any exceptions, maybe to log or send them by email or whatever, do that at the highest possible level -- certainly not inside this class.
Also, you definitely don't want to convert every Exception to a RuntimeError. Let it emerge. The stopClient() method has no purpose right now. When it has, we'll look at it..
You could basically wrap the ConnectionError, IOError and OSError together (like, re-raise as something else), but not much more than that...

A: In general, you should "catch" the exceptions that you expect to happen (because they may be caused by user error, or other environmental problems outside of your program's control), especially if you know what your code might be able to do about them.  Just giving more details in an error report is a marginal issue, though some programs' specs may require doing that (e.g. a long-running server that's not supposed to crash due to such problems, but rather log a lot of state information, give the user a summary explanation, and just keep working for future queries).
NameError, TypeError, KeyError, ValueError, SyntaxError, AttributeError, and so on,  can be thought of as due to errors in the program -- bugs, not problems outside of the programmer's control.  If you're releasing a library or framework, so that your code is going to be called by other code outside of your control, then such bugs may quite likely be in that other code; you should normally let the exception propagate to help the other programmer debug their own bugs.  If you're releasing an application, you own the bugs, and you must pick the strategy that helps you find them.
If your bugs show up while an end-user is running the program, you should log a lot of state information, and give the user a summary explanation and apologies (perhaps with a request to send you the log info, if you can't automate that -- or, at least, ask permission before you send anything from the user's machine to yours).  You may be able to save some of the user's work so far, but often (in a program that's known to be buggy) that may not work anyway.
Most bugs should show up during your own testing of course; in that case, propagating the exception is useful as you can hook it up to a debugger and explore the bug's details.
Sometimes some exceptions like these show up just because "it's easier to ask forgiveness than permission" (EAFP) -- a perfectly acceptable programming technique in Python.  In that case of course you should handle them at once.  For example:
try:
    return mylist[theindex]
except IndexError:
    return None

here you might expect that theindex is generally a valid index into mylist, but occasionally outside of mylist's bounds -- and the latter case, by the semantics of the hypothetic app in which this snippet belongs, is not an error, just a little anomaly to be fixed by considering the list to be conceptually extended on both sides with infinite numbers of Nones.  It's easier to just try/except than to properly check for positive and negative values of the index (and faster, if being out of bounds is a truly rare occurrence).
Similarly appropriate cases for KeyError and AttributeError happen less frequently, thanks to the getattr builtin and get method of dicts (which let you provide a default value), collections.defaultdict, etc; but lists have no direct equivalent of those, so the try/except is seen more frequently for IndexError.
Trying to catch syntax errors, type errors, value errors, name errors, etc, is a bit rarer and more controversial -- though it would surely be appropriate if the error was diagnosed in a "plug-in", third-party code outside your control which your framework/application is trying to load and execute dynamically (indeed that's the case where you're supplying a library or the like and need to coexist peacefully with code out of your control which might well be buggy).  Type and value errors may sometimes occur within an EAFP pattern -- e.g. when you try to overload a function to accept either a string or a number and behave slightly differently in each case, catching such errors may be better than trying to check types -- but the very concept of functions thus overloaded is more often than not quite dubious.
Back to "user and environmental errors", users will inevitably make mistakes when they give you input, indicate a filename that's not actually around (or that you don't have permission to read, or to write if that's what you're supposed to be doing), and so on: all such errors should of course be caught and result in a clear explanation to the user about what's gone wrong, and another chance to get the input right.  Networks sometime go down, databases or other external servers may not respond as expected, and so forth -- sometimes it's worth catching such problems and retrying (maybe after a little wait -- maybe with an indication to the user about what's wrong, e.g. they may have accidentally unplugged a cable and you want to give them a chance to fix things and tell you when to try again), sometimes (especially in unattended long-running programs) there's nothing much you can do except an ordered shutdown (and detailed logging of every possibly-relevant aspect of the environment).
So, in brief, the answer to your Q's title is, "it depends";-).  I hope I have been of use in listing many of the situations and aspects on which it can depend, and recommending what's generally the most useful attitude to take towards such issues.


text:
Q: jquery + Scrolling + Check what element is visible I would like to know if its possible with jQuery to do the following:
http://jsfiddle.net/AzFJR/2/
-check which ".main" is visible at the moment and dynamically add ".active" to the corresponding link in the "nav" ?
Regards!
Edit:
I have worked it out using this Viewport Plugin and following code:
//find what element is in view
var inview = '#' + $('.sectionSelector:in-viewport:first').attr('id'),

//find the corresponding link
$link = $('.mainNav li a').filter('[hash=' + inview + ']');

//check i its already active or not and if not
if ($link.length && !$link.is('.active')) {

    //remove all previous active links and make the current one active
    $('.mainNav li a').removeClass('active');
    $link.addClass('active');

}

//Start same proccess on every scroll event again
$(window).scroll(function () {
    var inview = '#' + $('.sectionSelector:in-viewport:first').attr('id'),
    $link = $('.mainNav li a').filter('[hash=' + inview + ']');
    if ($link.length && !$link.is('.active')) {
        $('.mainNav li a').removeClass('active');
        $link.addClass('active');
    }
});

Thanks every1 for the help!

A: Use the jQuery ELEMENT 'INVIEW' EVENT plugin.
$('div').bind('inview', function(event, isInView, visiblePartX, visiblePartY) {
  if (isInView) {
    // find link and addClass '.active'
  } else {
    // remove the class
  }
});

A: The scrollTo plugin should do the trick http://flesler.blogspot.com/2007/10/jqueryscrollto.html


text:
Q: terraform import fargate cluster I have an existing manually created fargate cluster named "test-cluster" in us-west-1
In terraform configuration file i created
resource "aws_ecs_cluster" "mycluster" {

}

I run terraform command to import the files
terraform import aws_ecs_cluster.mycluster test-cluster

I receive this error message
Error: Cannot import non-existent remote object
While attempting to import an existing object to aws_ecs_cluster.cluster, the
provider detected that no object exists with the given id. Only pre-existing
objects can be imported; check that the id is correct and that it is
associated with the provider's configured region or endpoint, or use
"terraform apply" to create a new remote object for this resource.
I've also ran aws configure adding the correct region.

A: Based on the comments.
The issue was caused by using wrong account in terraform and/or AWS console.
The solution was to use correct account.


text:
Q: Wait until MongoDB has completed its query without using callbacks I have an issue with the asynchrous programming model in Node.js.
I know this has been asked before, but so far I haven't found anything that I can use to solve my issue.
How do I force console.log from running before dbQueryName has been invoked and username has gotten its value from it?
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

function dbQueryName() {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("mydb");

        dbo.collection("users").findOne({}, function(err, result) {
            if (err) throw err;

            return result.name
            db.close();
        });
    });
}

var username = dbQueryName();

// Wait until dbQueryName() has been invoked and username has gotten its value before running this
console.log(username);

I have managed to get it working using a callback parameter in the function, but is there a way to do this with less code and indentation?
function dbQueryName(callback) {
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
        var dbo = db.db("mydb");

        dbo.collection("users").findOne({}, function(err, result) {
            if (err) throw err;

            callback(result.name)
            db.close();
        });
    });
}

dbQuery(function(result){
    var username = result
    console.log(username);
});

A: Yes if you are not passing a callback to MongoClient.connect or collection.findOne, it returns a promise.
But you need to add another function to use async await
init()

async function dbQueryName() {
    const db = await MongoClient.connect(url);
    const dbo = db.db("mydb");

    const user = await dbo.collection("users").findOne({})
    return user.name
}
async function init() {
    try {
        const name = await dbQueryName()
    } catch (error) {
        console.log(error);
    }
}


text:
Q: ant design custom Form List: How to handle Array inside an array The data I receive from the backend looks something like this:
 const pronounsExample = [
  [
    {
      id: '62f51edbbd529a9306052013',
      title: 'He / Him / His',
    },
  ],
  [
    {
      id: '62f51ef8bd529a9306052014',
      title: 'She / Her / Her',
    },
  ],
]

I use Form.List whenever I have an array of objects but the above value is different, because it is array inside an array and then an object inside, I would like to build a form Item so that users can manipulate these values and the Form should return the requred data in the above format:
Here is what I use when I have an Array of Objects:
 <Form.List name="pronouns" initialValue={data?.pronouns}>
        {(fields, { add, remove }) => {
          console.log('List Fields', fields)
          return (
            <div>
              <Row gutter={[16, 16]} justify="end">
                <Col>
                  <Button onClick={() => add()} className="mb-2">
                    <PlusOutlined /> {messages.buttons.add}
                  </Button>
                </Col>
              </Row>
              {fields.map((field) => (
                <Row key={field.key} gutter={[16, 16]}>
                  <Form.Item name={[field.name, 'id']} hidden>
                    <Input />
                  </Form.Item>
                  <Col flex={1}>
                    <Form.Item name={[field.name, 'nameTranslate']}>
                      <Input />
                    </Form.Item>
                  </Col>
                  <Col>
                    <Button
                      type="danger"
                      onClick={() => remove(field.name)}
                      disabled={fields.length === 0}
                      icon={<DeleteOutlined />}
                    />
                  </Col>
                </Row>
              ))}
            </div>
          )
        }}
      </Form.List>

helpful links:
https://ant.design/components/form/#Form.List

A: Let's say, I guess your problem is converting an array of arrays of objects to an array of object, right?
If yes, my solution is:
let filteredArray = [];
for (let i = 0; i < pronounsExample.length; i++){
       filterdArray.push([...pronounsExample[i]])
    }

So, initialValues = filteredArray[0]


text:
Q: TortoiseSVN - Repository on localhost, then working copies on localhost and online. Possible? I am attempting to use tortoiseSVN to solve a small problem which I am having.
I have a development laptop, and develop the majority of my websites on it.
If however I am on the move, and someone sends me an SMS reporting a bug for example, I often login to my ftp on any computer there an then, and fix the website 'live' per se.
If i then make an additional change on my development laptop, I often forget about the live change that I have made, and as a result lose it.
As such, I am looking to use tortoiseSVN to alleviate this problem.
My hosting account is a shared hosting account with hostgator which does NOT support SVN repositorys.
Am I correct to think that the way SVN works is that my 'live' copy MUST be the repository? Or am I missing the point?
Could someone explain how I would go about achieving what I want, even if it requires a hosting change.. or perhaps an alternative which suits my situation better..?
Many Thanks.
Tom

A: I'm not sure about what you mean by "live" copy, but here is how you work with SVN.
First you have a svn server, this can be on your laptop, but should preferably be on separate with automated backups etc.
Then on your local machine you have the working copy. The working copy is a mostly a clone of the content on the server, but with your local modifications. When you are satisfied with your local modifications you commit (submit) the changes to the server. If you are not satisfied with your local changes you can easily revert to the version on the server (or an older version).
To get things to your production environment has nothing to do with svn. This is called a deployment process or release process. A deployment process typically compiles, backs an installer or collects files to be installed and finally installs/copies the result to your production environment.
The "master" copy of your application/web site should be on the svn server. To get something into production you run a script or follow a manual procedure to get the content from a working copy to the production.
By using an svn server as the master copy instead of your laptop you don't solve the problem of missing updates when you "cheat" by editing files directly in your production environment. But if you have remote shell access (ssh) you can have a local working copy on the production server, edit stuff in the working copy and check them in by command line svn tools.
Edit
To clarify: your "live" copy should absolutely not be the repository. The repository is not structured like a regular file tree with regular files in it. More like a sequence of changesets.
Your "live" copy should preferably not be a working copy either. The working copy contains special folders and files to keep track of "stuff" that you don't want on your public web site. Your live copy should be a copy of relevant files in a working copy. Either with copy *.html /www-folder/ or svn export or some more elaborate method.

A: One of the best answer is to use a distributed versioning system where your web-site is a mirror branch or directly the repository (or working copy, it's the same in DVCS).
So you benefit directly from your version control !
You can use Bazaar, Git or mercurial to do so, (or any other DVCS, it's just the major ones).


text:
Q: JQL for this condition how would the JQL look like for this condition?:
Generate a report of all HIGH severity JIRA tickets for a project with key X (or name X) that were created from 9 PM EST to 12 AM EST from the start of the year?
I tried something like :
Project = X AND Severity = "HIGH" AND created > "2015/01/01 21:00" and created < "2015/09/09",

but I need only those issues that are created between 9 PM and 12 AM everyday, from the beginning of the year.
Any ideas would be greatly appreciated.

A: Unfortunately there seems to be no tool to get the hour from created date but you can workaround it.
My two ideas are:

*

*find these tickets directly on Jira database (if you have access) it should be very easy since there are functions like hour (mySQL) or truncate (postgres)

*prepare JQL filter using some generator script - it is definetely less comfortable but possible to achieve even when you have not acces to database. The worst thing is that Jira filter fields accepts only 2000 characters string so you would need to copy that filter few lines by few lines.
Little crazy but ok - it works so what's the idea? The idea is to use startOfYear() JQL function and its *offset version**. For example:
created >= startOfYear(21h) and created < startOfYear(24h)

will give you all tickets from 1 Jan 21:00 - 2 Jan 00:00
then you can use this Python script:
step = 27
maxDay = 1

while maxDay <= 365 + step:
    maxDay += step

    output = "project = X and Severity = HIGH and ("

    for i in range(maxDay-step, maxDay):
        output += " (created >= startOfYear(" + str( ( (i-1) * 24 ) + 21) + "h) and created < startOfYear(" + str(i*24) + "h)) or"

    output = output[:-3]
    output += ")"

    print output
    print

which will generate you set of JQL requests to copy-paste and execute (it is actually 15 of them - you can see here). Every set bounds 28 days because of 2000 limit of filter input in Jira.

A: I fixed this issue by writing a custom JQL function and then using that function with a JQL query, which fits well with our requirements :
created >= "2015-01-01" and created <= "2015-12-31" and issue in getIssuesForTimeRange("21", "24")


text:
Q: Why isn't this SQLite example working on my computer? I have been trying out the pre-release of 2022 Visual Studio. One of the new features is the ability to fully manipulate SQLite databases in a browser. I have downloaded this example from GitHub, but I am getting errors talking about missing dlls. (In particular, sqlite3.) Said dlls are included in the project.
What I have installed:
Version 17.2.0 Preview 3.0
VisualStudio.17.Preview/17.2.0-pre.3.0+32408.312
Microsoft .NET Framework
Version 4.8.04161

Installed Version: Community

.NET Core Debugging with WSL   1.0
.NET Core Debugging with WSL

ADL Tools Service Provider   1.0
This package contains services used by Data Lake tools

ASA Service Provider   1.0

ASP.NET and Web Tools 2019   17.2.374.58081
ASP.NET and Web Tools 2019

Azure App Service Tools v3.0.0   17.2.374.58081
Azure App Service Tools v3.0.0

Azure Data Lake Tools for Visual Studio   2.6.5000.0
Microsoft Azure Data Lake Tools for Visual Studio

Azure Functions and Web Jobs Tools   17.2.374.58081
Azure Functions and Web Jobs Tools

Azure Stream Analytics Tools for Visual Studio   2.6.5000.0
Microsoft Azure Stream Analytics Tools for Visual Studio

C# Tools   4.2.0-3.22205.5+0167599e0e1634ea3ed8d0e41390a3c0d9b3e4e9
C# components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Common Azure Tools   1.10
Provides common services for use by Azure Mobile Services and Microsoft Azure Tools.

Extensibility Message Bus   1.2.6 (master@34d6af2)
Provides common messaging-based MEF services for loosely coupled Visual Studio extension components communication and integration.

Microsoft Azure Hive Query Language Service   2.6.5000.0
Language service for Hive query

Microsoft Azure Stream Analytics Language Service   2.6.5000.0
Language service for Azure Stream Analytics

Microsoft JVM Debugger   1.0
Provides support for connecting the Visual Studio debugger to JDWP compatible Java Virtual Machines

Mono Debugging for Visual Studio   17.2.18 (c6a6269)
Support for debugging Mono processes with Visual Studio.

NuGet Package Manager   6.2.0
NuGet Package Manager in Visual Studio. For more information about NuGet, visit https://docs.nuget.org/

Razor (ASP.NET Core)   17.0.0.2218101+885a343b00bcab620a90c1550c37dafd730ce984
Provides languages services for ASP.NET Core Razor.

SQL Server Data Tools   17.0.62204.01010
Microsoft SQL Server Data Tools

ToolWindowHostedEditor   1.0
Hosting json editor into a tool window

TypeScript Tools   17.0.10330.2001
TypeScript Tools for Microsoft Visual Studio

Visual Basic Tools   4.2.0-3.22205.5+0167599e0e1634ea3ed8d0e41390a3c0d9b3e4e9
Visual Basic components used in the IDE. Depending on your project type and settings, a different version of the compiler may be used.

Visual F# Tools   17.1.0-beta.22178.3+6da0245a7ce4bb8483b8d1f2993c8ecaea967ad9
Microsoft Visual F# Tools

Visual Studio IntelliCode   2.2
AI-assisted development for Visual Studio.

VisualStudio.DeviceLog   1.0
Information about my package

VisualStudio.Mac   1.0
Mac Extension for Visual Studio

VSPackage Extension   1.0
VSPackage Visual Studio Extension Detailed Info

Xamarin   17.2.0.145 (main@33e358f)
Visual Studio extension to enable development for Xamarin.iOS and Xamarin.Android.

Xamarin Designer   17.2.0.242 (remotes/origin/main@08c837845)
Visual Studio extension to enable Xamarin Designer tools in Visual Studio.

Xamarin Templates   17.2.15 (2e3b60e)
Templates for building iOS, Android, and Windows apps with Xamarin and Xamarin.Forms.

Xamarin.Android SDK   12.3.0.3 (d17-2/bbba5a2)
Xamarin.Android Reference Assemblies and MSBuild support.
    Mono: adf1bc4
    Java.Interop: xamarin/java.interop/d17-2@9760f0a9
    ProGuard: Guardsquare/proguard/v7.0.1@912d149
    SQLite: xamarin/sqlite/3.38.2@7b1e016
    Xamarin.Android Tools: xamarin/xamarin-android-tools/d17-2@fc3c2ac

Xamarin.iOS and Xamarin.Mac SDK   15.9.0.100 (cf971a68e)
Xamarin.iOS and Xamarin.Mac Reference Assemblies and MSBuild support.

Error message in browser console:
blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: The type initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception.
System.TypeInitializationException: The type initializer for 'Microsoft.Data.Sqlite.SqliteConnection' threw an exception.
 ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
 ---> System.DllNotFoundException: e_sqlite3
   at SQLitePCL.SQLite3Provider_e_sqlite3.SQLitePCL.ISQLite3Provider.sqlite3_libversion_number()
   at SQLitePCL.raw.SetProvider(ISQLite3Provider imp)
   at SQLitePCL.Batteries_V2.Init()
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   --- End of inner exception stack trace ---
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.MethodBase.Invoke(Object obj, Object[] parameters)
   at Microsoft.Data.Sqlite.Utilities.BundleInitializer.Initialize()
   at Microsoft.Data.Sqlite.SqliteConnection..cctor()
   --- End of inner exception stack trace ---
   at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteRelationalConnection.CreateDbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.get_DbConnection()
   at Microsoft.EntityFrameworkCore.Storage.RelationalConnection.Open(Boolean errorsExpected)
   at Microsoft.EntityFrameworkCore.Sqlite.Storage.Internal.SqliteDatabaseCreator.Exists()
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.ExistsAsync(CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreatedAsync(CancellationToken cancellationToken)
   at Microsoft.EntityFrameworkCore.Storage.RelationalDatabaseCreator.EnsureCreatedAsync(CancellationToken cancellationToken)
   at BlazorSQLiteWasm.Pages.Demo.OnInitializedAsync() in C:\Users\Yuen Winston\source\repos\BlazorSQLiteWasm\Pages\Demo.razor.cs:line 38
   at BlazorSQLiteWasm.Pages.Demo.OnInitializedAsync() in C:\Users\Yuen Winston\source\repos\BlazorSQLiteWasm\Pages\Demo.razor.cs:line 56
   at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync()
   at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask(Task taskToHandle, ComponentState owningComponentState)

I have already tried running dotnet workload install wasm-tools because I saw it as a solution to a similar question.


text:
Q: Why to use Querydsl? I am new to JPA, JPQL, Hibernate, Querydsl and now I saw that in my project is used Querydsl for querying and I am wondering why this approach has been chosen. So you can be for sure why exactly is in my project but you can tell why and in what situations Querydsl is preferred. Why we can use simple JPQL statements?

A: I would like to make a counterpoint to the QueryDSL usage.
I don't like to use QueryDSL for the follow reasons:

*

*You need to compile the project frequently to maintain the Q classes updated

*You need to setup the IDE to consider the Q classes generated on target as normal classes.

*I have already seen the IDE "get lost" and no longer recognize the Q classes

*I already create simple QueryDSL statements that generated really weird and not predictable SQLs.

Even being friendly for final users, I prefer to use JPQL because it's closer to the generated SQL and more predictable.
But compared to Criteria, I prefer QueryDSL.

A: *

*You can use code completion in IDE

*IDE refactoring tools work (more-or-less)

*type-safe

*(almost)syntax-safe

*compiler generates errors on compile time of wrong types etc vs Hibernate complains just on first run

*Consistency, you can use same principles to query JPA, MongoDB, Collections...


text:
Q: Copy constructor and returning by value I'm learning about return value optimization and copy elision in C++ and wrote a test vector class to experiment with it in which I allocate memory for an integer array in the constructor:

    //Constructor:
    Vector::Vector(int s): elem{new double[s]}, sz{s} {std::cout << "Constructor called"<<std::endl;}

    //Destructor:
    Vector::~Vector(){
        delete[] elem;
        std::cout << "Destructor is called" << std::endl;
    }

    double& Vector::operator[](int i){ return elem[i];}

    //Move constructor:
    Vector::Vector(Vector&& v): elem{v.elem}, sz{v.sz}
    {
    std::cout << "Move constructor is called" << std::endl;
        v.elem = nullptr;
        v.sz=0;
    }

    //Copy constructor:
    Vector::Vector(Vector& v): elem{v.elem }, sz{v.sz}
    {
    std::cout << "Copy constructor is called" << std::endl;
    }

In a main file I write a function in which I create a vector from an integer array and return it by value:

    Vector make(int s,int array[]){

    Vector v(s);

    for(int i =0; i<s; i++){
    v[i] = array[i];
    }

    return v;
    }

I call this in the main function as follows:

    int main(){

    int a[] = {1,2,3,4};

    Vector v = make(4,a);

    return 0;
    }

When I then use the compiler option -fno-elide-constructors
the move constructor gets called when returning from function. If I get what is written in this post: move constructor called on return instead of copy, the first thing the compiler tries to do is to use the move constructor and when this is not available it uses the copy constructor. So I thought that if I deleted the move constructor:
  Vector(Vector&&)=delete;

the copy constructor would be used as a last resort. If I do this however, the compiler complains that
error: use of deleted function 'Vector::Vector(Vector&&)'

Vector v = make(4,a);

I wonder if someone can explain to me what is going on here? I know it's probably what I would want to do, but is it possible to make the copy constructor being called when returning the object from the function?

A: copy constructor should have a const parameter :
Vector::Vector(const Vector& v)

without it cannot accept a rvalue than make return


text:
Q: Getting request parameters on html page called through RequestDispatcher I've been having some problem managing a homework task and got stumped looking for an answer online too.
I have a website built using HTML and using Javascript and jQuery to update dynamically given data from a server using Java and Jersey for servlets.
One of the HTML pages I have is "create_card.html", it lets the user assign values and send a post request to the servlet, which adds a new card to the database, and sends a forward request to the page "buy_card.html" with the created card's ID as a request parameter as:
RequestDispatcher dispatcher = request.getRequestDispatcher("/buy_card.html?card_id="+cardID.ToString());
dispatcher.forward(request, response);

All this works fine, and the parameter is passed correctly(I'll get back to this in a bit), but I'm having trouble finding a way to read it.
The assignment limited us to only using html pages and not jsp(On jsp it's easy to get the parameter and is how I know it's passed correctly), but on html, I have to use JS or jQuery to read it somehow, but since I'm using the request dispatcher, the url of the page doesn't change and window.location gives me the address of the previous page, so I can't access the parameters through the URL.
I can't change way this works either since the assignment requires us to make the site as a Single Page Application.
So I'm looking for any ideas on another way to pull the parameter from forwarded page, not using JSP.
Does anyone know of a way?
Thanks in advance.
EDIT:
So after some more digging around, I found this:
How to read the post request parameters using javascript

A: So, after a few more days of looking and finding nothing, I gave up and went for a hack.
Instead of passing parameters to my form, I instead save them as cookies sent with the response.
It's ugly, but I suppose it works =/


text:
Q: Why can't I create a Windows backup on my secondary disk? I've installed Windows 7 Ultimate on an SSD that I've added to the XPS desktop that I bought from Dell. I would like to use the built-in backup functionality to create incremental backups and store them on the large drive that came with the machine.  I formatted the large drive and turned it into a Basic disk.
However, when I try to set the backup location to the large internal disk (E:\) in the "Set up backup" wizard, a get a message saying, "A system image cannot be saved on a drive that your computer boots from or that Windows is installed on."
Windows is not installed on that disk.  I even deleted the OEM partition that was on the disk, and removed it completely from the boot order in the BIOS.
Any clue why Windows is griping at me about this?

A: Your system drive does not have to be the same drive as windows is installed on. So it would look like your machine is starting off the harddrive (which tells it to continue booting off the SSD)
Try reading this following article which describes (better than I can) a similar problem and a resolution.


text:
Q: What is the purpose of Apache2's configuration files? Why does Apache2 have multiple configuration files? What are their roles? I found some information about older Apache versions, but it's usually deprecated, and the official Apache documentation doesn't explain the logic of splitting up the configuration files and what they're for.

A: Hmm. From one point of view, you can dump all the configuration into one httpd.conf file, but this would be... hard to read.
Most distros will divide up the configuration by having httpd.conf include subdirectories.  You may want to look at distro-specific documentation, for example:
https://help.ubuntu.com/12.04/serverguide/httpd.html
For Ubuntu, the Apache configuration directory is /etc/apache2.  The primary subdirectories for your organizational convenience are conf.d, mods-available, mods-enabled, sites-available and sites-enabled.  You would keep your module configuration in the mods-available directory, and your virtualhost configurations in the sites-available directory.  Note that the *-enabled directories contain symlinks to the corresponding *-available directories, so you can keep a bunch of things floating around in *-available, but only activate them by symlinking from the *-enabled directory.  The master httpd.conf file will do an include of what's in the *-enabled directories.
RHEL/CentOS doesn't work that way, and leave it somewhat more up to your discretion on how to set up the /etc/httpd base directory.  You can dump everything into /etc/httpd.conf; you can create a similar directory structure to Ubuntu (and modify httpd.conf to include the *-available directories that you've made), or some combination thereof.
So, you may want to check your distro's documentation first.  As you'll see with the Ubuntu one, they provide links to other resources.


text:
Q: Arrival-time handling with wrap around in C I´m currently writing a software in Ansi-C and are struggling to get one of the basic functionality to work.
The software will receive messages over a CAN-network and when these messages arrive, I need to make sure that they are delivered before a expected time and after the previous message.
Only unsigned variables are allowed to be used, so there will be problems with wrap around when the timers reach their maximum value (255 in my case).
It is easy to verify that messages arrive before the expected time, since I know the maximum time between two messages.
This example handles wrap around and discovers messages that are late:
UC_8 arrival = 250;
UC_8 expected = 15;
UC_8 maxInterArrTime = 30;

result = expected - arrival;

if(result <= maxInterArrTime){
// ON TIME!
}
else{
// DELAYED
}

This is the easy part, but I must also check that the arrived message actually have arrived after the previous message. My problem is that I do not know how to solve this with the wrap around problem. I tried to mimic the solution that finds delayed messages, but without any luck.
UC_8 arrival = 10; // Wrapped around
UC_8 lastArrival = 250;
UC_8 expected = 15;
UC_8 maxInterArrTime = 30;

result = expected - arrival;
result2 = lastArrival - arrival; //Problem

if(result2 >= ???){ // How should I compare and with what?
  //Message received after previous msg

  if(result <= maxInterArrTime){
  // ON TIME!
  }
  else{
  // DELAYED
  }
else{
  //Message received before previous msg - ERROR
}

My problem is when the arrival time value is lower than the previous arrival time, but is actually "larger" since it has wrapped around. I guess I might need to do it i several steps.
Any suggestions how I can solve this? I need to keep the number of if-statements low, the code will be analysed for complexity and other stuff.

A: If you can GUARANTEE that the delay between packets will not be 256 or more then the following will account for wrap around
if (newerTime >= olderTime)
  delay = newerTime - olderTime;
else
  delay = 256 - olderTime + newerTime;

If you can't guarantee the delay is less than 256 then unwind is correct, and you can't do what you want to do.

A: Huh? You can't magically code your way around a case of missing information. If you only have 8-bit unsigned timestamps, then you will not be able to differentiate between something that happened 3 ticks ago, and something that happened 259 ticks ago, and so on.
Look into making larger (more bits) timestamps available.

A: If you can ensure that the absolute value of the time delta is less than 1/2 of the maximum measurable time span then you can determine the time delta.
int8_t delta_u8(uint8_t a, uint8_t b) {
    int8_t delta = a - b;
    return delta;
}

...

  delta = delta_u8(newerTime, olderTime);
  delay = abs( (int) delta ); // or you could have a byte version of abs, since
                              // I suspect that you may be doing embedded stuff
                              // and care about such things.

If you can ensure that time always move forward then you can do better.  By time moving forward I mean that in your case newerTime is always greater than olderTime, regardless of how they numerically compare.  In this case you can measure deltas up to the maximum measurable time span -- which really goes without saying.
uint8_t delta_i8(uint8_t a, uint8_t b) {
    return a - b;
}

If you know that two events can't happen during the same tick you can do even better by 1.  If you know that two events can't happen closer together than a certain amount of time then you can calculate deltas up to maximum time span representable by your time stamp + the amount of time that must be between events, but then you have to use a larger variable size to do the actual math.
All of these work because the values rap around when you do math on them.  You can very easily think of this as turning one of your known time values into the new origin (0) and adjusting the other time value to match this shift.


text:
Q: Program to move room to room I have attempted changing the rooms around and for some reason I always get an output of You cant go that way, please choose a new direction!, or Invalid entry. I have not been able to move rooms. What should am I doing wrong? I dont know what I am doing and people are so rude.
rooms = {
        'Great Hall': {'South': 'Bedroom'},
        'Bedroom': {'North': 'Great Hall', 'East': 'Cellar'},
        'Cellar': {'West': 'Bedroom'}
    }

place = 'Great Hall'

def go_new_place(place, direction):
    new_place = place
    for i in rooms:
        if i == place:
            if direction in rooms[i]:
                new_place = rooms[i][direction]

    return new_place

while 1:
    print('You are in', place)
    direction = input('Which direction would you like to go? Or do you wish to exit?')
    if direction == 'Exit':
        exit(0)

    if direction == 'North' or 'South' or 'West' or 'East':
        new_place = go_new_place(place, direction)

        if new_place == place:
            print('You cant go that way, please choose a new direction!')
        else:
            place = new_place
    else:
        print('Invalid entry!')

A: I just run your code and made some tests with inputs and the code work fine. Maybe when you input a direction you use lowercase characters? There is a difference between South and south in python.
Edit:
To get rid of the spaces the user may input, you can use the strip() function. it takes a string and returns it without the spaces in the start or the end of the string. Very useful.


text:
Q: Google Maps v3 API - Drawing Circles on Map What I'm trying to do is draw a circle on google maps and retrieve the latitude/longitude/radius to store in a database, alternatively a geometry object would also be fine.
Using the standard code from https://developers.google.com/maps/documentation/javascript/examples/drawing-tools i created the map and drawing toolbox. What i can't seem to do is get the lat/long/radius from the map using javascript, surely this must be possible.
Any ideas?
Thanks
Note - my code is identical to the google example, i figured it was better to link to it rather than copying ~60+ lines of html into a post.
Thanks

A: Ref: https://developers.google.com/maps/documentation/javascript/drawing
google.maps.event.addListener(drawingManager, 'circlecomplete', function(circle) {
      var radius = circle.getRadius(),
      center = circle.getCenter();
});

Edit: getCenter()


text:
Q: What are the security benefits of using a proxy server? In Wikipedia is written:

Security: the proxy server is an additional layer of defense and can protect against some OS and Web Server specific attacks. However, it does not provide any protection to attacks against the web application or service itself, which is generally considered the larger threat.

What OS and Web Server specific attacks are meant ?

A: Webservers such as IIS, Apache, Tomcat and others that serve applications have a very large base of source code. This means that there is plenty of room to find security exploits as well as many other less harmful bugs. The exploits are often published on mailing lists such as those available through http://www.securityfocus.com/.
Proxy servers such as nginx are often "thinner", with smaller source code bases thatn the application web servers, and therefore have a smaller attack surface. Some exploits in IIS or Apache or other application web servers can therefore be masked by a proxy server that either does not have the same exploit or that can filter requests to prevent access to the exploit on the end server.
The proxy server can run on a minimal OS, such as a custom Linux filesystem that has very few services and executables on the filesystem other than the proxy server, so that if someone does manage to find an exploit in the proxy, there aren't enough executables in the proxy's OS (possible not even a shell program) to take advantage of the exploit. This is much safer than exposing a full-featured, general purpose OS to the Internet. Full featured OS's often have many exploits and usually need to have a full complement of utilities and shells in order to provide the desired service.
In general, the rate of exploit detection for application servers and full-featured operating systems together is much higher than the rate for the commonly used proxy servers and their OS's, so a proxy can buy you time to fix a back-end application server or OS vulnerability.
Although Wikipedia states "it does not provide any protection to attacks against the web application", in fact some proxy servers can perform HTTP request re-writing or filtering that can go a long way to preventing SQL injection and CSS attacks.


text:
Q: Docker Containers not running on boot2docker boot Operating system: Windows10
Using:

*

*Oracle VM VirtualBox

*DockerToolbox v1.9.1i

Hi, do you know how to start a container automatically at boot2docker boot?
I have created a new machine with docker-machine. Then I have run a new container with docker run. It's all up and and running, but when I shutdown my Windows and try to start my docker machine the container inside doesn't start. I have tried to add docker start id command to the file /mnt/sda1/var/lib/boot2docker/profile but it doesn't work.
I have tried also to connect to the virtual  machine with ssh (docker-machine ssh name) and run the command docker start id without success. Finally I have to stop and remove the container and make a docker run again.

A: I suspect your container don't start because when the machine (the boot2docker VM) restarts, it still has it in an 'Exited' state.
Confirm with a docker-machine ssh default "docker ps -a". (after a docker-machine start default)
If so, add in your /mnt/sda1/var/lib/boot2docker/profile a call to a script which will:

*

*test if the container is exited:
docker inspect -f {{.State.Running}} $CONTAINER_ID

*if the previous command

*

*errors, it means the container is not runnig at all: docker run

*returns false, docker rm + docker run

*return true: nothing to do.


text:
Q: which is correct - in section below or below section We have given detail description of these tools in below section.
or
We have given detail description of these tools in section below.
which one is correct?

A: Either is acceptable in UK English, provided that you to put a 'the' in there:
"We have given detailed descriptions of these tools in the below section."
or:
"We have given detailed descriptions of these tools in the section below."
or even:
"We have given detailed descriptions of these tools in the following section."
If you search google for the term 'the below section', you find many official UK and US documents which use it:
https://www.google.co.uk/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=%22the+below+section%22+filetype:pdf


text:
Q: Facebook page tab is empty even for google.com? I've struggled with setting up a new Facebook page tab app for days. No matter what I do, I see a blank page (and believe me, I've read everything that google could find on the subject). Finally, I figured I just needed to see something working. So, I set up the most basic page tab app I could think of. All it does is tries to load google. Here's the setup: http://cl.ly/1h0R2c3O1T3i1T1B422d. There's nothing more to it.
You can try installing it to your own page: https://www.facebook.com/dialog/pagetab/?app_id=389862364403147&next=http://google.com
When you do, I suspect you'll see what I'm seeing...nothing (except for the familiar Facebook page header and footer)
Just in case Facebook isn't loading google.com 'cause they're at war, here's the setup for my real application: http://cl.ly/2J2t3n3I1D1N262M1s0J
Here's what I've tried:

*

*Using a proxy to a publicly-accessible domain.

*Making sure to use absolute URLs for Page Tab and Secure Page Tab

*Sending the simplest page (the facebook_channel page I'm using now is just some text enclosed by html and body tags.

*Not using html and body tags, and just using text.

*Creating servers on https and http.

None of this works. Thanks in advance for your help. If I had hair, I'd be ripping it out.

A:
When you do, I suspect you'll see what I'm seeing...nothing (except for the familiar Facebook page header and footer)

Get a better test browser then :-)
Opera gives me the following message,

Error
https://google.com/
The website does not permit its content to be displayed in a frame. It must be displayed in a separate window.

– which was to be expected, since Google sends the HTTP header X-Frame-Options:    SAMEORIGIN
Regarding your problem with your own app page – check your server logs, to see if the request even comes up there; and if so, how it is answered.
Then check if there's a problem with your SSL certificate – Firefox for example won't let you add an exception for your local test site if it's displayed in an iframe (should show a warning message though). Can you reach your test page outside of Facebook, stand-alone?


text:
Q: Pages in beamer are incorrectly numbered when using "show notes on second screen" I'm using beamer to create a presentation, and want to use the mode "show notes on second screen". Unfortunately, there seems to be a bug: when I turn it on, the page numbers are shifted one page up, so page 1 becomes 2, 2 becomes 3, and so on, with the last page number being repeated. With overlays, the numbers also shits one position, so the previous page of the overlay, and the last one has incorrect number.
I attach a minimum sample file: just check the PDF page numbers. By commenting the line \setbeameroption{show notes on second screen=left}, the numbers work fine; when adding it, the numbering fails.
\documentclass{beamer}

\usepackage[spanish]{babel}

\usepackage{pgfpages}

\setbeameroption{show notes on second screen=left}

\begin{document}

\begin{frame}
First frame (should be 1)
\end{frame}

\begin{frame}
Second frame (should be 2)
\end{frame}

\begin{frame}
Third frame (should be 3)\\

\pause
Also third frame (should also be 3)
\end{frame}

\begin{frame}
Fourth frame (should be 4)
\end{frame}

\end{document}

A: I know this is an old question, but I just ran into this problem myself and decided to do something about it.  I wrote a little perl script to shift the page numbers up one and add a number 1 for page 1.  This reverses the mangling done by pgfpages, at least for me.
You'll need to have perl installed and the CAM::PDF module from CPAN.
Download the program


text:
Q: Why would a photodiode with an op-amp be very linear? I read here mentioned

The configuration in Figure 1a creates a  very linear response in terms of the irradiance of the light source.

Would this configuration of photodiode not be linear? Why?

The model of photodiode model should be following picture:

Voltage across photodiode should be \$V = I_{PD} \cdot R_{Load}\$ (ignore dark current)
V of above formula seems to very linear to Id and Rload
Why does a photodiode need a transimpedance amplifier for linearity?

A:
Voltage across photodiode should be $$V = I_D \cdot R_Load$$

This is wrong. The entirety of \$I_d\$ does not flows straight to \$R_load\$. It gets split up to also flow through the junction capacitance and shunt resistance.
\$I_d\$ itself is also of limited power in that it has limits as a current source and can't produce any arbitrary voltage to maintain its output current. It gets loaded down.

A: Your circuit should be close to linear if the voltage across the load resistor is moderate. The voltage across the diode changes, but that doesn't have a strong effect on the current unless it gets so small (< 1V) that significant forward current flows. However, the depletion depth of the diode varies with bias: photocharge generated outside the depletion region is poorly collected, so that influences the current. This is most pronounced for infrared, where the radiation may penetrate the entire volume of the diode.
So, for fussy photometry use a transimpedance amp. For less fussy applications, a load resistor may be OK.

A:
Why does a photodiode need a transimpedance amplifier for linearity?

It's a simple case of if the bias voltage across the photodiode changes, then the photo-current for a given illumination will also change: -

Original image from here.
So, if you have a photodiode in series with a resistor and, the photo-current increased, then the voltage across the resistor must also increase and, inevitably the voltage bias across the photodiode must decrease. This creates a more non-linear relationship.
An op-amp trans-impedance-amplifier (TIA) holds the voltage across the photodiode constant.
There are also other benefits of a TIA.

A: For DC, your formula works.
But bear in mind that in your voltage output setting, the output voltage varies based on photocurrent, so based on photocurrent, there will be different DC bias over the photodiode, and the generated photocurrent just might depend on the voltage bias over it.
And, like mentioned, the load resistance and thus output voltage varies, and so does the internal capacitances need current to get charged to new voltage values.
With the photocurrent mode, the op-amp keeps a fixed bias voltage over the photodiode. Thus the DC bias does not vary based on photocurrent. Also the internal capacitances are kept relatively constant voltage as the photocurrent can't change the voltage of capacitances that much, as there is only the internal series resistance.
The photocurrent mode is just faster an better, at least for high speed data communications.


text:
Q: mysqli_fetch_array not showing results correct I'm rather new to both MySQL and PHP. But I am trying to list my results correct with from my database. But only get some results.
This is my SQL, and when I try it direct to the database I get the result I want.
$sql = "SELECT ItemRelation.ItemRelTo, ItemRelation.Item, Items.CatID, Items.ItemID,
Items.Title, Items.Image, Items.Desc, Items.TimeStamp
FROM Items
INNER JOIN ItemRelation
ON ItemRelation.ItemRelTo=Items.ItemID
WHERE ItemRelation.Item = " . $filterbyitem;

So it's when I am trying to list my result with a mysqli_fetch_array I don't get the same
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
    echo '
';
    echo '' . $row['ItemID'] . '	';
    echo '' . $row['Item'] . '	';
    echo '' . $row2['CatID'] . '	';
    echo '' . $row2['Title'] . '	';
    echo '	';
    echo '' . $row2['Desc'] . '	';
    echo '' . $row2['TimeStamp'] . '	';
    echo '
';
}

It list the result from ItemID and Item but the rest will not show. Is there anyone that can see any problem by doing this? I have listed my results like this before but not whit this SQL commando when I read from several tables.

A: Change row2 to row and it solves your problem
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result))
{
    echo '
';
    echo '' . $row['ItemID'] . '	';
    echo '' . $row['Item'] . '	';
    echo '' . $row['CatID'] . '	';
    echo '' . $row['Title'] . '	';
    echo '	';
    echo '' . $row['Desc'] . '	';
    echo '' . $row['TimeStamp'] . '	';
    echo '
';
}