Creating stored procedure with declare and set variables

Question: I am creating one stored procedure where only value has to pass and I have to retrieve multiple values from multiple tables. I tried to do like this but its showing errors like

Incorrect Syntax near Begin

and

Must declare the scalar variable @OrderID

Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT

SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)

SET @AppointmentID = (SELECT  AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)

SET @PurchaseOrderID = (SELECT  PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)

Comment: Where is `@OrderID` declared? Please post the entire procedure, there is no `BEGIN` in the code you posted. Also why are you assigning to variables then never using the results anywhere? Should these be output parameters?
Comment: Since I assume there may be many order items, appointments, or purchase orders for an order, can you describe which one you want to assign to the variable? It also might help to post all of the code as @Martin suggested and also to post your actual goals, some sample data and desired results.
Answer: You should try this syntax - assuming you want to have @OrderID as a parameter for your stored procedure:
CREATE PROCEDURE dbo.YourStoredProcNameHere
   @OrderID INT
AS
BEGIN
 DECLARE @OrderItemID AS INT
 DECLARE @AppointmentID AS INT
 DECLARE @PurchaseOrderID AS INT
 DECLARE @PurchaseOrderItemID AS INT
 DECLARE @SalesOrderID AS INT
 DECLARE @SalesOrderItemID AS INT

 SELECT @OrderItemID = OrderItemID
 FROM [OrderItem]
 WHERE OrderID = @OrderID

 SELECT @AppointmentID = AppoinmentID
 FROM [Appointment]
 WHERE OrderID = @OrderID

 SELECT @PurchaseOrderID = PurchaseOrderID
 FROM [PurchaseOrder]
 WHERE OrderID = @OrderID

END

OF course, that only works if you're returning exactly one value (not multiple values!)
Answer: I assume you want to pass the Order ID in.  So:
CREATE PROCEDURE [dbo].[Procedure_Name]
(
    @OrderID INT
) AS
BEGIN
    Declare @OrderItemID AS INT
    DECLARE @AppointmentID AS INT
    DECLARE @PurchaseOrderID AS INT
    DECLARE @PurchaseOrderItemID AS INT
    DECLARE @SalesOrderID AS INT
    DECLARE @SalesOrderItemID AS INT

    SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
    SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
    SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END

Comment: On the other hand, your result is undefined because you've used `TOP` without `ORDER BY` - it will pick an arbitrary row. I would prefer to leave out the `TOP` - this way if you meant the inner query to only select one row, you get an error otherwise. With the `SELECT @OrderItemID = ` or `TOP 1` approaches, you get the arbitrary row silently. For cases where `OrderID` is the primary key it's one thing, but in other cases I think we need a better definition of which AppointmentID / PurchaseOrderID is actually desired. The oldest? The most recent? The one with the highest value?
Comment: I dunno, I guess it's personal preference, but it's clearer what's going on using `SET`, especially for a single value.  Otherwise it gets hidden in the whole `SELECT` statement.


I can't open this .jar file. Help! (Kubuntu Wily)

Question: I have already checked the questions people ask about this problem. But that
was Ubuntu and I'm running Kubuntu.
I tried to set jar on the Application Preferences Order but there is no
such thing as jar so, I choose java instead.
Then I clicked OK and everything and double clicked on the file I want to open. The loading cursor changed into a jumping coffee bean but still, nothing
happened. It still won't open.
Now, after doing some gcj stuff (which I have no idea what it is), I tried to execute java -jar PixelsinHell.jar and it shows me this :
    Exception in thread "LWJGL Application" java.lang.ExceptionInInitializerError
        at com.badlogic.gdx.backends.lwjgl.LwjglGraphics.setVSync(LwjglGraphics.java:502)
        at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:118)
Caused by: java.lang.ArrayIndexOutOfBoundsException: 0
        at org.lwjgl.opengl.LinuxDisplay.getAvailableDisplayModes(LinuxDisplay.java:954)
        at org.lwjgl.opengl.LinuxDisplay.init(LinuxDisplay.java:738)
        at org.lwjgl.opengl.Display.<clinit>(Display.java:138)
        ... 2 more
AL lib: (EE) alc_cleanup: 1 device not closed

Help, please?
Comment: Ubuntu and Kubuntu will have no differences here. Use those other questions.
Answer: This post appears to have your exact error message.
It states that installing the x11-xserver-utils package is required. You can install this with sudo apt-get install x11-xserver-utils.


Java: Merging two lists from complex objects with duplicates to one ordered list

Question: First off my problem is similiar to this already answered question Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java.
However the difference here is that I tried to merge two lists with more than just a String together. The intention on my side was to merge two objects of the following kind (to simplify things I striped unnecessary infos from the example):
public class Data{
  private int count;
  private Type type;
  private Key uniqueKey;
}

So that I get a new oject which has a summarized count out. This will eliminate unwanted duplicates because the uniqueKey on these objects was identical. The reason for this is that I mapped several business types to only one technical type.
The problem here is that you have to account for every possiblity in order to handle the merge correctly and don't miss an original object.
Here are some cases I tried to cover with unit test:

One normal, followed by two duplicates, and one normal = normal, merged, normal
Two duplicates, followed by two normal = merged, normal, normal
Two normal, followed by two duplicates = normal, normal, merged

and so on and so forth...
So how to solve that without going crazy?
Answer: Since I spent half a day with that problem, I thought the simple answer might be useful to someone else.
So what did I try:

I decided not to go recursive since I avoid it if I can for obvious reasons and used two nested loops
I wrote unit tests for every case I could think of
Then I tried step by step to make them all green
I banged my head against the table because everytime I made one green another one went red
I asked a colleague
He let me state the problem without showing him my "solution"

Here's the magic 15 min solution:
public static LinkedList<Data> merge(final LinkedList<Data> source) {
    final HashMap<Data, Integer> temp = new HashMap<>();

    for (final Data data : source) {
        final int count = data.getCount();
        data.setCount(0);
        if (temp.get(data) == null) {
            temp.put(data, count);
        }
        else {
            temp.put(data, temp.get(data) + count);
        }
    }

    final Set<Entry<Data, Integer>> set = temp.entrySet();
    final LinkedList<Data> result = new LinkedList<>();

    for (final Entry<Data, Integer> entry : set) {
        final Data mergedData = entry.getKey();
        mergedData.setCount(entry.getValue());
        result.add(mergedData);
    }

    Collections.sort(result, new DataComparator());

    return result;
}


Roslyn and error messages

Question: I am building a Roslyn syntax tree from my own DSL. I would like to annotate the tree with information about the original file and line where the data came from, and then to get the potential errors when validating the tree.
How would I annotate the syntax tree?
Comment: Is that info not already there?
Answer: Annotate your tree?  I don't think you can add metadata to the trees directly...  How about adding comments to it?
<code>var tree = SyntaxTree.ParseText(@"namespace Foo
{
    public class Bar
    {
        public string Biz()
        {
            return ""Baz"";
        }
    }
}");
var annotatedTree = SyntaxTree.Create(tree.GetRoot()
    .WithLeadingTrivia(
        Syntax.Comment(String.Format("// source: scratch")),
        Syntax.Comment(String.Format("// date: {0}", DateTime.Now))
    )
    .NormalizeWhitespace()
);
</code>
Comment: As a last resort, it might work, but I would prefer to modify the metadata directly if possible. This would still be a pain, especially considering that I would need to attach comments to every line _in connection with the  original source_.
Comment: Ah, I didn't notice that you mentioned line numbers. The `#line` directive will definitely help.

Roslyn and error messages


Find an enclosing subfolder in Safari's bookmark hierarchy

Question: How do I find the enclosing bookmark folder in the hierarchy for a given bookmark on Safari/MacOS?
I looked in Xcode to examine ~Library/Safari/Bookmarks.plist. That apparently doesn't hold content, just data structure info it seems. Of course I searched manually in each top level folder and then into next level enclosed folders. This problem resulted from slipping my thumb off the trackpad while trying to move a folder. It fell into some crack (ugh). I can find the contents of the enclosed folder since I recall that subfolder's name. I want the enclosing folder for a given subfolder. FWIW I saw a related question for Android's bookmark hierarchy. It doesn't seem to have been answered.
Comment: Please provide enough code so others can better understand or reproduce the problem.
Answer: Low tech answer I discovered. Go to a link that's enclosed. Save as bookmark. Up comes a scrolling list of folders with the one enclosing it selected and also its enclosing folder. I could unravel from there.
On a related problem someone did offer a code sample.I Would have tried that but my coding skills have long since evaporated. Thanks to anyone who spent a moment considering the question.


How to call a function from one class into another(main) class in Qt Creator?

Question: This is in reference to my previous post.
Present State: I have designed a keypad GUI in qt creator by making a separate class and i have displayed the entered text locally in that GUI. But I need to merge this keypad with my main GUI.
I have implemented'friend function concept' to achieve the task. But I m facing some errors in this
I m attaching the modified code along with the question:
keypad class: .h file
namespace Ui {
class kp16;
}

class MainWindow;

class kp16 :
        public QWidget
{
    Q_OBJECT

public:
    explicit kp16(QWidget *parent = 0);

    ~kp16();
     QString dat;
     void handles();

private:
    Ui::kp16 *ui;

   friend class Mainwindow ;  // Now mainwindow class   can access    private members of kp16
   **friend int MainWindow::inputdata( );**  // Inputdata() function of   mainwindow can access internal members of kp16

};
#endif //KP16_H

mainwindow.h
class MainWindow : public QMainWindow
{
Q_OBJECT

 public:
explicit MainWindow(QWidget *parent = 0);
**int inputdata( kp16 val );**  //declare inputdata function in  mainwindow
int i=0;

~MainWindow();
public slots:

kp16.cpp
kp16::kp16(QWidget *parent) :
QWidget(parent),
ui(new Ui::kp16)
{
ui->setupUi(this);
connect(ui->k_pushButton_2,SIGNAL(clicked()),this,SLOT(handles()));
}

kp16::~kp16()
{
delete ui;
}

void kp16::handles()
{
QPushButton* button = (QPushButton*)(sender());
QString fd=button->text();
dat.append(fd);
ui->label->setText(dat);
}

mainwindow.cpp
kp16 *kp;  //creating instance of kp16

int inputdata( kp16 val)     // friend function definition
{
 QString movedata=0;
 movedata=val.dat;
 return movedata.toInt();
}

void MainWindow::on_lineEdit_textEdited(const QString &arg1)
{
    QString displayKeypad;
    displayKeypad= inputdata(*kp);

    ui->lineEdit->setText(displayKeypad);
}

ERRORS:

error: prototype for 'friend int MainWindow::inputdata()'
does not match any in class 'MainWindow'
[in kp16.h]
error: candidate is: int MainWindow::inputdata(kp16)
[In mainwindow.h]
Comment: For starters, `int inputdata(kp16)` should be `int kp16::inputdata()`.
Comment: Even if it is added to the class `inputdata( kp16 )` is not a valid function.
Comment: Did my solution work for your previous question?
Comment: No...because I have to make a touch screen keypad GUI. I am not  interfacing a hardware keypad/ keyboard to my system
Answer: As mentioned in the error, inputdata() is not a member to class kp16 it is friend to class kp16.
-> (or .) operator can be used only with members. friend functions are used called as any other normal function.
To resolve your issue you just need to do following:

Change the line displayKeypad= kp->inputdata(); to displayKeypad= inputdata(*kp);
Change the deceleration of int inputdata( kp16 val ); function as int inputdata( kp16& val );
Change the definition of inputdata() function as following:
int inputdata( kp16& val)     // friend function definition
{
 QString movedata=0;
 movedata=val.dat;
 return movedata;
}

Change friend int MainWindow::inputdata( ); to friend int MainWindow::inputdata(kp16& val);. Though it is redundant because MainWindow is already friend to kp16 class.

Note: Based on the way you are using friend function, I think you need to understand more about use of friend keyword. You can refer this link to know more.
Updated (After question update):
As error log is sugesting, change line friend int MainWindow::inputdata( ); to friend int MainWindow::inputdata(kp16);
Comment: Thanx for ur help..I have implemented the changes being suggested by u..and I have already gone through 'Geeks for Geeks' & 'tutorials point'...
But still some errors are coming....
Comment: Code :
Kp16.h:
private:
    Ui::kp16 *ui;

 friend class mainwindow ;
// Now mainwindow class   can access private members of kp16

friend int MainWindow::inputdata( );
  // Inputdata() function of mainwindow can access internal members of kp16 declaring friend function

mainwindow.h
Comment: @ShubhamSInghRao Can you update the question to provide complete error log? As per above comment it seems that it is a warning not error. Also, can you confirm that in line `friend class mainwindow;` it is correct i.e. it should be `friend class MainWindow;` if I'm not wrong (See the _case-sensitiveness_).
Comment: I have updated the modified code with ur suggestions being implemented.  Plz go through it. Still it is indicating 2 errors.                                                                          And it is 'friend class MainWindow;' only .
Comment: @ShubhamSInghRao Answer is updated!!! Also, if it is `friend class MainWindow;` then update the same in your question. Though I can do this but I leave it upto you.
Comment: friend class MainWindow; Updated in the question too.

Any idea about errors?
Comment: By Implementing the aforesaid suggestions it is giving me new errors:

1. error: 'QWidget::QWidget(const QWidget&)' is private
     Q_DISABLE_COPY(QWidget)
     ^

2. In kp16.h:
     error:  within this context
     in class kp16 :
       ^


What's wrong with this command?

Question: So I entered this and it says this all the time

Data Tag Parsing Failed: Encountered Multiple Top Tags, Only One Expected

And here is the command:
/summon Villager ~ ~1 ~ {NoAI:1,Rotation:[45.0f,-15.0f]},{CustomName:"Fire"}

Comment: For reference, one should [avoid using capital letters for the beginning of *every single* word](http://www.grammarbook.com/punctuation/capital.asp).
Answer: You don't need to separate the {NoAI:1,Rotation:[45.0f,-15.0f]} portion of the NBT tag and the {CustomName:"Fire"} portion. In fact, it's causing the syntax error here.
What you're going to want is as follows:
/summon Villager ~ ~1 ~ {NoAI:1,Rotation:[45.0f,-15.0f],CustomName:"Fire"}

Additionally, you may want to add CustomNameVisible:1 to the NBT tag to make the name show up like a player name, so the command becomes the following:
/summon Villager ~ ~1 ~ {NoAI:1,Rotation:[45.0f,-15.0f],CustomName:"Fire",CustomNameVisible:1}

Comment: it forces a custom name to be visible/invisible, if you set it to`0` you won't see the name, useful for crazy commandblock stuff and custom maps. also sorry for necropost
Comment: After testing, I'm not quite clear what `CustomNameVisible` does. I'll do some more science to find out.

What's wrong with this command?


Draw text along a path on windows phone

Question: I am developing a map App in windows phone 7.5 platform. I need draw a text along some road. In the android, I can create a Path object and assigned start and end points with it. And then I can call the drawTextOnPath API to draw the text along the path. But I don't know how to implement this in windows phone. It seems that I can only use TextBlock to draw text on WritableBitmap, but the TextBlock class does not provide API to change the orient of text. Must I use the XNA to draw the text?
EDIT1: I am not using any Map srevice such as Bing and the Map control to implement my app. Because the App just provides map of our school campus.
Answer: the article :http://windowsphonegeek.com/articles/Windows-Phone-Map-Control-Display-Current-Location-and-Remove-previous-Pushpins
is very useful
....................................2
o  you want to find a way to draw path on writebitmap.
you can draw path on the parent control of the writebitmap.
like this:
var yourpath
  = XamlReader.Load(@"") as Path;
Children.Add(_pathUnreadTriangle);
And MeasureOverride it
Comment: Hi MengMeng, Thanks for your answer, but I am not using the Map Control and any map service such as Bing while I draw my own map by programming. I am so sorry for unclear statement and I will modify the question. Thank you.
Comment: I am sorry, what I want to do is draw a Text string with a specific orientation just like along a path. You must saw a map that draw a text but not 90 degree horizon or vertical.

Draw text along a path on windows phone


c++ print out bitset of vector

Question: I am copy the double value to the vector of unsigned char. It will be my buffer for socket, which should contain values of different types.
I wanted to test if the coping works correct. I wrote a small code.
vector<unsigned char> buffer(8);
double doubleValue_1 = 8.0;
memcpy(&buffer[0], &doubleValue_1, sizeof( doubleValue_1));

bitset<64>bitset_1(doubleValue_1);
cout << "doubleValue_1: " << bitset_1 << endl;

cout << "buffer: ";
for (int i = 0; i < buffer.size(); i++) {
    bitset<8>bitset_v(buffer.at(i));
    cout << bitset_v;
}

cout << endl << endl;

double doubleValue_2;
memcpy(&doubleValue_2, &buffer[0], sizeof(doubleValue_2));

bitset<64>bitset_2(doubleValue_2);
cout << "doubleValue_2: " << bitset_2 << endl;

And I got the output:
doubleValue_1: 0000000000000000000000000000000000000000000000000000000000001000
buffer:        0000000000000000000000000000000000000000000000000010000001000000
doubleValue_2: 0000000000000000000000000000000000000000000000000000000000001000

How you can see, the first doubleValue_1 represented 8.0. Than I copied this value to vector. And the output is NOT equal to the previous one. But when I coped bytes from vector to double back, I got in doubleValue_2 the same value as in doubleValue_1.
My question is, why the output of vector is different than of double? Maybe I print out the vector in wrong way. Could you suggest me how I can do it correctly?
Thank you a lot.
Answer: bitset<64>bitset_1(doubleValue_1); is casting your double to an unsigned long (because that is what the bitset<64> constructor takes.)
Similarly for bitset<64>bitset_2(doubleValue_2);.
Neither one is actually winding up with the bit representation for a double.
Comment: thank you. you are right. I found how I can print out the double. http://www.exploringbinary.com/displaying-the-raw-fields-of-a-floating-point-number/

c++ print out bitset of vector


GWT: The test class 'com.myco.clearing.commons.xml.XMLNodeTest' was not found in module

Question: I have a Maven (3.0.3) / GWT (2.4) project.  I'm trying to write some JUnit test cases but running into issues.  All my test cases extend GWTTestCase and include this code ...
@Override
public String getModuleName() {
    return "com.myco.clearing.product.ProductPlus";
}

The "ProductPlus.gwt.xml" file is located in my src/main/java directory.  To include that in my classpath I have this configured for my surefire-plugin ...
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.6</version>
            <configuration>
                <additionalClasspathElements>
                    <additionalClasspathElement>${project.build.sourceDirectory}</additionalClasspathElement>
                    <additionalClasspathElement>${project.build.testSourceDirectory}</additionalClasspathElement>
                </additionalClasspathElements>
                <useManifestOnlyJar>false</useManifestOnlyJar>
                <forkMode>always</forkMode>
                <systemProperties>
                    <property>
                        <name>gwt.args</name>
                        <value>-out \${webAppDirectory}</value>
                    </property>
                </systemProperties>
            </configuration>
        </plugin>

However, upon running "mvn clean test", I get all these errors, including this one ...
testParsingNodeWithAttributes(com.myco.clearing.commons.xml.XMLNodeTest)  Time elapsed: 2.563 sec  <<< ERROR!
com.google.gwt.junit.JUnitFatalLaunchException: The test class 'com.myco.clearing.commons.xml.XMLNodeTest' was not found in module 'com.myco.clearing.product.ProductPlus'; no compilation unit for that type was seen
at com.google.gwt.junit.JUnitShell.checkTestClassInCurrentModule(JUnitShell.java:743)
at com.google.gwt.junit.JUnitShell.runTestImpl(JUnitShell.java:1346)
at com.google.gwt.junit.JUnitShell.runTestImpl(JUnitShell.java:1309)
at com.google.gwt.junit.JUnitShell.runTest(JUnitShell.java:653)
at com.google.gwt.junit.client.GWTTestCase.runTest(GWTTestCase.java:441)
at junit.framework.TestCase.runBare(TestCase.java:134)
at junit.framework.TestResult$1.protect(TestResult.java:110)
at junit.framework.TestResult.runProtected(TestResult.java:128)
at junit.framework.TestResult.run(TestResult.java:113)
at junit.framework.TestCase.run(TestCase.java:124)
at com.google.gwt.junit.client.GWTTestCase.run(GWTTestCase.java:296)
at junit.framework.TestSuite.runTest(TestSuite.java:232)
at junit.framework.TestSuite.run(TestSuite.java:227)
at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:59)
at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.executeTestSet(AbstractDirectoryTestSuite.java:120)
at org.apache.maven.surefire.suite.AbstractDirectoryTestSuite.execute(AbstractDirectoryTestSuite.java:145)
at org.apache.maven.surefire.Surefire.run(Surefire.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.maven.surefire.booter.SurefireBooter.runSuitesInProcess(SurefireBooter.java:290)
at org.apache.maven.surefire.booter.SurefireBooter.main(SurefireBooter.java:1017)

This is a bizarre error because the class in question is in my src/test/java directory, which I have included as an "additionalClassPathElement" (above).  What other configurations do I need to make to correct this error? - Dave
Answer: The package for your test must be in the client classpath for the module specified. Based on the module's name, your test probably belongs in the com.myco.clearing.product.client package, or a subpackage of that.
Comment: Could you please explain how exactly that is achieved? Thanks.
Comment: How what is achieved, @Cornelius? The package is the same as the normal client code in the project, just in the test sources instead of the regular sources.


Font awesome icons and panels not showing properly when using JS

Question: I'm trying to create HTML elements dynamically with JS. However panels and font awesome icons are not shown properly when doing so.
This is the HTML code I want to create dynamically with JS.

My JS code:
  let row = document.getElementById('row');
  let col = document.createElement('col');
  let panelCustom = document.createElement('panel-custom');
  let fa = document.createElement('fa');

  panelCustom.classList.add("colorized");
  panelCustom.classList.add("border");
  fa.classList.add("fa-chevron-right");
  fa.classList.add("right-arrow");

  row.appendChild(col);
  col.appendChild(panelCustom);
  panelCustom.appendChild(fa);

Comment: There's an unclosed `` in your HTML sample. Please fix it, so we can see what you intended to build.
Answer: You can try this ( it should work as expected ) :

let row = document.createElement('div');
row.className = "row";

let col = document.createElement('div');
col.className = "col";

let panelCustom = document.createElement('div');
panelCustom.className = "panel-custom colorized border";

let fa = document.createElement('i');
fa.className = "fa fa-chevron-right right-arrow";

panelCustom.appendChild(fa);
col.appendChild(panelCustom);
row.appendChild(col);
document.body.appendChild(row);
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" rel="stylesheet"/>
Answer: You can't actually create elements of type "col", "panel-custom" or "fa", like you're trying to here:
let col = document.createElement('col');
let panelCustom = document.createElement('panel-custom');
let fa = document.createElement('fa');

These are not valid HTML elements. In fact, they should be
 elements as in your HTML sample. Create
 elements instead:
let col = document.createElement('div');
let panelCustom = document.createElement('div');
let fa = document.createElement('div');

Then add the required classes:
panelCustom.classList.add("panel-custom");
panelCustom.classList.add("colorized");
panelCustom.classList.add("border");
// etc.


Can I Breed Non-Galarian Pokemon?

Question: I wanted to breed for a High IV / Good Nature Shiny Farfetch'd (Yes I know, odd choice but I have my reasons), but when the first egg hatched a Galarian one came out, even though I used a normal one.
So is it possible to breed non-Galarian forms of Pokemon in Sword and Shield? Or do I have to import them from other games?
Answer: Based on this guide, which I verified and confirmed, giving a Kantonian Farfetch'd an Everstone will allow breeding to maintain its regional form.
However, this will not work for Pokemon where the base evolution, such as Pikachu and Koffing, do not have a regional form. When evolved, their evolution would be the regional variant that is found in Galar region (Standard Raichu and Galarian Weezing respectively).
Another thing to consider that the guide says:

If a female Pokémon or Ditto holding an Everstone breeds, they will always retain their original form.
Comment: Should probably clarify that "regional evolutions" specifically refers to cases where the pre-evolution does *not* have a regional variant. You can use an Everstone to breed an Alolan Vulpix and evolve it into an Alolan Ninetales just fine, for instance.

Can I Breed Non-Galarian Pokemon?


Quoting items in an array with backticks?

Question: I have this code:

let list = "none, inherit, circle, disc, decimal, lower-alpha, lower-latin, lower-greek, lower-roman, upper-alpha, upper-latin, upper-greek, upper-roman";
let a = list.split(',').map(s => s.trim());
console.log(a);
let quoted = '';
a.forEach(t => quoted += `'${t}, '`);
console.log(quoted);

I'm expecting it to log single quotes around each item in the list, but the list comes out like this:
'none, ''inherit, ''circle, ''disc, ''decimal, ''lower-alpha, ''lower-latin, ''lower-greek, ''lower-roman, ''upper-alpha, ''upper-latin, ''upper-greek, ''upper-roman,

(I have a feeling I'm brain farting this but ...) Thoughts on why the '${t}, ' expression is not coming out the way I think it should?  I'm trying to get this:
'none', 'inherit', 'circle', 'disc', 'decimal' ...

Comment: Why was that unexpected? Each item is surrounded by quotes, with the comma inside: `'${t}, '`. Did you want e.g. `'${t}', ` - what *was* the expected output?
Comment: You want `quoted += \`'${t}', \``  (comma outside the single quotes)
Answer: Change this
a.forEach(t => quoted += `'${t}, '`);

to this
a.forEach(t => quoted += `'${t}', `);

Comment: Or you could just use `join`: `\`'${list.split(',').map(s => s.trim()).join("', '")}'\``
Comment: Nice tip - I'll be adding that!  Thanks!
Answer: Just use .split() with a comma and a space delimiter then .join("', '") for a string.
Demo

let list = "none, inherit, circle, disc, decimal, lower-alpha, lower-latin, lower-greek, lower-roman, upper-alpha, upper-latin, upper-greek, upper-roman";
let str = `'${list.split(', ').join("', '")}'`;
console.log(str);
Answer: Here's another way using just the regexp -

const list =
  "none, inherit, circle, disc, decimal, lower-alpha, lower-latin, lower-greek, lower-roman, upper-alpha, upper-latin, upper-greek, upper-roman"

const list2 =
  list.replace
    ( /([^,\s]+)(?=,\s*)?/g
    , t => `'${t}'`
    )

console.log(list2)
// 'none', 'inherit', 'circle', 'disc', 'decimal', 'lower-alpha', 'lower-latin', 'lower-greek', 'lower-roman', 'upper-alpha', 'upper-latin', 'upper-greek', 'upper-roman'


error in ldap_pvt_thread.h while giving 'make depend' to add dependencies

Question: I am configuring openldap-2.3.6 in my RHEL6 server, after running ./configure command successfully, I am getting the follwing error while adding dependencies using the command 'make depend'.
The error is:
../../include/ldap_pvt_thread.h:69:7: error: missing binary operator before token "("
I have checked line no.69 in ldap_pvt_thread.h, it goes like this:
<code> 61 #define LDAP_PVT_THREAD_CREATE_JOINABLE 0
 62 #define LDAP_PVT_THREAD_CREATE_DETACHED 1
 63
 64 #define LDAP_PVT_THREAD_SET_STACK_SIZE
 65 #ifndef LDAP_PVT_THREAD_STACK_SIZE
 66         /* LARGE stack. Will be twice as large on 64 bit machine. */
 67 #define LDAP_PVT_THREAD_STACK_SIZE      ( 1 * 1024 * 1024 * sizeof(void *) )
 68 /* May be explicitly defined to zero to disable it */
 69 #elif LDAP_PVT_THREAD_STACK_SIZE == 0
 70 #undef LDAP_PVT_THREAD_SET_STACK_SIZE
 71 #endif

</code>
I have even tried by changing line no.69 to:
if defined( LDAP_PVT_THREAD_STACK_SIZE ) && LDAP_PVT_THREAD_STACK_SIZE == 0
but it dint workd...
it is driving me nuts ...what change do I need to make, please help....!
Answer: Either you are using a fairly old branch of the code or somehow this bug has got back into the code.
I can compile a recent branch without error, on an older branch (circa 2007) I get the problem.
The patch (indicated in the above link) works for me, I then have to configure with
CPPFLAGS=-D_GNU_SOURCE ./configure
to get round this subsequent error
getpeereid.c:64:15: error: storage size of peercred isn't known


Laravel 5.X - Too many redirects error when using IP address

Question: I am trying to redirect to /hc/ directory which holds index.php, etc. The browser is showing ERR_TOO_MANY_REDIRECTS error. Please tell me what I am doing wrong here.
This was working just fine when I was using a domain name in my old hosting. Now when I am using IP it is failing.
# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /hc/

# Protect hidden files from being viewed
<Files .*>
Order Deny,Allow
Deny From All
</Files>

RewriteCond %{HTTP_HOST} ^126.96.36.199$ [NC]
RewriteRule ^(.*)$ http://220.127.116.11/$1 [L,R=301]

# Protect application and system files from being viewed
RewriteRule ^(?:application|modules|system)\b.* index.php/$0 [L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php?/$0 [PT,L,QSA]

Comment: Roll back my changes, if you don't like them.
Answer: The problem with this rule
RewriteCond %{HTTP_HOST} ^184.108.40.206$ [NC]
RewriteRule ^(.*)$ http://18.104.22.168/$1 [L,R=301]

is that it redirects ^(.*)$ to itself $1. The client then requests the same URL again, and is redirected to itself, and requests the same again, and so on ... Using a domain name doesn't change this.
To avoid this redirect loop, or any other loop, you need some condition, which exits early or skips this rule.

To redirect everything to /hc, you can use this rule
RewriteRule !^hc/ /hc%{REQUEST_URI} [R,L]

This rule first checks, if the request isn't already for hc, and if it is not redirects it.
And then to rewrite each request for /hc/ to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php?/%{REQUEST_URI} [L]

Comment: It depends on what the rule is supposed to do. As it stands, this rule does effectively nothing, and you can just remove it.
Comment: Thanks, I have a laravel '/hc' directory in the public_html folder and my need is to redirect every request to the 'hc' directory which in turn will call the respective controller. It seems not working for me. I have commented out the lines pointed out but it still not working for me.


JQuery - get value of data attribute of element in selector, not in attr

Question: I am always looking for a shorter and faster way of making jQuery selections, and I wondered if there is a shorter way to select the value of the data attribute of a given element. Now I have this
const phoneCode = $('#loginCountryCodeInput').attr('data-phone-code');

to get the value of this data attribute
<input id="loginCountryCodeInput" data-phone-code="+1">

Is there a shorter selector, something like this?
const phoneCode = $('#loginCountryCodeInput[data-phone-code]');

Comment: No, it doesn't work that way!
Answer: Use data() method to get custom data-* attribute value.
$('#loginCountryCodeInput').data('phone-code');

FYI : There is no way to get the value by a selector, which generates a jQuery object.

There are some difference between the methods : jQuery Data vs Attr?
Comment: @Marco : there is no way to get it's value, simply using selector :)
Comment: Nice but the question is to achieve it by selectors :)
Answer: You can have .data() function for that
$("#controlid").data("phone-code");

Answer: Yes there is. It's almost like the one you wrote, but you need to use $("#id-of-element[property='value']").
E.g.: $("#loginCountryCodeInput[data-phone-code='+1']")
Source documentation: https://api.jquery.com/attribute-equals-selector/
Answer: try this. there any other answer available. take which one best suite for you.
document.querySelectorAll('[data-phone-code="+1"]');
$('a[data-phone-code=+1]');


Where can I find webmin for Ubuntu 10?

Question: I would like to install webmin, but it is neither available from Synaptic, nor from apt-get.
Why can't I find it in synaptic or apt-get? How can I get it and install?
Comment: Can you please let us know the exact version of Ubuntu you are using?
Answer: Webmin is not in any Ubuntu repositories. You will need to download the debian package file (.deb) at http://www.webmin.com/download.html
Their installation instructions for Debian apply to Ubuntu (and include Ubuntu specific notes) at http://www.webmin.com/deb.html

Where can I find webmin for Ubuntu 10?


What do I use to cover an insulation wrapped duct? (Silver foil wrap?)

Question:
I was looking for silver foil to cover the heating duct insulation wrap. What is it called?
Comment: Covering up that duct work with only foil tape is going to be very expensive.
Comment: Are you talking about the insulation over your heating duct lines?
Comment: Doresoom: how expensive? I am good till 100. :-)
Comment: If you want to measure out your area to be covered, it's approximately [$25 for 5400 sq inches](http://www.amazon.com/Nashua-617020-322-3-Foil-Yards-Aluminum/dp/B001S94T1S), which comes out to $0.66/sq. ft. if I did my math right. Don't forget to account for overlap!
Answer: You're looking for Duct Wrap.  It's actually an insulation in it's own right, being one side foil, and the other side fiber insulation.   I see no reason why you couldn't apply it over top of the existing insulation, provided everything is dry.

http://www.homedepot.ca/product/reflectix-duct-wrap-12x25/902353
Answer: HVAC foil tape or Aluminum foil tape.  What you DON'T want is a fabric/cloth duct tape.


Why are battleaxes so rarely used among players?

Question: I started playing OSRS last week mainly due to the nostalgic factor. However I never realised before that I've never seen a player fighting with a battleaxe (in the F2P world atleast, can't say about Members worlds).
Which is odd because stats-wise it would be the perfect middle-ground between scimitar and 2H swords.

               | Speed | Slash | Strength Bonus|
Battleaxe      |   4   |  +48  |      +64      |
2H Sword       |   3   |  +69  |      +70      |
Scimitar       |   6   |  +45  |      +44      |

I've used the stats from the rune weapons, because that's the strongest set in F2P.
So why is the battleaxe so rarely used?
Source for weapon attack speed
Battleaxe stats
2H Sword stats
Scimitar stats
Comment: @BadAtPHP For accessibility reasons, non-code content should not be indented or wrapped in `<code>` tags, or screenreaders et al will read it as code and visitors who rely on that could be confused. It's also more at play in code-based sites on the SE network where questions *require* code at certain times and people might abuse backticks or indentation to get around that rule.</code>
Comment: IDK why the edit was needed or WTH it changed, but ohh well...
Answer: I can speak for the members side of things, and battleaxes are still rarely used.  I think the reason is mainly due to the speed of them.  Yes they are stronger than certain weapons, but let's analyze an example situation here:
Let's examine how many times you would perform an attack across 36 game ticks using a battleaxe (roughly 22 seconds).
36 game ticks / 6 ticks per attack = 6 total attacks
Now let's do the same with a scimitar:
36 game ticks / 4 ticks = 9 total attacks
Thus within the same amount of game ticks, you would be able to perform three additional attacks using a scimitar compared to a battleaxe.
Another problem with battleaxes is by the time you are ready to use the stronger variants (such as rune and dragon), you will end up paying more for them than you would for their scimitar counterparts.
For example: The dragon battleaxe is currently around 120,000 gold, where the dragon scimitar is about 60,000.  Attack bonuses for both of these weapons are nearly the same, with the battleaxe only having a +3 advantage (in regard to using the slash style).  This also doesn't consider the fact that you need to do certain quests to use both of these weapons.  The Dragon Battleaxe requires a significant amount of prerequisites while the Dragon Scimitar doesn't require as many.
The max hit with a dragon battleaxe at 99 strength with no other items is a 26 (see this calculator).  The max hit with a dragon scimitar at 99 strength with no other items is 22.  Consider the situation above again, except this time we will use the total number of attacks to calculate the total damage that can be dealt in this time span:

Dragon Battleaxe: 6 * 26 = 156 total damage
Dragon Scimitar: 9 * 22 = 198 total damage

Divide those numbers by the time in seconds (~22 seconds):

Dragon Battleaxe: 156 / 22 = 7.09 DPS
Dragon Scimitar: 198 / 22 = 9 DPS

If you managed to max every hit, the dragon scimitar would be able to deal more damage over the battleaxe in the same amount of time since it has a higher DPS.
Comment: Don't remind me of those dreadful DDP++ duels >.> But in the context of the question, I was referring to just the two weapons rather than the entire selection of weapons
Comment: @Wondercricket in most PVP now a days, neither of these specials are used.  The battleaxe raises your strength but at the cost of your other stats, while the scimitars turns off your opponents protections prayers for just 5 seconds.  This could be enough to make a difference in a fight, but it costs 55% of your special attack power to perform, leaving you with at most one spec afterwards with something like a dragon dagger.
Comment: On top of DPS output, DS is preferred in PVP over the DBA IIRC. While the DBA's special increases your stats, the DS's special prevents your opponent from using the protection prayers
Comment: There is one exception to using battleaxes and its the Leaf Bladed one.  It's great to use for slayer on certain creatures due to it having significant boosts.
Comment: @Wondercricket if we are just talking about these two weapons then yes I would agree. The battleaxe spec is not worth it, especially if using potions which most do in PvP
Comment: Thanks for the answer. Didn't think about that the scimitar's DPS would overtake the BA after a few ticks.
Comment: Shouldn't you divide with seconds to get DPS?
Answer: The battleaxe has lower DPS (damage-per-second, the rate at which damage is inflicted) than the other two by a significant amount. For certain monsters, it's worth switching between the longsword and scimitar, but the battleaxe DPS is low enough overall that it's never really worth using. The scimitar is generally considered to be the best overall due to having the highest DPS.
Answer: While it be might seem like the best because it is in the middle of strength and speed, most people use a scimitar simply because of its speed. Being able to hit faster and more often in a fight usually is more advantageous than hitting slower.
Especially in PvP, the more you can hit your opponent the more time they have to spend healing which can cause the unprofessional ones to lose their cool and mess up the fight.


event.getX not corresponding with getLayoutX for circle

Question: I'm trying to create a program that creates an instance of circle which gets the x and y coordinates of the mouseclick. However when trying to get the x for the circle it seems to be equal to 0.
pane.setOnMouseClicked(new EventHandler<MouseEvent>() {
        public void handle(MouseEvent event) {
            final Circle newCircle = getCircle(event.getX(), event.getY(), 30);
            pane.getChildren().addAll(newCircle);
            final Timeline loop = new Timeline(new KeyFrame(Duration.millis(100), new EventHandler<ActionEvent>() {
                double deltaX = 2;
                double deltaY = 2;
                public void handle(ActionEvent event) {
                    newCircle.setLayoutX(newCircle.getLayoutX() + deltaX);
                    newCircle.setLayoutY(newCircle.getLayoutY() + deltaY);

                    final Bounds bounds = pane.getBoundsInLocal();
                    final boolean atRightBorder = newCircle.getLayoutX() >= (bounds.getMaxX()-newCircle.getRadius());
                    final boolean atLeftBorder = newCircle.getLayoutX() <= (bounds.getMinX()+newCircle.getRadius());
                    final boolean atBottomBorder = newCircle.getLayoutY() >= (bounds.getMinY()+newCircle.getRadius());
                    final boolean atTopBorder = newCircle.getLayoutY() <= (bounds.getMinY()-newCircle.getRadius());
                    if(atRightBorder || atLeftBorder)
                        deltaX *= -1;
                    if(atBottomBorder ||atTopBorder)
                        deltaY *= -1;
                }
            }));
            loop.setCycleCount(Timeline.INDEFINITE);
            loop.play();

The line i'm focusing on is this one:
final Circle newCircle = getCircle(event.getX(), event.getY(), 30);
            System.out.print(newCircle.getLayoutX());

Where i get the print out "0.0" even though the event.getX parameter is different.
Any ideas as to why this happens?
Edit: getCircle():
 private Circle getCircle(double x, double y, double r){
    final Circle newCircle = new Circle(x, y, r);
    return newCircle;
}

Answer: The constructor you are calling is implemented as such:
public Circle(double centerX, double centerY, double radius) {
    setCenterX(centerX);
    setCenterY(centerY);
    setRadius(radius);
}

Where setCenterX() has the implementation:
public final void setCenterX(double value) {
    if (centerX != null || value != 0.0) {
        centerXProperty().set(value);
    }
}

getLayoutX() is accessing the layoutX property, which haven't been set by the constructor, hence it returns 0.0:
public final double getLayoutX() {
    return layoutX == null ? 0.0 : layoutX.get();
}

You need to set the layoutX property, like you already do in your code:
newCircle.setLayoutX(newCircle.getLayoutX() + deltaX);

Comment: I seem to have fixed this issue by using relocate(event.getX(),event.getY()) instead. But your solution worked as well! thanks!

I seem to have another issue where my bounds maxX and Y are actually updating even though i set it to final.


Power iteration error for eigenvectors

Question: I'm trying to use the ideas of power iteration to approximate stationary distributions of Markov chains. Let's say I have a left irreducible stochastic matrix $A$ (i.e., non-negative and each column sums to 1), with 1 as eigenvalue of multiplicity $1$. Then, there will be a unique positive vector $u$ with $||u||_1 = 1$ and $Au = u$, such that for each non-negative vector $b$,
$$\lim_{k\to\infty} A^kb = u.$$
The rate of convergence is dominated by the second largest eigenvalue of $A$, but I don't necessarily have a way of computing it in my case.
Let's say I have a vector $b$ such that $||Ab - b||_1 \leq \varepsilon$, for some known $\varepsilon > 0$. This is used as a sort-of-good stopping condition in some textbooks, but I would like to know: is there an actual bound (depending on $\varepsilon$ or otherwise) that can be proved for the distance $||b - u||_1$?
Update 1:
I have found some references that do the following: if we let $e = Ab - b$ be the "defect vector" (i.e., the failure of $b$ to be an eigenvector of $A$), then $b$ is an eigenvector of the matrix
$$A + E,$$
where $E = -e\mathbf 1^T$. From here, there are a couple of books that apply perturbation techniques to approximate the error $||b - u||$: if we set $\varepsilon E = -e\mathbf 1^T$ with $||E|| = 1$, then we may see the vector $b$ as a function of $\varepsilon$ (this actually applies to the eigenvalue as well, but in our case it is always $1$):
$$(A + \varepsilon E)b(\varepsilon) = b(\varepsilon).$$
With slightly different notation, in the book Numerical mathematics (Quarteroni et al., 2007) they mention the bound

However, what I want is a bound with the $||\cdot||_1$ norm. So, additional question: is it "legal" to substitute all norms by the norm that I want? I was wondering that it might be (maybe with a modification), as this comes from this other book, An Introduction to Numerical Analyis (Atkinson, 1989), where it is stated:
Comment: Well, you cannot substitute norms "freely", but usually you can rigorously easily substitute a norm with another at the price of a multiplicative constant. This is called the [equivalence of norms](http://mathonline.wikidot.com/equivalence-of-norms-in-a-finite-dimensional-linear-space)
Comment: Here, to pass from a $||.||_2$ bound to a $||.||_1$ bound, you can use $||.||_1\leq \sqrt{n} ||.||_2$ (a consequence of Cauchy-Schawarz)
Comment: I know this bound, but it messes too much with what I want to do afterwards. Also, this bound comes from a first-order approximation of $b(\varepsilon)$ in another book, which makes me think that a similar $||\cdot||_1$ bound could be possible. I'll update the question later with this additional reference.
Comment: @EwanDelanoy I've updated it now. It seems to me that we could take $||\cdot||_1$ norms on both sides (after moving $u_k$ to the LHS) and reach a similar conclusion, right?
Comment: Sure, you can take the absolute values, and sum on all coordinates. It seems you answered your own question ?
Comment: I feel unsafe taking the norm on the RHS after going through this, because in this context each $u_j$ is an eigenvector, not a component (yeah, notation). Which would amount to obtain a bound similar to $n/\min |1-\lambda|$.
Answer: There are two levels of approximations that are usually considered in these situations.  One is to suppose that we know something about the magnitudes of the other eigenvalues.  Then we can write
$$ A = \sum_i \lambda_i v_i u^T_i $$
where $\lambda_i$ is the $i$th eigenvalue and $v_i$ and $u_i$ are its associated left and right eigenvectors, respectively.  In the question, the right eigenvectors $u_i$ are normalized so that $||u_i||_1 = 1$, and it is convenient to choose the normalization of the left eigenvectors so that $v_i^T u_i = 1$.  Since the left and right eigenvectors associated to different eigenvalues are orthogonal, we can write
$$ A^k = \sum_k \lambda_i^k v_i u_i^T $$
and therefore
$$ A^k b = \sum_k \lambda_i^k ( u_i \cdot b ) v_i $$
The first term (with $\lambda_1 = 1$ and $u_1 = u$ as in the question) is the limit for large $k$, which is
$$ \lim_{k \to \infty} A^k b = ( u \cdot b ) v_1 $$
Subsequent terms, which can basically be considered error terms, have a 1-norm of
$$ | \lambda_i |^k | u_i \cdot b | \  || v_i ||_1 $$
You can try to generate a useful inequality from the last equation, but almost all of the value in the inequality will come from an assumption about how much smaller $|\lambda_i|$ is than $|\lambda_1| = 1$.  For example, if we let $\lambda_2 = 1 - \delta$ for some sufficiently small $\delta$, we can basically make the error as bad as we want to.  So the most fruitful way to proceed is to look at the size of $\lambda_2$.
It is obviously not possible to say anything rigorous for $\lambda_2$ for arbitrary matrices, because we can always construct a matrix with a value of $\lambda_2$ that will break whatever assumptions we have made.  But there are very strong results about the size of $\lambda_i$ for random matrices.  And generally speaking, these results apply extremely well for most matrices when $n$ is large, so they are very fruitful for computation.
The most basic result in this field is Wigner's semicircle distribution.  The short version is that if you have a large random symmetric matrix, then the largest eigenvalue will scale as $O(n)$ and the rest of the eigenvalues will have magnitude less than or equal to $O(\sqrt{n})$.  The coefficients of the two depend on the mean and variance of the entries of the random matrix, respectively.  Wigner's original results only apply to symmetric/Hermitian matrices, but they have been extended to the asymmetric case.  There are also extensions that give a distribution for entries in the eigenvectors and so forth, but I don't recall whether there is anything useful there for your question.
In your case, this means that, if your matrix is large and you feel comfortable with thinking of it as being "approximately" random in some sense, then the rest of your eigenvalues should have magnitude less than or equal to $\frac{c}{\sqrt{n}}$, where $c$ can be found by looking at the mean and variance of the entries in your matrix.  This gives you a fantastic convergence result (errors scaling like $n^{-k/2}$) pretty quickly.
I will mention two more things.  First, if your matrix does have a $\lambda_2$ that is very close to $\lambda_1$, then this says that it has some very interesting structure.  For example, in the community of people who study physics on complex networks, we would say that such a matrix might represent a random walk on a network with very strong "community structure."  Second, there are rigorous methods for approximating the eigenvalues and eigenvectors of such matrices (see for example this paper and some of the references therein).  But to apply these methods you have to make some kind of assumption about what the special structure is in your matrix, which will depend on the application you're working on.

Power iteration error for eigenvectors


How to Rename Multiple Files With Their First 10 Characters?

Question: I am having a problem to rename multiple files by replacing the name by their first 10 characters of their old name. I tried to find the solution in internet but I didn't find the answers.
Example:
Original File Names:
1208605001abAcd.jpg
1201230111FbcAdee.jpg
11512345714x611aaa.jpg

What I want to achieve:
1208605001.jpg
1201230111.jpg
1151234571.jpg

Answer: You can try:
rename -n 's/(.{10}).*(\.jpg)$/$1$2/' *.jpg

Example:
$ rename -n 's/(.{10}).*(\.jpg)$/$1$2/' *.jpg
11512345714x611aaa.jpg -> 1151234571.jpg
1201230111FbcAdee.jpg -> 1201230111.jpg
1208605001abAcd.jpg -> 1208605001.jpg

The -n option only simulates the command, so that you can verify the changes. Run without it to actually make the changes.
The regex (.{10}).*(\.jpg) consists:

.{10} - any 10 characters, in a group (…), followed by
.* - any number of any characters followed by
\.jpg$ - the extension at the end ($) of the filename, in the second group

The replacement $1$2 is just the first group followed by the second.
Comment: This holds for the `rename`  that comes with `perl` (e.g. on Ubuntu), not the one that comes with `util-linux` (e.g. on Fedora, CentOS, Cygwin).
Comment: Sorry if I am missing something, when I tried to run your suggested command I've got this message : "Substitution replacement not terminated at (eval 1) line 1.". Did I do something wrong?
Comment: @surya_darmana there was supposed to be a `/` after `$2`. The example output has it correct. I have fixed it.
Comment: Thank you very much, the command is run perfectly, you made my day :D
Answer: You can do with only bash:
for FILE in *.jpg ; do mv "${FILE}" "${FILE:0:10}.jpg" ; done

With a little work you can get file extension and add automagically to the new name.
Comment: Use globbing (`*`) instead of `ls` (for which you wouldn't need the `-1` anyway), and quote the variables. (`"${FILE:0:10}.jpg"`).
Comment: I prefer using ls, but +1 for the quoting! (error of distraction).
Comment: It isn't a matter of preference, using `ls` will break on files with spaces in the name. Globbing won't.
Comment: Great, @Kevin! I never thought about IFS. I'm "old", I'm yet naming my files with underscore instead of spaces. :-)
I'll edit my answer.
Answer: If you use zsh:
zmv '(*).(*)' '${1:0:10}.$2'

If it's not already done, you may need to first run:
autoload zmv

Comment: Will this keep the extensions?
Comment: @muru no, I didn't notice that particular requirement. Updated with a version that does.
Answer: If you want a GUI version, take a look at pyRenamer, a powerful bulk-renaming tool.

pyRenamer has two great advantages. One is that it allows you do a "what if", in other words to see what would happen before you commit to the change.
The other advantage is explained nicely in its description:

You can rename files using patterns, search and replace,
  substitutions, insert or delete text, or even rename files manually.
You can also rename images using their EXIF tags and music using their
  internal tags.

To install, use Ubuntu Software Centre or your favourite software installer, or use the command line issue the following command:
sudo apt install pyrenamer


For two sets A and B, prove or disprove each of the following: A is a subset of B and B is a subset of A

Question: Let $A = \{x\in\mathbb{Z} \mid x = 6a + 4,a\in\mathbb{Z}_{+}\}$ and $B = \{y\in\mathbb{Z} \mid y = 18b - 2, b\in\mathbb{Z}_{+}\}$, where $\mathbb{Z}_{+}$ represents the set of positive integers.
Prove or disprove the following statements:
a) $A\subseteq B$
b) $B\subseteq A$
MY ATTEMPT
Now, for a set $A$ to be a subset of set $B$, the set $B$ would have to contain all elements of $A$.
So, to disprove this, could use just use an example like $a = 1$ where $x = 6(1) + 4 = 10$ and show that $y = 18b - 2$ cannot equal $10$ when be is a positive integer?  I'm not sure if this is correct or if you could also do this for part b.
Thanks in advance!
Comment: Hint1: does $4\in A$ ? $\in B$ ? Hint2: can you write $18b-2=6a+4$ for some $a=f(b)$ ?
Comment: Right.  There are many ways to show that a) is false, but it suffices to find just one $x\in A$ (e.g. $x=10$) which is provably not in $B$ (E.g. $y\in B\implies y\ge 18(1)-2>10). $ F0r b)  observe that $x\in A\iff 2\le (x+2)/6\in\Bbb Z^+$ while $y\in B\iff  1\le (y+2)/18\in \Bbb Z^+\implies 3\le (y+2)/6\implies y\in A.$
Comment: " I'm not sure if this is correct or if you could also do this for part b." You *could* if you could find a counterexample.  But $18\cdot 1-2 = 16 = 6\cdot 2 + 4$ and $18\cdot 2 -2= 34 = 6\cdot 5 + 4$.  So if you want to find a counterexample it's going to requires something more than trial and error?  Who do you think you will find a counter-example (if that is what you want to do)?
Comment: A single counterexample is always enough to disprove a statement. All examples must be taken (i.e. the proof must consider every possible example) to prove a statement.
Answer: If we don't know the answer we can try to prove it and see what occurs.  We may get a proof or we may find a that we don't have sufficient reasons to say it is true and we may get the conditions that may lead to a counterexample.
To prove $A\subset B$ we have to show that for ever $6a + 4\in A$ there is a $b$ so that $18b - 2= 6a+4$.  SO let's try to find that $b$.
If that is so then $18b = 6a +6$ and $b = \frac {6a + 6}{18} = \frac {a+1}3$.
But $\frac {a+1}3$ need not be a whole number.
So we failed!  Boo-hoo!
BUT THAT'S OKAY.
Since $b= \frac {a+1}3$ need not be an integer and could FAIL to be an integer we know it is not an subset and we have a method to find counter-examples.
Let $a$ be so that $\frac {a+1}3$ is not an integer.  Ex. $a=1,2,4,5,7,...etc$ and $6a + 4 = 10,16,28,34,46, ....etc$ will never have an integer $b$ so that $18b-2$.
So $A \not \subset B$.
......
On the other hand to prove $B\subset A$ we must show that for every $18b-2\in B$ there is a $6a + 4\in A$ so that $18b-2 = 6a + 4$.  So let's try to find that $a$.
But this time when we try to find that $a$ we get:  $6a = 18b - 6$ so $a =\frac {18b-6}3 = 3b -1$.  But that is always an integer.
Oh, no!  We didn't fail!  SO we can't find a counter-example and we can't prove $B\not\subset A$!  Boo... hoo?
Wait.  We showed it is always true so .... we did prove $B\subset A$.
SO that's that.  If $18b - 2 \in B$ then $6[3b-1] + 4 = 18b -2$ and $6[3b-1]+4\in A$.
So $B\subset A$.
Comment: Love the language in this answer; takes it to the basics
Comment: Thank you for your enthusiastic and simple answer! @fleablood


Are extensions quasi-isometric

Question: Let $0 \rightarrow K \rightarrow G_1 \rightarrow L \rightarrow 0 $ $$$$
 $0 \rightarrow K \rightarrow G_2 \rightarrow L \rightarrow 0 $ $$$$
be two group extensions with $G_1,G_2$ finitely generated. Are $G_1$ and $G_2$ necessarily quasi-isometric (with respect to their word metric)?Thank you for all your answers.
Answer: No, they need not be quasi-isometric.
For example, using $K=\mathbb{Z}^2$ and $L=\mathbb{Z}$, the extension group $G$ is a semidirect product where the action of $L$ on $K$ is defined by some $M \in GL(2,\mathbb{Z})$. In this case there are three quasi-isometry classes (as one knows from studying the 8 geometries of 3-manifolds, due to W. Thurston):

If $|\text{trace}(M)| < 2$, i.e. if $M$ has finite order, then $G$ is quasi-isometric to $\mathbb{R}^3$.
If $|\text{trace}(M)| = 2$, then $G$ is quasi-isometric to 3 dimensional NIL geometry.
If $|\text{trace}(M)| > 2$, then $G$ is quasi-isometric to 3-dimensional SOLV geometry.

Things will get even wilder for more complicated kernels and quotients.
Comment: You can use the theorem of Milnor that the growth function is a quasi-isometry invariant (up to an appropriate equivalence relation): $\mathbb{R}^3$ has cubic polynomial growth; NIL geometry has quartic polynomial growth; and SOLV geometry has exponential growth. These classes of growth are all inequivalent.
Comment: Is it easy to see that none of these are quasi-isometric to each other?
Answer: Let's Take $G_{1}$ = $HF_{3}(\mathbb{Z}$), the Heisenberg group of 3 by 3 upper diagonal matrices over the integers with 1 on diagonal. Take $G_{2}$ = $\mathbb{Z}^{3}$ , $K$ = $\mathbb{Z}$ and $L =\mathbb{Z}^{2}$. Certainly $G_{1}$ and $G_{2}$ are not quasi-isometric because $G_{1}$ and $G_{2}$ have different growth degree.

Are extensions quasi-isometric


encrypted query string in emails rails

Question: My app sends out an email with a URL in it. The url contains a query string attribute that is encrypted. I CGI escaped the encrypted value so that symbols like + * . etc are escaped. The escaped URL appears in the email as expected, but when we click on the link, the encrypted values are decrypted.
For Example, the url in the email is as follows
http://development.com/activate/snJAmJxkMo3WZ1sG27Aq?album_id=2&email=5M%2BjE1G6UB26tw/Ah%2Bzr1%2BJSSxeAoP6j&owner_id=4
email=5M%2BjE1G6UB26tw/Ah%2Bzr1%2BJSSxeAoP6j
when we click on this link the url in the browser appears as
http://development.com/activate/snJAmJxkMo3WZ1sG27Aq?album_id=2&email=5M+jE1G6UB26tw/Ah+zr1+JSSxeAoP6j&owner_id=4
email=5M+jE1G6UB26tw/Ah+zr1+JSSxeAoP6j
The + is substituted with space. As a result
params[:email] = 5M jE1G6UB26tw/Ah zr1 JSSxeAoP6j
which gives me a 404.
Is there any way I can avoid this situation. How can I make the url in the browser also appear as
http://development.com/activate/snJAmJxkMo3WZ1sG27Aq?album_id=2&email=5M%2BjE1G6UB26tw/Ah%2Bzr1%2BJSSxeAoP6j&owner_id=4
in the browser?
Answer: In order to avoid this situation I Hex encoded the email attribute so that the it contains only alphabets and numbers. Used these are the methods to Hex encode and decode.
<code>convert string2hex:
def hexdigest_to_string(string)
 string.unpack('U'*string.length).collect {|x| x.to_s 16}.join
end

convert hex2string
def hexdigest_to_digest(hex)
 hex.unpack('a2'*(hex.size/2)).collect {|i| i.hex.chr }.join
end
</code>

encrypted query string in emails rails


Does an Interdiction Nullifier module allow escape against a Heavy Interdiction Cruiser's Infinity Point?

Question: Recently my Nereus was blown up - typical eve-online activity.
I made the error of undocking in low sec while a Broadsword was in range. After my ship's destruction, I learned that the Broadsword is a Heavy Interdiction Cruiser, which can use its Warp Disruption Field Generator module on a single ship in low sec to create infinite warp disruption on that ship. This mode is available in low sec, while the bubble mode is restricted to null sec.
This happened the day before the patch, which added new Interdiction Nullifier modules. These modules can be fitted on Industrial ships, like the Nereus.
The module's description is:

Temporarily nullifies the effects of warp disrupt probes and mobile warp disruptors.

Does this module counter the single target mode of the Warp Disruption Field Generator?
Comment: The patch notes state that Interdiction Modules and blueprints are new.
The descriptions on these modules are new, and misleading, imo.

https://www.eveonline.com/news/view/patch-notes-version-19-04
Comment: This isn't a new mechanic, I remember using scripted hics to catch blockade runners with huge amounts of warp core stabs in high sec even. Some 5-6 years ago. Also interdiction nullifiers have been around forever too on t3 cruisers. They only help against bubbles, nothing else.
Answer: No. Scripted HI modules work like scrams/points. Nullification gets you out of bubbles only, same as for Interceptors and T3 Cruisers with the relevant subsystem.
Answer: To complement the accepted answer - the heavy dictors' point strength is not infinite when loaded with scripts. The scripts make it essentially a disruptor or a scrambler module with strength of 100 points (and of course there is no technically a way to overcome such a great number with stabilizer modules).


Ubuntu 18.04 stuck up on boot screen

Question: I'm using ASUS model A53E notebook with 4GB RAM and 500GB HDD. I allocated 100GB for Ubuntu, and Ubuntu has more than 20GB free space. It also has Windows 7 and it's working perfectly. Usually I miss the battery warning and my laptop often gets shut down, but yesterday when I rebooted the Ubuntu system it's hanging on:
Started Gnome Display Manager.
Started Hold until boot process finishes up.

After these two lines nothing is happening.
I tried Boot-Repair and grub-update and Boot-Repair Advanced options, but still got no results. Ubuntu still stops at the above lines.
What precautions should I take in future so this won't happen? What will happen if I'm in a serious development phase working for some clients? Is Ubuntu stable?
Comment: I would boot a 'live' system (eg. Ubuntu install media) and `fsck` (file system check) your partition(s).  If I lose power, it's usually my first step before I try booting.
Comment: used fsck too, then ran boot-repair....still stucking up at `Started Hold until boot process finishes up.` and the boot never finishes...
Comment: Have you switched to runlevel 1 (ie. add a '1' to your linux [kernel] line so it stops at runlevel 1 & looked for clues in logs. Also removing 'quiet splash' may reveal more. You could also just login to terminal (ctrl+alt+f4 for example) and look for clues there too in logs.  I might look for what was last done before power off, or do a search (I'd run this from a 'live' system) for latest file(s) in hopes of clue as to what system was last doing when power went off for clues as to what it was doing.. You may recall what it was doing so can narrow down where to look (what I'd do)
Comment: No, not tried that but like to. Will Level 1 go into rescue mode?

But yes, will try to get the log file. Was browsing when power went off. Have a live USB still no clue, how to get back the old system.
Comment: Tried so many things... it seems the themes and display driver are troubling...Please let me know how to switch to runlevel 1?
Comment: At grub you can add a " 1 " to the linux kernel line to stop the boot at runlevel 1 (default is 5), where at grub you press  to edit the entry instead of  to load.  Refer https://wiki.ubuntu.com/Kernel/KernelBootParameters
Comment: Already used GRUB_CMDLINE_LINUX_DEFAULT="nomodeset" with no change, will try to add 1 at run. As we're not getting prompt to try "systemctl set-default runlevel1.target". Believe we need a tool to analyze and fix all the boot problems of ubuntu. Since windows have safe mode and it fixes most of the problems.
Comment: All the Ubuntu users need much better automatic solution than Windows so that every user need not spend time on R&D on Ubuntu.
Comment: You've done things that have just complicated matters; I would never have run boot-repair; expecting `fsck` alone to have detected and fixed the issue caused by power-outage (corrected for memory that wasn't sync'd to disk), but boot-repair makes changes and if run before the `fsck` it's likely to have introduced many many more issues.  GRUB_CMDLINE* looks like it's from /etc/default/grub which you wouldn't touch; the change I made impacts the next boot only being a change in RAM during boot. There are recovery tools but having run boot-repair (when run matters) I can't advise sorry
Comment: level 1 worked fine for me. able to get back the normal screen but with wierd icons on right side and on desktop.
You're an experienced person but not everyone available on blogs and other sources. Corrected the GRUB_CMDLINE before setting to level1. Believe the themes are disturbed. Will remove and check.
Answer: Open it in recovery mode. and it will boot up after clicking resume. i am also having same issue. i will update if any way is done. for temporary advance option recovery would work.

Ubuntu 18.04 stuck up on boot screen


variable resets upon frame

Question: I have a layer named GlobalActions Layer that is on the main timeline, that holds the variable called EnergyNumber.
On frame 2, but same scene, I have a button that subtracts 10 from the variable that's on the GlobalAction.
Finally, I have a button that returns you to frame 1.
I click that button that sends me back to frame 1, and the EnergyNumber would reset back to 100. How can I fix this?
Comment: Basically, I set a variable to 100, and a button is supposed to take away 10 each time it is clicked. However, the variable always resets itself back to 100 once I leave the frame the button is on.
Comment: HTML5, WebOS, ActionScript, PHP, Excel, iOS, Android?
Comment: Oh, sorry didn't specify. Actionscript 3
Answer: Your variable will get redefined when you return to frame 1.
Solution:

Define your variable on frame one.
Never return to frame 1 - use frame 2 to hold whatever content you currently use for frame 1.
Move the content of frame 2 to frame 3.
Only alternate between frames 2 and 3.
Comment: You are a real lifesaver Marty! Thanks!!
Answer: Actually it is possible to return to frame #1 without resetting the variable in the process.  Here's how:
<code>var myVar;
if (myVar == undefined) myVar = true;
</code>
If you set "myVar" to "false" on another frame and then return, your code will see "false", since it's now a defined variable.

variable resets upon frame


How to remove old-work ceiling light fixture box attached to conduit pipes

Question: I am trying to install thin LED recessed lights in my hallway. I need to remove the old ceiling box, as shown in the picture. I tried to remove the box for the whole day but was unsuccessful. I cut the drywall around it ad is sure that it is not fixed with a joist or anything.
I removed the punch knockouts and found that the whole ceiling box was connected to three conduits using the connected, as shown in the picture below. The conduit brings in the wire for a three-way switch system to the said ceiling box. There are the big nuts that are tightly screwing these conduit connected at the backside of the box.
Please give any suggestions as to how to remove the box. I still want to use the same wiring so don't want to damage the conduits or wires coming out of them.
Thank you
Comment: What make and model is your new fixture? Is mounting the fixture slightly offset from the existing junction box acceptable? Are you in Chicago or such?
Answer: Removing this box is not a good solution when there are rigid conduits bringing wires into this existing box. The main reason for this is that those wires would still need to terminate into an accessible junction box. On top of that there is just no simple way to adapt the existing rigid conduits for connection to the floating connection box on a recessed fixture.
This may be a doable project IF:

You had access to an attic space above this ceiling
You have the experience and perseverance to work through the serious rework of the existing conduits to some other accessible junction box in the attic.
Keep in mind that the wires in those conduits may very well not be long enough when you go to try create a new junction box - which then entails pulling new wires through those conduits back to their other connection points.

The practical way to deal with this is to keep the existing ceiling boxes and install new surface mount LED fixtures. If you insist on the recessed fixtures then you will need to cut new holes in the ceiling for those fixtures near the existing electrical box and then run new flexible conduit from that existing box over to the recessed fixture floating connection box. If you choose this latter route then just purchase suitable flat white cover plates for the existing electrical box. If the ceiling is a different color the flat cover plate can be painted once installed to coordinate with the ceiling.
Comment: You can always use conduit. Depending on jurisdiction, you may also be able to use Romex instead (most places you can). You generally don't want to run Romex inside conduit as it is hard to do and you lose the convenience aspects of Romex.
Comment: Thank you so much, Michael. You have given me great confidence in further steps after today's try. I could not access the attic, thereby, will look for flushed Led light. Just curious, do I need to run Romex wire in conduit in the ceiling as per US electrical code?.
Answer: You need to stop destroying stuff right now.
Since your project is this light, you are assuming the universe is gracious enough to have ALL the wires in these conduits be ONLY about this light.  That is a faulty assumption.  There could be other circuits you don't know about; your plans could break them.
Now to start with, nobody uses conduit for their health. They use conduit because it's legally required in the situation they are in - commercial building, local requirement, etc.  So when you see conduit, expect it's a requirement.
However, conduit is easier than you're making it.  You just need to learn the craft of it.  It might not actually be that big a deal to run conduit from this box to your planned lamp location.  You could demote this box to simply being a splice box and serve the new lamps from here.  Use a blank cover plate and also put 10 cent covers into the holes you erroneously knocked out.
By the way, the reason "removing the box" is impractical is because you don't alter the piping with the wires in it.  You go to the boxes they connect to, and pull  the wires out of it.  Then you modify the piping as needed and pull the wires back in.
Keep in mind every splice, tee and sharp corner need to be at a junction box, and the box cover must be accessible forever.
Answer: The existing answers are correct in that you should not, in all likelihood, be attempting to remove this box or the wiring or the conduit.
However, to actually answer the question you asked, since there are occasions to actually remove and replace a box*
The nut that is visible inside the box on the cable clamp/conduit nipple is a standard righty-tighty, lefty-loosey nut. Usually, you thread the nut on to the nipple, tighten it by hand, then place blade an old flat-blade screwdriver against one of the notches sticking up on the nut tap it with a hammer to tighten it down. To loosen it, simply tap in the opposite direction (turn it counter-clockwise). One or two taps should have it loose enough for you to then turn it by hand to back the nut off.
Tap in the direction of the green arrow to tighten and the red arrow to loosen.
Image courtesy of topaz-usa.com. First small image I found for what I was after. Arrows are own work.
Again, unless you are completely removing the circuit, make sure you replace the box when you're done. All wiring connections must be made in an approved box.

*Valid times to remove/replace the box include replacing a light-weight ceiling fixture (mounted to a standard-duty box) with a ceiling fan (mounted to a heavy duty, fan-rated box). Also, when adding a circuit, you may exceed the legal fill for a box, so may choose to replace the box with a larger/deeper one. There are other times, these are just 2 examples.


Are sections of the structure sheaf of a scheme determined by their values at its closed points?

Question: This question got me thinking if it's true that for every commutative ring with $1$, $R$, we have that the structure sheaf of $X_{max}=MaxSpec R$ at a distinguished open set $D(f)$ is exactly $R_f$. As I don't know the answer for this, but do know it's true for $X=Spec R$ I tried the following approach:
Define the sections of the structure sheaves at an open set $U$ as functions $s:U\to\bigsqcup_{I\in U} A_I$, where $I$ is either a maximal or prime ideal depending on whether we're working in $MaxSpec$ or $Spec$, respectively, and we further require that these sections are locally a quotient.
I tried coming up with an isomorphism between $\mathcal{O}_{X_{max}}(D(f))\cong\mathcal{O}_X(D(f))$ or a counterexample. The isomorphism seems clearly true when $R$ is an integral domain, but is it still true in general? Clearly, given any open set $U$, every $s\in\mathcal{O}_X(U)$ induces a section in $\mathcal{O}_{X_{max}}(U)$, but how about the converse? Is every section of the structure sheaf of a scheme determined by its values in the closed points?
Here's my attempt to construct a counter example:
Consider $R$ not an integral domain with a unique maximal ideal $m$ containing at least another prime ideal $(0)\subsetneq p\subsetneq m$. Furthermore, assume there are two different elements $r,s\in R$ and some $0\neq f\in m-p$ such that $rf=sf=0$. Then, we further assume $\frac{r}{1}\neq\frac{s}{1}\in R_m-\{0\}$, and by construction they are both zero in $R_p$.
Therefore, $r$ and $s$ define different global sections of $\mathcal{O}_X$, but are both zero as sections of $\mathcal{O}_{X_{max}}$. In this way we conclude that both sheaves are different, so they must also differ in the basic open sets of the topology.
Is my reasoning correct?
Answer: Let $R$ be local domain (but not a field) and $0\neq f$ a non-unit.
If we work with the maximal spectrum, we have $D(f)=\emptyset$, i.e. there are no sections.
If we work over the prime spectrum, we have the familiar $\mathcal O_{\operatorname{Spec} R}(D(f))=R_f \neq 0$.

To understand whats going on here, you should take another look at the proof that $\mathcal O_{\operatorname{Spec} R}(D(f))=R_f$, for instance at Hartshorne. You will notice that the fact $\sqrt I = \bigcap\limits_{\mathfrak p \supset I} \mathfrak p$ is a crucial ingredient of the proof.
It turns out that you can actually take the same proof for the maximal spectrum if $\sqrt I = \bigcap\limits_{\mathfrak m \supset I} \mathfrak m$ (only running through maximal ideals) holds, i.e. if $R$ is a Jacobson ring (for example if $R$ is a finitely generated algebra over a field).
A local ring of positive dimension is of course not a Jacobson ring, thats how I came up with the counterexample.
Summarizing, the question whether $\mathcal O_{\operatorname{MaxSpec} R}(D(f))=R_f$ holds comes down to the question whether $R$ is a Jacobson ring. Being a domain or not is totally irrelevant. This should also answer your other question. There $R$ was a finitely generated $k$-algebra, i.e. everything is fine there.
Comment: Great, this is exactly the kind of answer I was looking for! However, I still have one question regarding the case of a general scheme. Does this mean that we can extend an arbitrary section of a scheme defined only in the closed points iff each affine open set of a cover is a Jacobson ring? Cheers.
Comment: What do you mean by defined in the closed points? Sections are defined on opem sets.
Comment: In other words I mean that if we know the values of a section of an open set  in an affine scheme then we can uniquely determine the whole section.
Comment: Restriction maps are injective for *integral* schemes. But closed points and Jacobson ring do not play any role there.
Comment: Great, thanks!${}$


File Access dates changed unexpectedly. Metadata crawler?

Question: Is it usual for file access dates (read dates) to change without human interaction? Which applies for all files under /home/myusername/ if I see that correctly but not for system files.
My personal files get a recent file access date that looks like the result of a batch processing, so multiple files at the same minute, although I didn't access them and I also didn't copy them at the file access date.
I noticed the behavior when I wanted to attach a file to an email and sorted by "Used recently" in the dialogue to choose a file more quickly. There are files listed that I didn't use at the specific date and time.
This behavior wasn't present on my system from the beginning, it was freshly installed (no upgrade) approx. 2 years ago.
The problem started a few weeks ago.
Does Ubuntu 20.04 LTS have some meta data crawler or daemon that processes files in batch mode and changes the read date of every file it accesses? Or do I have to worry that my system was compromised?
The file change dates remain untouched.
I'm sorry if this question is trivial but I didn't find anything specific on askubuntu or on the web concerning this problem (but I found much stuff on how to change file dates etc.)
Comment: It apparently happens for all file types in the same fashion (office files, image files, text files, pdf files, xml files) and it gets refreshed often (accessed usually the day I look for it).
Answer: It's not normal for personal files to change access date/time unless they are accessed somehow ... Although browsing a directory with some applications e.g. email client attach dialog might indeed change access date/time which is especially known for file-types like images and videos that are previewed as thumbnails.
However, who or what had accessed a certain file is not per se logged by default ... There might be traces in some specific applications' logs generally for system files and not personal files and that's it.
Bottom line is that unless you have auditing service on and active for a certain file/directory, there is no way for knowing who or what accessed the file.
You can setup auditing like so:
sudo apt install auditd

Then, start monitoring a file like so:
sudo auditctl -w /path/to/file

Or a directory(be careful with auditing directories as the logfile size might grow extremely large especially for Home) like so:
sudo auditctl -w /path/to/directory/

You can list currently audited files/directories entries like so:
sudo auditctl -l

and delete those entries like so:
sudo auditctl -W file/directory

The audit information will be written to the file:
/var/log/audit/audit.log

That you can view and search with e.g.:
grep "something" /var/log/audit/audit.log

or with e.g.:
ausearch --file "file-name"

and get reports with e.g.:
aureport

References:

man auditd - The Linux Audit daemon.
man auditctl - a utility to assist controlling the kernel's audit system.
man ausearch - a tool to query audit daemon logs.
man aureport - a tool that produces summary reports of audit daemon logs.
Comment: Thank you, I'm gonna try this.
Another strange thing I noticed: If I access some media with VLC player, the file access date of the particular file played doesn't get updated (played today, file access date yesterday). I checked the date with the gnome file manager, with ls -ul and stat.
Comment: Yesterday, I added some directories using 'sudo auditctl -w /path/to/directory/'

Today I searched for file changes via 'sudo aureport -f', but the timestamps that get displayed by aureport don't match the ones that I see via the file system (the same in Gnome file manager, 'ls -ul' and 'stat' commands). File system access date is today, aureport access date is yesterday.


How to handle json format error shows if the table is empty

Question: Am fetching values from a table, its working perfectly. When the table is empty am getting aler box json formating error. How can i handle that error?
my sql query is given below, am using php zend framework
public function getProductsAction(){

     $oProductModel = new Application_Model_Db_Table_Products();
     $oSelect = $oProductModel->fetchAllProductItems();

     echo Zend_Json::encode($this->_helper->DataTables($oSelect, array('product_id','e.ename as employee_name','name','brand','conditions','about','image_path','reserved_price','Max(b.bid_amount) as amount')));

}

and view page is
$(document).ready(function(){

    jQuery('#product-table').dataTable({
        <?php if(Qsm_User::isAdmin()){ ?>
            "sDom": 'Tlfrtip',
            "oTableTools": {
                "sSwfPath": "/js/DataTables/extras/TableTools/media/swf/copy_csv_xls_pdf.swf",
                "aButtons": [{
                        "sExtends":    "collection",
                        "sButtonText": 'Save ',
                        "aButtons":    [ "csv", "xls", "pdf" ]
                    }]
            },
       <?php } ?>
        "sPaginationType": "full_numbers",
        "bProcessing": true,
        "bServerSide": false,
        "sAjaxSource": '/buyproduct/api/get-products',

        "aoColumns": [
            {"sTitle":"ID", "bVisible":false},
            {"sTitle":"Emp Name", "bVisible":true},
            {"sTitle":"Product", "sWidth": '10%'},
            {"sTitle":"Brand", "sWidth": '10%'},
            {"sTitle":"Condition", "sWidth": '10%'},
            {"sTitle":"Description", "sWidth": '20%'},
            {"sTitle":"Image","sWidth": '18%',
             "mData": null,
             "bSearchable": false,
             "bSortable": false,
             "fnRender": function (oObj){
            var actions = "";
            actions += "\n\
             ";
                actions +="";
            return actions;
            }
            },
            {"sTitle":"Starting Bid Price", "sWidth": '10%'},
            {"sTitle":"Current Bid Price", "sWidth": '10%'},
            {
                "sTitle":"Bid",
                "sWidth": '17%',
                "mData": null,
                "bSearchable": false,
                "bSortable": false,
                "fnRender": function (oObj){
                    var actions = "";
                    actions += "\n\
                               ";
                    actions +="";
                    return actions;
                 }
            }
            <?php if(Qsm_User::isAdmin()){ ?>
            ,{
                "sTitle":"Transaction",
                "sWidth": '22%',
                "mData": null,
                "bSearchable": false,
                "bSortable": false,
                "fnRender": function (oObj){
                    var actions1 = "";
                    actions1 += "\n\
                                ";

                    actions1 +="";
                    return actions1;
                }
            }
            <?php } ?>
        ]
    });

});

Please anybody help me to handle this json formating error
Answer: your action will return empty string on no row condition which is invalid json data, Check the value returned from
$this->_helper->DataTables($oSelect, array('product_id','e.ename as employee_name','name','brand','conditions','about','image_path','reserved_price','Max(b.bid_amount) as amount'))

if null/or no rows echo something like this or empty row data
{
   "msg": "no-data"
}

Update:
public function getProductsAction(){

 $oProductModel = new Application_Model_Db_Table_Products();
 $oSelect = $oProductModel->fetchAllProductItems();
 if($oSelect){
    echo Zend_Json::encode($this->_helper->DataTables($oSelect, array('product_id','e.ename as employee_name','name','brand','conditions','about','image_path','reserved_price','Max(b.bid_amount) as amount')));
 }else{
    echo '{"msg": "no-data"}';  //or edit with empty data matching required by your view
 }
}

Comment: how to use this in my code, can you please explain where should i use this
Comment: for no row condition only am getting this error, when there is no data in table. So how to handle this json format error.
Comment: not sure of the data format returned by your helper class, if $oSelect is null on empty row condition use the above code in update:, you can also handle the empty row condition in your helper->DataTables
Comment: without checking whether the table is empty or not how we use if else condition?
Comment: is $oSelect is rowset or query?, could you share some code of $oProductModel->fetchAllProductItems(); and $this->_helper->DataTables  to know how the data is featched


Where to place login failed message in Twitter Boostrap

Question: This is a basic question from a programmer who would like to get the design 'right'.
In the example Twitter Bootstrap, where would you place the 'failed login attempt' message?
Here's a link to the basic example, http://getbootstrap.com/examples/jumbotron/, with the login for top right.
It seems to me the options are:

In a javascript alert, but this requires additional user clicks
In a new page (after redirect), but this seems unnecessarily complex
Beneath the login form (in the header).  This seems the most natural place to put it, but would mean increasing the height of the header for a single element

I guess the question is... Where would Mark Otto put it?
Sorry if this is not very relevant.
Answer: How about something like this. This makes it clear what went wrong (well, not my dummy text) and does not get in the way of the two fields or the input button. I am using a tooltip for the error message.

download bmml source – Wireframes created with Balsamiq Mockups
Comment: I agree with this solution, although for security reasons I wouldn't show which input is the wrong one (I'd show the dialog below the button instead).
Answer: If you're not going to indicate which field is the source of the error, I would recommend doing a more global style alert above the header in fact. Also, make sure the error messaging is friendly, and clearly describes what happened and how to recover from the error. Also provide a forgot your password link in the message.
Something like this:

We're sorry, it seems the email password combination you entered is incorrect. Please try again. Forgot your password?


Beginner question gets 29 upvotes

Question: Why is this a checkmate?
It seems there's some arbitrage problem with these kinds of questions. Ostensibly, I could just pretend to be a beginner and then ask beginner questions like these and instantly attract 25 upvotes within a few days.
Are these kinds of questions really ok? If so, then should these kinds of questions really be ok? I think of making certain new questions or FAQs off-topic to prevent these kinds of things. r/chess has a "Helpful Links" part in the sidebar.
I mean, I have nothing against n00bs or anything, but what's to stop me or anyone from pretending to be a beginner and posting all these easily answered questions about basic things like pins or checkmates? I could even say I reached a stalemate (without using the term stalemate) and wonder the lone king can't move. I'll even make sure to use an image instead of FEN/PGN.
Some food for thought, I guess.
One idea came to mind as I finished typing all this. Perhaps migrate to the Board Games SE if it's too much of a beginner question. I was thinking it would be something a little (A LITTLE) like MathOverflow and Math.SE (not the best analogy which is why I emphasised 'little').
By the way, here is another example, but this time to do with etiquette/ethics/rules rather than actual gameplay.
Comment: Do it. On Arqade I asked a pretty easy question of what a well known gaming term referred to, and got 20+ votes from it. Not only is it easy rep, but you re helping out those people who "don't know what they don't know."
Comment: I think those kind of posts should be simply downvoted (but I see you only have 5 downvotes right now). By the way, if you want some ideas, ask "what is this weird pawn capture?" and add a JPG screenshot from your cellphone of an en-passant, or "rook and king moving at the same time" for a castling move :)
Comment: If someone asks a basic question that is useful to other people who cares if they're getting their reputation inflated with that?
Comment: @PausePause LOL ok thanks!
Comment: known issue...beginners are an over-represented demographic in this SE (as compared to other chess-focused communities): https://chess.meta.stackexchange.com/a/251/46
Comment: @PausePause "why is this [particular position] a mate?" is not helpful, reusable, searchable knowledge in the same way that "what is head bobbing?" is
Answer:
I could just pretend to be a beginner and then ask beginner questions like these and instantly attract 25 upvotes within a few days.

This beginner got lucky; the question became a Hot Network Question. Likely because it attracted more than one answer (which IMHO wasn't really necessary in this case) and everybody with a bit of chess knowledge, including visitors normally only active on other Stack Exchange sites, can verify the correctness and upvote because of the association bonus. Many consider this a flaw of the Hot Network Question list, there's quite a bit of discussion on Meta Stack Exchange.

Are these kinds of questions really ok?

Yes.

Questions that have to do primarily with chess in its standard form are on-topic here. This includes questions about theory, rules, specific positions/games (including puzzles), chess-specific events, chess players, hard facts such as statistics and other historical data, and physical items such as chessboards, pieces, and clocks.

(emphasis mine)
Chess Stack Exchange doesn't see much questions per day or traffic, so we don't have the luxury to rashly close questions which (to experienced chess players) may seem to lack research. Rather, we should put some energy in them to edit into decent shape. Of course, there are still questions for which there is no hope at all and should be closed, but 'too basic' has never been a close reason here, unlike e.g. on History Stack Exchange.
It seems that you think it's unfair that some well-researched or interesting questions or answers get much less attention than (some) basic ones like this. Well, that has been known for more than 10 years and nobody found a good solution yet. I guess it's the same kind of issue where a simple novel written for the masses (50 shades of a certain color) is way more profitable than a true literary masterpiece.
Comment: "which (to experienced chess players) may seem to lack research" -- to be honest, you don't need to be an _experienced_ chess player to judge that that question lacks research. Just knowing the rules is enough. (source: I'm not even a chess player, let alone experienced.) The question even mentions a proposed counter-move, but apparently they hadn't bothered to actually make the move and look at the board position after it... Sometimes I wonder if the association bonus should permit downvotes too, just for things like this. I know I would use that option.
Comment: I think I was the 3rd or 4th answer on this and tbh it did feel necessary, because at the time all of the answers were using basically "it's pinned" which is useless if you don't already know what a pin is, as I doubt the asker did. Getting 78 upvotes for an explanation of basic rules is pretty absurd though.
Comment: 'Chess Stack Exchange doesn't see much questions per day or traffic' --> AAAAAAAAAAHHHHHHHHHHHHHHHHHHHHHH so that's the thing! you don't want to close these kinds of things FOR NOW because (or partly because) of your low number of questions? XD XD but in the future YOU MAY consider closing (with an amendment of rules) if, say, chesse gets as many posts per day as maths se?
Comment: As I said earlier in [this meta answer](https://chess.meta.stackexchange.com/a/578/12957), justifying bad questions just because there are 'not enough' questions per day here seems a bad idea to me.
Comment: the low posts per day thingy applies here as well? https://chess.meta.stackexchange.com/questions/950/should-questions-feature-computer-analysis-whenever-relevant and even here? https://chess.meta.stackexchange.com/questions/948/whether-or-not-images-instead-of-fen-pgn-are-allowed
Comment: 'It seems that you think it's unfair that some well-researched or interesting questions or answers get much less attention than (some) basic ones like this.' --> part 1. ok i've read the link succeeding and it's very interesting. i've even followed other links. and if that's how i came off - like kinda jealous or something - that's not what i intended.
Comment: part 2. my intention is absolute, not relative. it's to do with gaming the system in that i could ask any damn beginner question i want, get a lot of upvotes and therefore have enough rep to set bounties. i don't really care that my questions are not getting upvoted enough or anything. so...it's like i'm evil. but i'm not shallow/jealous evil. i'm manipulative (of the reputation/rules/bounty) evil. (this is last part a joke to be clear. i don't really - necessarily - intend to waste  time posting beginner questions just to be able to set bounties)
Comment: @ilkkachu yes, being able to downvote with the association bonus would probably help. [I've found another solution.](https://stackexchange.com/users/6085540/glorfindel?tab=accounts)
Comment: @FedericoPoloni trolololol. of course i agree with you. i just think the mods/admins should admit that's what they're doing if that's what they're doing. thanks for commenting.
Comment: @ilkkachu thanks for commenting. i upvoted your comment, but i don't think the question should be downvoted though. in this case, i think it's more like hate the game not the player. if the site doesn't have a rule, then well why downvote the player?
Answer: Don't worry about it. It is largely self-correcting.
Numerical rep is only correlated with the reputation that really matters: the respect of knowledgeable community members. Posting a lot of overly basic questions might give a person an initial boost, but they will rapidly hit a ceiling if they stick to such a strategy (since those upvoting basic questions from a new user are less likely to upvote it for more established users) and they won't gain the sort of reputation that really means anything.
Comment: @BCLC You'll notice that many (not all, of course) of those askers are one-time users, they ask and go away for good, and don't care of acknowledging an answer. They couldn't care less about reputation or how much effort they put before asking.
Comment: thanks. the rep doesn't have to mean anything. the rep could be for bounty. is your answer still the same after i mention this?
Comment: @BCLC I'm not completley sure what you are getting at. I haven't seen a lot of overly basic questions (of the "why am I in checkmate"? sort)  that have had a bounty attached to them. But even if there were, I would stand by my answer. Rep is an imperfect measure of what is actually important. Some people can game the system, but so what? There is a limit to how far they will get if they do so (it is safe to say that almost everyone over 10k has earned it) and even if they could, they are just winning at a game which is more boring than chess.
Comment: i mean if i ask a beginner question and gain say 50 points from it, then it's like i can set a bounty on other or future questions i, resp, have or would have. meanwhile, i did not  really or necessarily contribute anything to the site. seems like arbitrage, rent-seeking or something

Beginner question gets 29 upvotes