问:
Difference between [[NSDate date] retain] and [[NSDate alloc] init]
As both of the following serves the same purpose,

```<code>today = [[NSDate date] retain];
</code>```

and

```<code>today = [[NSDate alloc] init];
</code>```

Then what's the difference between them?

Does anything here is related to memory allocation methods or something else is the reason for using them accordingly.

答:
[NSDate date] is a convenience constructor using which you can leave the headache of releasing the object to autorelease pool. Sending a retain message to the convenience constructor like [[NSDate date] retain] makes you the owner of the object and you are responsible for releasing it properly.

[[NSDate alloc] init] is the default initializer by which you become the owner of the object, which is almost equal to [[NSDate date] retain].

Body:
As both of the following serves the same purpose,

today = [[NSDate date] retain];

and

today = [[NSDate alloc] init];

Then what's the difference between them?

Does anything here is related to memory allocation methods or something else is the reason for using them accordingly.


来源: stackexchange

问:
findViewById(R.id.deleteButton) must not be null in kotlin
I'm attempting to create a button called "delete" in a flashcard application that will delete flashcards the user does not need. However, whenever I attempt to implement this button, I get the error "findViewById(R.id.deleteButton) must not be null". Normally I would have a gridview that would display my flashcard sets, and if I clicked on any of the sets, it would lead me to the flashcards in the set. Now that I've tried to implement a "delete" button inside of my flashcard activity (the activity that activates when i click on the flashcard sets), the android emulator crashes whenever I click on my flashcard sets.

.kt code:

```<code>class FlashcardSetDetailActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_linear)

    val recyclerLinear =
findViewById<RecyclerView>(R.id.recyclerLinear)
    recyclerLinear.adapter = AdapterLinear(Flashcard.getHardcodedFlashcards())

    val deleteButton: Button = findViewById(R.id.deleteButton)

    deleteButton.setOnClickListener() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        }
    }
}
</code>```

my xml code is the following:

```<code><TextView
    android:id="@+id/my_textLinear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black"
    android:textSize="24sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/my_textLinear2"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent" />

<TextView
    android:id="@+id/my_textLinear2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:textColor="@color/black"
    android:textSize="24sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/my_textLinear"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/deleteButton"
    android:layout_width="157dp"
    android:layout_height="88dp"
    android:text="Delete"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="1.0" />
</code>```

</androidx.constraintlayout.widget.ConstraintLayout>

Ignore the textviews. They just display my the title and the description of my flashcards. My button is what does not work. Can Somebody please help me with this error? Thanks.

答: I suggest you use view binding because it is null-safe and also type-safe. Because I was also facing this issue then I am started to use view binding it is easy and the main point is it replaces findViewById()</p>

ContentLicense: CC BY-SA 4.0

Body:
I'm attempting to create a button called "delete" in a flashcard application that will delete flashcards the user does not need. However, whenever I attempt to implement this button, I get the error "findViewById(R.id.deleteButton) must not be null". Normally I would have a gridview that would display my flashcard sets, and if I clicked on any of the sets, it would lead me to the flashcards in the set. Now that I've tried to implement a "delete" button inside of my flashcard activity (the activity that activates when i click on the flashcard sets), the android emulator crashes whenever I click on my flashcard sets.

.kt code:

class FlashcardSetDetailActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_linear)

    val recyclerLinear =
findViewById<RecyclerView>(R.id.recyclerLinear)
    recyclerLinear.adapter = AdapterLinear(Flashcard.getHardcodedFlashcards())

    val deleteButton: Button = findViewById(R.id.deleteButton)

    deleteButton.setOnClickListener() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        }
    }
}

my xml code is the following:

<TextView
    android:id="@+id/my_textLinear"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textColor="@color/black"
    android:textSize="24sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintEnd_toStartOf="@+id/my_textLinear2"
    app:layout_constraintHorizontal_bias="0.5"
    app:layout_constraintStart_toStartOf="parent" />

<TextView
    android:id="@+id/my_textLinear2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:textColor="@color/black"
    android:textSize="24sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/my_textLinear"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/deleteButton"
    android:layout_width="157dp"
    android:layout_height="88dp"
    android:text="Delete"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="1.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

Ignore the textviews. They just display my the title and the description of my flashcards. My button is what does not work. Can Somebody please help me with this error? Thanks.


问:
Cannot import or install pandas-profiling in Jupyter Notebook
I have technically already installed pandas-profiling using

pip install pandas-profiling

But when I try to import it, I get the following error:

```<code>import numpy as np
import pandas as pd
import pandas_profiling
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-1-e1a23f2a6f04> in <module>()
  1 import numpy as np
  2 import pandas as pd
  3 import pandas_profiling

  ModuleNotFoundError: No module named 'pandas_profiling'
</code>```

First Error Image

So I tried installing it in Jupyter Notebook and got the following error as well:

```<code>import sys
!{sys.executable} -m pip install pandas-profiling

 Collecting pandas-profiling
 Could not find a version that satisfies the requirement pandas-profiling
 (from versions: )
 No matching distribution found for pandas-profiling
</code>```

Second Error Image

I am also unable to install it using conda for both as I am unable to establish a connection to conda.anaconda.org for some reason.

答:
From Anaconda Prompt:

conda install -c conda-forge pandas-profiling

Body:
I have technically already installed pandas-profiling using

pip install pandas-profiling

But when I try to import it, I get the following error:

import numpy as np
import pandas as pd
import pandas_profiling
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-1-e1a23f2a6f04> in <module>()
  1 import numpy as np
  2 import pandas as pd
  3 import pandas_profiling

  ModuleNotFoundError: No module named 'pandas_profiling'

First Error Image

So I tried installing it in Jupyter Notebook and got the following error as well:

import sys
!{sys.executable} -m pip install pandas-profiling

 Collecting pandas-profiling
 Could not find a version that satisfies the requirement pandas-profiling
 (from versions: )
 No matching distribution found for pandas-profiling

Second Error Image

I am also unable to install it using conda for both as I am unable to establish a connection to conda.anaconda.org for some reason.


问:
why it is so difficult to make tensorflow work?
Over the years, I always stumbled with the installation of tensorflow. I really love this library but at the same time, I also really hate it because it is so difficult to make it work. I can install it but I always have an error when running it. Can anyone make it easy to install and make it work considering it is so popular?

I spend almost the whole day today figuring out the installation issue with tensorflow. This morning I got a conflict issue with scipy, DLL stuff which I posted it twice already from last night.

failed to install tensorflow with a lot of package conflicts

statsmodels: ImportError: DLL load failed while importing _arpack: The specified procedure could not be found

I eventually decided to start from scratch and create new environments with python 3.6.10 and then installed tensorflow first, then added matplotlib, pandas, statsmodels, etc.  I am still stuck now

```<code>File "C:\Users\test\miniconda3\envs\dash36\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.estimator'
</code>```

then I tried to print a version of tensorflow-estimator to see conflict. and I got another error.

```<code>>>> import tensorflow-estimator
  File "<stdin>", line 1
    import tensorflow-estimator
SyntaxError: invalid syntax
</code>```

can anyone please help me with the installation of tensorflow? could you please tell me which python version, tensorflow version, numpy/scipy version, scikit-learn version? I am going to work with plotly dash. which dash version also works with tensorflow?

Thank you so much

答:
Try creating new virtual environment using Python and install Tensorflow.</p>
```<code>#Create virtual env called venv
python -m venv --system-site-packages .\venv
#Activate venv
.\venv\Scripts\activate
#Upgrade pip
pip install --upgrade pip
#Install latest Tensorflow version: Current latest version 2.8
pip install --upgrade tensorflow
#Verify the install:
python -c "import tensorflow as"
</code>```

Body:
Over the years, I always stumbled with the installation of tensorflow. I really love this library but at the same time, I also really hate it because it is so difficult to make it work. I can install it but I always have an error when running it. Can anyone make it easy to install and make it work considering it is so popular?

I spend almost the whole day today figuring out the installation issue with tensorflow. This morning I got a conflict issue with scipy, DLL stuff which I posted it twice already from last night.

failed to install tensorflow with a lot of package conflicts

statsmodels: ImportError: DLL load failed while importing _arpack: The specified procedure could not be found

I eventually decided to start from scratch and create new environments with python 3.6.10 and then installed tensorflow first, then added matplotlib, pandas, statsmodels, etc.  I am still stuck now

File "C:\Users\test\miniconda3\envs\dash36\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked
ModuleNotFoundError: No module named 'tensorflow_core.estimator'

then I tried to print a version of tensorflow-estimator to see conflict. and I got another error.

>>> import tensorflow-estimator
  File "<stdin>", line 1
    import tensorflow-estimator
SyntaxError: invalid syntax

can anyone please help me with the installation of tensorflow? could you please tell me which python version, tensorflow version, numpy/scipy version, scikit-learn version? I am going to work with plotly dash. which dash version also works with tensorflow?

Thank you so much

Body:
Try creating new virtual environment using Python and install Tensorflow.

#Create virtual env called venv
python -m venv --system-site-packages .\venv
#Activate venv
.\venv\Scripts\activate
#Upgrade pip
pip install --upgrade pip
#Install latest Tensorflow version: Current latest version 2.8
pip install --upgrade tensorflow
#Verify the install:
python -c "import tensorflow as"


问:
Jest Mock an an error thrown and get the actual error from the catch
In code below I'm trying to test method getParameter for failure. Module A contains the method to test.

Module A.spec contains the test. Problem is that the test always passes, meaning it never hiuts the catch. I am mocking AWS.SSM to fail. What am I missing here?

Module A:

```<code>const AWS = require ('aws-sdk')
exports.getParameter = async function (parameterName) {
    const params = {
        Name: parameterName,
        WithDecryption: true
    };
    const ssm = new AWS.SSM();
    try {
        const paramValue = await ssm.getParameter(params).promise();
        return paramValue.Parameter.Value;
    }
    catch (e) {
        console.log(e);
        throw new Error('Error while retrieving parameter value from pstore.\n' + e);
    }
};

exports.AWS = AWS
</code>```

Module A.spec.js

```<code>  const prm = require('A')

  test('should handle error', () => {
      prm.AWS.SSM = jest.fn().mockImplementation(() => {
         throw new Error()
      })
    prm.getParameter = jest.fn()
    try{
      prm.getParameter("abc")
    }
   catch(e)
   {
     console.log(e)
   }
 });
</code>```

答:
You can use jest.spyOn(prm.AWS, 'SSM').mockReturnValue() to mock the SSM constructor and its instance.

E.g.

a.js:

const AWS = require('aws-sdk');

exports.getParameter = async function (parameterName) {
  const params = {
    Name: parameterName,
    WithDecryption: true,
  };
  const ssm = new AWS.SSM();
  try {
    const paramValue = await ssm.getParameter(params).promise();
    return paramValue.Parameter.Value;
  } catch (e) {
    console.log(e);
    throw new Error('Error while retrieving parameter value from pstore.\n' + e);
  }
};

exports.AWS = AWS;
```
<p><code>a.spec.js</code>:</p>
<pre class="lang-js prettyprint-override"><code>const prm = require('./a');

describe('71027434', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  test('should get parameter value', async () => {
    const ssm = {
      getParameter: jest.fn().mockReturnThis(),
      promise: jest.fn().mockResolvedValueOnce({ Parameter: { Value: 'fake value' } }),
    };
    const SSMSpy = jest.spyOn(prm.AWS, 'SSM').mockReturnValue(ssm);
    const actual = await prm.getParameter('abc');
    expect(actual).toEqual('fake value');
    expect(SSMSpy).toBeCalledTimes(1);
    expect(ssm.getParameter).toBeCalledWith({ Name: 'abc', WithDecryption: true });
  });

  test('should handle error', async () => {
    const mError = new Error('network');
    const ssm = {
      getParameter: jest.fn().mockReturnThis(),
      promise: jest.fn().mockRejectedValueOnce(mError),
    };
    const SSMSpy = jest.spyOn(prm.AWS, 'SSM').mockReturnValue(ssm);
    await expect(prm.getParameter('abc')).rejects.toThrowError(
      'Error while retrieving parameter value from pstore.\n' + mError
    );
    expect(SSMSpy).toBeCalledTimes(1);
    expect(ssm.getParameter).toBeCalledWith({ Name: 'abc', WithDecryption: true });
  });
});
</code>```

Test result:

 PASS  stackoverflow/71027434/a.spec.js (8.108 s)
  71027434
    ✓ should get parameter value (4 ms)
    ✓ should handle error (23 ms)

  console.log
    Error: network
        at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/stackoverflow/71027434/a.spec.js:20:20
        at Generator.next (<anonymous>)
        at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/stackoverflow/71027434/a.spec.js:8:71
        at new Promise (<anonymous>)
        at Object.<anonymous>.__awaiter (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/stackoverflow/71027434/a.spec.js:4:12)
        at Object.<anonymous> (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/stackoverflow/71027434/a.spec.js:19:42)
        at Object.asyncJestTest (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:106:37)
        at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:45:12
        at new Promise (<anonymous>)
        at mapper (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:28:19)
        at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:75:41

      at Object.<anonymous> (stackoverflow/71027434/a.js:13:13)
          at Generator.throw (<anonymous>)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 a.js     |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        8.623 s, estimated 10 s
```
<p>package version:</p>
<pre class="lang-json prettyprint-override"><code>"aws-sdk": "^2.875.0",
"jest": "^26.6.3",
</code>```

Body:
In code below I'm trying to test method getParameter for failure. Module A contains the method to test.

Module A.spec contains the test. Problem is that the test always passes, meaning it never hiuts the catch. I am mocking AWS.SSM to fail. What am I missing here?

Module A:

const AWS = require ('aws-sdk')
exports.getParameter = async function (parameterName) {
    const params = {
        Name: parameterName,
        WithDecryption: true
    };
    const ssm = new AWS.SSM();
    try {
        const paramValue = await ssm.getParameter(params).promise();
        return paramValue.Parameter.Value;
    }
    catch (e) {
        console.log(e);
        throw new Error('Error while retrieving parameter value from pstore.\n' + e);
    }
};

exports.AWS = AWS

Module A.spec.js

  const prm = require('A')

  test('should handle error', () => {
      prm.AWS.SSM = jest.fn().mockImplementation(() => {
         throw new Error()
      })
    prm.getParameter = jest.fn()
    try{
      prm.getParameter("abc")
    }
   catch(e)
   {
     console.log(e)
   }
 });

Body:
You can use jest.spyOn(prm.AWS, 'SSM').mockReturnValue() to mock the SSM constructor and its instance.

E.g.

a.js:

const AWS = require('aws-sdk');

exports.getParameter = async function (parameterName) {
  const params = {
    Name: parameterName,
    WithDecryption: true,
  };
  const ssm = new AWS.SSM();
  try {
    const paramValue = await ssm.getParameter(params).promise();
    return paramValue.Parameter.Value;
  } catch (e) {
    console.log(e);
    throw new Error('Error while retrieving parameter value from pstore.\n' + e);
  }
};

exports.AWS = AWS;

a.spec.js:

const prm = require('./a');

describe('71027434', () => {
  afterEach(() => {
    jest.restoreAllMocks();
  });
  test('should get parameter value', async () => {
    const ssm = {
      getParameter: jest.fn().mockReturnThis(),
      promise: jest.fn().mockResolvedValueOnce({ Parameter: { Value: 'fake value' } }),
    };
    const SSMSpy = jest.spyOn(prm.AWS, 'SSM').mockReturnValue(ssm);
    const actual = await prm.getParameter('abc');
    expect(actual).toEqual('fake value');
    expect(SSMSpy).toBeCalledTimes(1);
    expect(ssm.getParameter).toBeCalledWith({ Name: 'abc', WithDecryption: true });
  });

  test('should handle error', async () => {
    const mError = new Error('network');
    const ssm = {
      getParameter: jest.fn().mockReturnThis(),
      promise: jest.fn().mockRejectedValueOnce(mError),
    };
    const SSMSpy = jest.spyOn(prm.AWS, 'SSM').mockReturnValue(ssm);
    await expect(prm.getParameter('abc')).rejects.toThrowError(
      'Error while retrieving parameter value from pstore.\n' + mError
    );
    expect(SSMSpy).toBeCalledTimes(1);
    expect(ssm.getParameter).toBeCalledWith({ Name: 'abc', WithDecryption: true });
  });
});

Test result:

 PASS  stackoverflow/71027434/a.spec.js (8.108 s)
  71027434
    ✓ should get parameter value (4 ms)
    ✓ should handle error (23 ms)

  console.log
    Error: network
        at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/stackoverflow/71027434/a.spec.js:20:20
        at Generator.next (<anonymous>)
        at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/stackoverflow/71027434/a.spec.js:8:71
        at new Promise (<anonymous>)
        at Object.<anonymous>.__awaiter (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/stackoverflow/71027434/a.spec.js:4:12)
        at Object.<anonymous> (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/stackoverflow/71027434/a.spec.js:19:42)
        at Object.asyncJestTest (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/jasmineAsyncInstall.js:106:37)
        at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:45:12
        at new Promise (<anonymous>)
        at mapper (/Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:28:19)
        at /Users/dulin/workspace/github.com/mrdulin/jest-v26-codelab/node_modules/jest-jasmine2/build/queueRunner.js:75:41

      at Object.<anonymous> (stackoverflow/71027434/a.js:13:13)
          at Generator.throw (<anonymous>)

----------|---------|----------|---------|---------|-------------------
File      | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
----------|---------|----------|---------|---------|-------------------
All files |     100 |      100 |     100 |     100 |
 a.js     |     100 |      100 |     100 |     100 |
----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        8.623 s, estimated 10 s

package version:

"aws-sdk": "^2.875.0",
"jest": "^26.6.3",


问:
Emacs program to collapse Json to single line
I'm dealing with a file that has a list of single line json strings. To edit an individual json object, I found this tool: https://github.com/gongo/json-reformat. Now, I'm looking for the reverse operation: given a nicely formatted Json object, collapse it into a single string.

Emacs version: 24.5.1

答:
The standard json module that comes with current versions of emacs (since 24.4?) has a json-pretty-print function that normally wraps the JSON in a region, but when given a prefix argument minimizes it instead.

So, select the region containing the JSON to minimize and type, C-u M-x json-pretty-print.

This is better than the previous answers because it understands that whitespace inside strings should be untouched.

ContentLicense: CC BY-SA 3.0


问:
Best online resource to learn Python?
I am new to any scripting language. But, Still I worked on scripting a bit like tailoring other scripts to work for my purpose. For me, What is the best online resource to learn Python?

[Response Summary:]

Some Online Resources:

 http://docs.python.org/tut/tut.html - Beginners

    http://diveintopython3.ep.io/     - Intermediate

http://www.pythonchallenge.com/     - Expert Skills

http://docs.python.org/             - collection of all knowledge

Some more:

 A Byte of Python.

Python 2.5 Quick Reference

Python Side bar

A Nice blog for beginners

Think Python: An Introduction to Software Design

答: The Cookbook is absolutely essestial if you want to know idiomatic python.</p>

OwnerDisplayName: Sreenath

Title: Best online resource to learn Python?

LastEditorDisplayName: Sreenath

ContentLicense: CC BY-SA 2.5


问:
Regex, php : how to negate a capturing parentheses
I want to analyse a mysql request with a php regex,
that is, extract the select_expr and the table_references from a mysql statement.
For example, here are two mysql queries that I would like my regex to match :

```<code>select id, name from table

select id, name
</code>```

From that query I would like to extract 2 parts : the "id, name" information and the "table" information too.

The first part can actually contain a string like CONCAT('id','.','nom') AS alias,

and the second part can look like : table t INNER JOIN table2 t2 ON t.id=t2.user_id.

So I tried this "I know it's not working but will get me on the road" regex :

```<code>'!select (.*)( from (.*))?!i'
</code>```

And of course, the first capturing parentheses get all until the end, which is not what I want.

In the

```<code>select id, name from table
</code>```

string, it matches "id, nom from table" as the first part, which is not what I want.
(I want "id, nom" as the first part and "table" as the second in this case).

What I would like to do from this point is to tell the regex that the first capturing parentheses
should not match the " from " sequence if founded.
I know there is the negated character class feature, [^a-z],
but that just negate one character and not a whole string (as a sequence of letters in the right order).

Do you have any lights on this ?
Can we negate the content of parentheses for example with regex ?

答:
The problem is that you use greedy matching. That is, your first .* group matches characters until the rest of your regex breaks. Since the FROM clause is made optional, it never happens and your first group just matches everything. The solution is to use non-greedy matching, by adding a ? after the * (it also works for +).

```<code>'!select (.*?)( from (.*))?!i'
</code>```

It should be enough for your simple case. If you want to parse a whole query, though, it's actually much, much easier to parse SQL statements backwards. For instance, let's have a fully-featured SQL query:

```<code>SELECT foo FROM bar WHERE cond GROUP BY col HAVING stuff ORDER BY this
</code>```

If you strrev it, you get:

```<code>siht YB REDRO ffuts GNIVAH loc YB PUORG dnoc EREHW rab MORF oof TCELES
</code>```

With that in mind, you can easily split it with a regex, without ending with a LISPesque amount of stacked parentheses. Here's a commented regex I made to match such a string (you would need to put it back on a single line with no whitespaces).

```<code>^ // match the beginning
    (.+\s+YB\s*REDRO)?\s* // is there an ORDER BY?
    (.+\s+GNIVAH)?\s* // is there a HAVING?
    (.+\s+YB\s*PUORG)?\s* // is there a GROUP BY?
    (.+\s+EREHW)?\s* // is there a WHERE?
    (.+\s+MORF)?\s* // is there a FROM?
    .+\s+TCELES // there is a SELECT
$ // match the end
</code>```

Now, all you have to do is strrev back your results, and voilà! you got a well-split query.

EDIT We can use non-capturing groups and named groups to enhance the regex. Right now, we get the individual clauses through the matches; that is, they start with a keyword. Without the keyword, it would get pretty confusing to tell what's what in the capture groups. Named groups help solve this problem.

Non-capturing groups are groups that don't appear in the regex results. They start with ?:, and they're useful to make a block optional (like (?:stuff here)?) without having to deal with it in the results.

Here's the new regex. I've also just learned about the x modifier which makes PCRE ignore whitespaces and accept comments inside regexes, so let's use that to make a valid snippet.

```<code>$regex = "/^
    (?:(?<orderby>.+)\s+YB\s*REDRO)?\s* # is there an ORDER BY?
    (?:(?<having>.+)\s+GNIVAH)?\s*      # is there a HAVING?
    (?:(?<groupby>.+)\s+YB\s*PUORG)?\s* # is there a GROUP BY?
    (?:(?<where>.+)\s+EREHW)?\s*        # is there a WHERE?
    (?:(?<from>.+)\s+MORF)?\s*          # is there a FROM?
    (?<select>.+)\s+TCELES              # there is a SELECT
$/msix";

$query = "SELECT foo FROM bar WHERE cond GROUP BY col HAVING stuff ORDER BY this";

preg_match($regex, strrev($query), $matches);
foreach ($matches as &$match)
    $match = strrev($match);

// now we can use $matches['from'] to get the FROM clause
echo $matches['from'];

print_r($matches);
</code>```

Body:
I want to analyse a mysql request with a php regex,
that is, extract the select_expr and the table_references from a mysql statement.
For example, here are two mysql queries that I would like my regex to match :

select id, name from table

select id, name

From that query I would like to extract 2 parts : the "id, name" information and the "table" information too.

The first part can actually contain a string like CONCAT('id','.','nom') AS alias,

and the second part can look like : table t INNER JOIN table2 t2 ON t.id=t2.user_id.

So I tried this "I know it's not working but will get me on the road" regex :

'!select (.*)( from (.*))?!i'

And of course, the first capturing parentheses get all until the end, which is not what I want.

In the

select id, name from table

string, it matches "id, nom from table" as the first part, which is not what I want.
(I want "id, nom" as the first part and "table" as the second in this case).

What I would like to do from this point is to tell the regex that the first capturing parentheses
should not match the " from " sequence if founded.
I know there is the negated character class feature, [^a-z],
but that just negate one character and not a whole string (as a sequence of letters in the right order).

Do you have any lights on this ?
Can we negate the content of parentheses for example with regex ?

Body:
The problem is that you use greedy matching. That is, your first .* group matches characters until the rest of your regex breaks. Since the FROM clause is made optional, it never happens and your first group just matches everything. The solution is to use non-greedy matching, by adding a ? after the * (it also works for +).

'!select (.*?)( from (.*))?!i'

It should be enough for your simple case. If you want to parse a whole query, though, it's actually much, much easier to parse SQL statements backwards. For instance, let's have a fully-featured SQL query:

SELECT foo FROM bar WHERE cond GROUP BY col HAVING stuff ORDER BY this

If you strrev it, you get:

siht YB REDRO ffuts GNIVAH loc YB PUORG dnoc EREHW rab MORF oof TCELES

With that in mind, you can easily split it with a regex, without ending with a LISPesque amount of stacked parentheses. Here's a commented regex I made to match such a string (you would need to put it back on a single line with no whitespaces).

^ // match the beginning
    (.+\s+YB\s*REDRO)?\s* // is there an ORDER BY?
    (.+\s+GNIVAH)?\s* // is there a HAVING?
    (.+\s+YB\s*PUORG)?\s* // is there a GROUP BY?
    (.+\s+EREHW)?\s* // is there a WHERE?
    (.+\s+MORF)?\s* // is there a FROM?
    .+\s+TCELES // there is a SELECT
$ // match the end

Now, all you have to do is strrev back your results, and voilà! you got a well-split query.

EDIT We can use non-capturing groups and named groups to enhance the regex. Right now, we get the individual clauses through the matches; that is, they start with a keyword. Without the keyword, it would get pretty confusing to tell what's what in the capture groups. Named groups help solve this problem.

Non-capturing groups are groups that don't appear in the regex results. They start with ?:, and they're useful to make a block optional (like (?:stuff here)?) without having to deal with it in the results.

Here's the new regex. I've also just learned about the x modifier which makes PCRE ignore whitespaces and accept comments inside regexes, so let's use that to make a valid snippet.

$regex = "/^
    (?:(?<orderby>.+)\s+YB\s*REDRO)?\s* # is there an ORDER BY?
    (?:(?<having>.+)\s+GNIVAH)?\s*      # is there a HAVING?
    (?:(?<groupby>.+)\s+YB\s*PUORG)?\s* # is there a GROUP BY?
    (?:(?<where>.+)\s+EREHW)?\s*        # is there a WHERE?
    (?:(?<from>.+)\s+MORF)?\s*          # is there a FROM?
    (?<select>.+)\s+TCELES              # there is a SELECT
$/msix";

$query = "SELECT foo FROM bar WHERE cond GROUP BY col HAVING stuff ORDER BY this";

preg_match($regex, strrev($query), $matches);
foreach ($matches as &$match)
    $match = strrev($match);

// now we can use $matches['from'] to get the FROM clause
echo $matches['from'];

print_r($matches);


答: According to your code above, your delete button is defined on your flashcard page. And there is no delete button in your activity_linear.xml, so you got an error. You need to implement this button in your Flashcard adapter.</p>

Title: findViewById(R.id.deleteButton) must not be null in kotlin


问:
K8s Node allocatable not taking in account pod resources
I am making some tests, and I believe I may be misunderstanding how "allocatable" work.
I have 2 nodes running on Azure-AKS, both with Memory capacity of 65 Gi, and nothing but some basic daemon running on them.
When describing these nodes, I have for both about 59 Gi memory "allocatable".

Then I start a new pod, with a resources request and limit of 30Gi on one of these node. In practice, the pod use just a couple of Mo.
I would be expecting the "allocatable" to reduce to 29 Gi, but it stays at  59 Gi.

If I am doing a describe, the "allocated" section will correctly display what I actually requested.

```<code>Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource                       Requests       Limits
  --------                       --------       ------
   memory                         31190Mi (53%)  32170Mi (55%)
   ....

</code>```

But not the allocatable:

```<code>Allocatable:
  attachable-volumes-azure-disk:  16
  cpu:                            7820m
  ephemeral-storage:              119716326407
  hugepages-1Gi:                  0
  hugepages-2Mi:                  0
  memory:                         59350320Ki
  pods:                           30

</code>```

So, is allocatable supposed to take in account the requested resources of the pod ?

If yes, why is the value not decreasing here?

If no, how can I know what is the total amount of request/limit on one specific node (in a parsable format, such as json) ?

答:
is allocatable supposed to take in account the requested resources of the pod ?

No. Allocatable is your underlying instance capacity minus all the reserved (eg. system-reserved, kube-reserved, eviction threshold).

...how can I know what is the total amount of request/limit on one specific node?

You can continue use kubectl describe node, or kubectl top node, or kubernetes dasboard and many other monitoring tools out there.

Body:
I am making some tests, and I believe I may be misunderstanding how "allocatable" work.
I have 2 nodes running on Azure-AKS, both with Memory capacity of 65 Gi, and nothing but some basic daemon running on them.
When describing these nodes, I have for both about 59 Gi memory "allocatable".

Then I start a new pod, with a resources request and limit of 30Gi on one of these node. In practice, the pod use just a couple of Mo.
I would be expecting the "allocatable" to reduce to 29 Gi, but it stays at  59 Gi.

If I am doing a describe, the "allocated" section will correctly display what I actually requested.

Allocated resources:
  (Total limits may be over 100 percent, i.e., overcommitted.)
  Resource                       Requests       Limits
  --------                       --------       ------
   memory                         31190Mi (53%)  32170Mi (55%)
   ....

But not the allocatable:

Allocatable:
  attachable-volumes-azure-disk:  16
  cpu:                            7820m
  ephemeral-storage:              119716326407
  hugepages-1Gi:                  0
  hugepages-2Mi:                  0
  memory:                         59350320Ki
  pods:                           30

So, is allocatable supposed to take in account the requested resources of the pod ?

If yes, why is the value not decreasing here?

If no, how can I know what is the total amount of request/limit on one specific node (in a parsable format, such as json) ?


问:
powershell: pipe file content into a command
I'm not fluent into PowerShell, and I struggle on a somewhat simple problem:

I want to encrypt a (small) random file with DPAPI and write the result into another file.

I can encrypt an immediate string:

```<code>'cleartext' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
--> the result is a bunch of digits: 1000000d08c9d[...]0e35854
</code>```

Same thing, output into a file:

```<code>'cleartext' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Set-Content -Path output.txt
--> the file is created, and contains the right data
</code>```

But I don't understand how to get data from a file:

```<code># content of a file
Get-Content -Path input.txt
# --> 1st line
#     blah
#     last line

# pipe it into a command
Get-Content -Path input.txt | Measure-Object -line -word
# --> Lines Words Characters Property
#     ----- ----- ---------- --------
#         3     5

# but can not pipe it into ConvertTo-SecureString
Get-Content -Path input.txt | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
# --> ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is an empty string.
#     + ...  -Path input.txt |  ConvertTo-SecureString -AsPlainText -Force | Conve ...
#     +                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#     + CategoryInfo          : InvalidData : (:PSObject) [ConvertTo-SecureString], ParameterBindingValidationException
#     + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand
</code>```

Question: how can I make ConvertTo-SecureString to read a file's content?

答:
The issue here is data type mismatch. ConvertTo-SecureString takes String input and not arrays. When in doubt run GetType() method on your object:

```<code>'cleartext'.GetType().Name
</code>```

String

whereas return from vanilla Get-Content is array of objects:

```<code>(Get-Content .\input.txt).GetType().Name
</code>```

Object[]

You don't have to use the Name property but its so much cleaner.

So as proposed in the comments using the "-Raw" switch will give you what you need:

```<code> (Get-Content .\input.txt -Raw).GetType().Name
</code>```

String

Body:
I'm not fluent into PowerShell, and I struggle on a somewhat simple problem:

I want to encrypt a (small) random file with DPAPI and write the result into another file.

I can encrypt an immediate string:

'cleartext' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
--> the result is a bunch of digits: 1000000d08c9d[...]0e35854

Same thing, output into a file:

'cleartext' | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Set-Content -Path output.txt
--> the file is created, and contains the right data

But I don't understand how to get data from a file:

# content of a file
Get-Content -Path input.txt
# --> 1st line
#     blah
#     last line

# pipe it into a command
Get-Content -Path input.txt | Measure-Object -line -word
# --> Lines Words Characters Property
#     ----- ----- ---------- --------
#         3     5

# but can not pipe it into ConvertTo-SecureString
Get-Content -Path input.txt | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString
# --> ConvertTo-SecureString : Cannot bind argument to parameter 'String' because it is an empty string.
#     + ...  -Path input.txt |  ConvertTo-SecureString -AsPlainText -Force | Conve ...
#     +                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#     + CategoryInfo          : InvalidData : (:PSObject) [ConvertTo-SecureString], ParameterBindingValidationException
#     + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand

Question: how can I make ConvertTo-SecureString to read a file's content?

Body:
The issue here is data type mismatch. ConvertTo-SecureString takes String input and not arrays. When in doubt run GetType() method on your object:

'cleartext'.GetType().Name

String

whereas return from vanilla Get-Content is array of objects:

(Get-Content .\input.txt).GetType().Name

Object[]

You don't have to use the Name property but its so much cleaner.

So as proposed in the comments using the "-Raw" switch will give you what you need:

 (Get-Content .\input.txt -Raw).GetType().Name

String


问:
button to open a chatbot from a modal not working in NextJs
So, i've been trying to open a chatbot on the click of a button in a modal component. The button works alright in the home page but wouldn't work from the modal. Here's my code below. #nextJs #React
I'd appreciate any help ! Thanks.

Other approaches that failed:
i tried useRef to read the button click from the modal but it doesnt work.

I also tried attaching and calling the querySelector from the modal using useEffect but it keeps popping up an error not recognizing the querySelector even after defining the document/windows.

I've tried calling it via a function from onClick and still it doesnt work and even while the chatbot is showing it doesn't open.

I've also noticed that when i close the modal, the link to opening the chatbot from home page stops working.
I followed the initial tutorial from https://codepen.io/dominiczaq/pen/ajBQVQ?css-preprocessor=postcss

```<code>./pages/home.js

function home(props,{selector}) {
    useEffect(() => {
     (function() {
            function onTidioChatApiReady() {
              window.tidioChatApi.hide();
            }

            if (window.tidioChatApi) {
              window.tidioChatApi.on("ready", onTidioChatApiReady);
            }

            document.querySelectorAll(".chat-button").forEach(button=>{
               button.addEventListener("click", function() {
              window.tidioChatApi.show();
              window.tidioChatApi.open();
            })
        });
        })();
    }, [])

 return (
          <>
          <section>

           <button class="chat-button">
            Open Chat
           //this button works
           </button>

           </section>

          <section>

          <div class="inline-block px-10">

            <Modal />

          </div>

           </section>
          </>
          );
          }

export default home;

</code>```
```<code>./src/components/modal.js

         export default function Modal ({props, }){

           const [open, setOpen] = useState();

          return (

          <button type="button"  onClick={(e) => {setOpen(true);  } } class="w-64 h-64"}
          <img  src="https://www.aSampleImage.com" class="w-full h-full" />
          </button>
          { open &&
           <div className="backdrop" selector="#modal">

           <button>
           <h1 className="chat-button m-1">
           Open Chat
           // this doesn't work , HELP !
           </h1>
           </button>

           <button onClick={() => setOpen(false)} className="btn-right submit btn modal-close close" type="button" >
            <CloseIcon className="m-1"/>
           </button>

           </div>
           }
           )
           }

</code>```

Please note that the code i've posted here is redacted and my imports are alright. Also, i imported my script in _document.js since i'm using NextJs. see below.

```<code>./pages/_document.js

class MyDocument extends Document {
    render() {
        return (
            <Html lang="en">
            <Head>
                <meta property="custom" content="" />
            </Head>

            <body>
                <Main/>
            <script async src="//code.tidio.co/xxxxxMyChatBotAPIlinkxxxxxxx.js" strategy="lazyOnload" />
            </body>
            <NextScript/>

        </Html>
        );
    }
}

export default MyDocument;

</code>```

答:
Your code is not working because

```<code>document.querySelectorAll(".chat-button")
</code>```

can not select your open chat button in modal because it's not exist in DOM when modal is closed. So you can create a open function and pass to your button

```<code>export default function Modal ({ props }){

const [open, setOpen] = useState();

const openChat = () => {
    tidioChatApi?.show();
    tidioChatApi?.open();
}

return (
    <button type="button"  onClick={(e) => setOpen(true)} class="w-64 h-64">
        <img  src="https://www.aSampleImage.com" class="w-full h-full" />
    </button>
    {open &&
    <div className="backdrop" selector="#modal">
        <button onClick={openChat}>
            <h1 className="chat-button m-1">
                Open Chat
            </h1>
        </button>
    </div>}
)}
</code>```

./pages/_document.js

```<code>class MyDocument extends Document {
render() {
    return (
        <Html lang="en">
        <Head>
            <meta property="custom" content="" />
            <script async src="//code.tidio.co/xxxxxMyChatBotAPIlinkxxxxxxx.js" />
        </Head>

        <body>
            <Main/>
        </body>
        <NextScript/>

    </Html>
    );
}}

export default MyDocument;
</code>```

Body:
So, i've been trying to open a chatbot on the click of a button in a modal component. The button works alright in the home page but wouldn't work from the modal. Here's my code below. #nextJs #React
I'd appreciate any help ! Thanks.

Other approaches that failed:
i tried useRef to read the button click from the modal but it doesnt work.

I also tried attaching and calling the querySelector from the modal using useEffect but it keeps popping up an error not recognizing the querySelector even after defining the document/windows.

I've tried calling it via a function from onClick and still it doesnt work and even while the chatbot is showing it doesn't open.

I've also noticed that when i close the modal, the link to opening the chatbot from home page stops working.
I followed the initial tutorial from https://codepen.io/dominiczaq/pen/ajBQVQ?css-preprocessor=postcss

./pages/home.js

function home(props,{selector}) {
    useEffect(() => {
     (function() {
            function onTidioChatApiReady() {
              window.tidioChatApi.hide();
            }

            if (window.tidioChatApi) {
              window.tidioChatApi.on("ready", onTidioChatApiReady);
            }

            document.querySelectorAll(".chat-button").forEach(button=>{
               button.addEventListener("click", function() {
              window.tidioChatApi.show();
              window.tidioChatApi.open();
            })
        });
        })();
    }, [])

 return (
          <>

           <button class="chat-button">
            Open Chat
           //this button works
           </button>

            <Modal />

          </>
          );
          }

export default home;

./src/components/modal.js

         export default function Modal ({props, }){

           const [open, setOpen] = useState();

          return (

          <button type="button"  onClick={(e) => {setOpen(true);  } } class="w-64 h-64"}

          </button>
          { open &&

           <button>

           Open Chat
           // this doesn't work , HELP !

           </button>

           <button onClick={() => setOpen(false)} className="btn-right submit btn modal-close close" type="button" >
            <CloseIcon className="m-1"/>
           </button>

           }
           )
           }

Please note that the code i've posted here is redacted and my imports are alright. Also, i imported my script in _document.js since i'm using NextJs. see below.

./pages/_document.js

class MyDocument extends Document {
    render() {
        return (

                <meta property="custom" content="" />

Body:
Your code is not working because

document.querySelectorAll(".chat-button")

can not select your open chat button in modal because it's not exist in DOM when modal is closed. So you can create a open function and pass to your button

export default function Modal ({ props }){

const [open, setOpen] = useState();

const openChat = () => {
    tidioChatApi?.show();
    tidioChatApi?.open();
}

return (
    <button type="button"  onClick={(e) => setOpen(true)} class="w-64 h-64">
        <img  src="https://www.aSampleImage.com" class="w-full h-full" />
    </button>
    {open &&
    <div className="backdrop" selector="#modal">
        <button onClick={openChat}>
            <h1 className="chat-button m-1">
                Open Chat
            </h1>
        </button>
    </div>}
)}

./pages/_document.js

class MyDocument extends Document {
render() {
    return (
        <Html lang="en">
        <Head>
            <meta property="custom" content="" />
            <script async src="//code.tidio.co/xxxxxMyChatBotAPIlinkxxxxxxx.js" />
        </Head>

        <body>
            <Main/>
        </body>
        <NextScript/>

    </Html>
    );
}}

export default MyDocument;


问:
Network port listener on c#
I'm trying to listen the active ports on my network. I tried HttpListener, but I'm not sure if this is the right listener. Any ideas or examples?</p>

```<code>using (m_listener = new HttpListener())
{
m_listener.Prefixes.Add("http://*:8080/");
m_listener.Start();
while (m_listener.IsListening)
{
HttpListenerContext context = m_listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
textBox1.Text += request.RawUrl + "\r\n";
textBox1.Text += request.UserHostName + "\r\n"; }
m_listener.Stop();
}
</code>```

答: HttpListener is probably not your best bet if you want to do a full network scan. I would look into the System.Net.Sockets namespace. Port scanners are typically done via the sockets interface. You can create TCP and UDP sockets and bind them to listen to any port on a local machine or connect to a remote machine. If the socket succeeds, then the port is open and ready.</p>

Title: Network port listener on c#

Body:
I'm trying to listen the active ports on my network. I tried HttpListener, but I'm not sure if this is the right listener. Any ideas or examples?

using (m_listener = new HttpListener())
{
m_listener.Prefixes.Add("http://*:8080/");
m_listener.Start();
while (m_listener.IsListening)
{
HttpListenerContext context = m_listener.GetContext();
HttpListenerRequest request = context.Request;
HttpListenerResponse response = context.Response;
textBox1.Text += request.RawUrl + "\r\n";
textBox1.Text += request.UserHostName + "\r\n"; }
m_listener.Stop();
}


问:
How to query rows grouped by matching string column but only count the most recent row for a specific set of keywords?
Have a single table of email events where each row is keyed with a specific outgoing email record fk and a specific recipient user fk. At any given time and in no specific order and even simultaneously from different threads I can have new records dropping into this table. Here are the relevant columns...

```<code>id (pk), email_id (fk), user_id (fk), event (string/name), created_at
</code>```

I am calculating the overall event counts for a given email, like how many emails were delivered, how many bounced, etc. However I need to ignore specific combinations of email events for a specific user because they become outdated when a newer event comes in. For example if a row says the email was 'deferred' for a specific user but then later a new event row is inserted that says 'delivered' or 'bounced' then I only want the most recently added row of any of those related keywords to be counted once as the current state.

What's a good way to do this at read time? I am having trouble because of the multiple layers of grouping that I need to do and reaching the limits of my SQL chops, here is the query I am trying to enhance as described:

```<code>select `event`, COUNT(1) as count, COUNT(DISTINCT user_id) as unique_count
from `email_activity`
where `email_id` = 7518
group by `event`
</code>```

For most of the events I want them all counted without any replacement so grouping by only event is fine in those cases, eg if something was a 'click' or 'open' event just total them up.

However, if there are any number of 'deferred', 'bounced', or 'delivered' events for the same email_id/user_id I only want to count the one with the most recent created_at date and ignore all the older ones.

Example row set (email_id, event, user_id, created_at):

```<code>7518, "click", 25, 1-20-2021
7518, "click", 73, 1-5-2021
7518, "bounced", 45, 1-19-2021
7518, "deferred", 45, 1-17-2021
7518, "delivered", 19, 1-1-2021
7518, "delivered", 25, 1-1-2021
7518, "delivered", 73, 1-1-2021
</code>```

So the queried count for email 7518 would be:

2 "click", 3 "delivered", and 1 "bounced" as the "deferred" row would be ignored for user 45 since it is older (only "bounced", "deferred", and "delivered" events are part of this "only count the latest" rule, all other event names are always counted).

答:
I did this in postgres db like below. step 4 is the main query which can be directly used. i have just added initial 3 steps for better understanding of each sub query.

```<code>    create table email_event(id serial, email_id integer, user_id integer, event varchar(10), created_at date);

    insert into email_event(email_id, event, user_id, created_at) values(7518, 'click', 25, '1-20-2021');
    insert into email_event(email_id, event, user_id, created_at) values(7518, 'click', 73, '1-5-2021');
    insert into email_event(email_id, event, user_id, created_at)values(7518, 'bounced', 45, '1-19-2021');
    insert into email_event(email_id, event, user_id, created_at) values(7518, 'deferred', 45, '1-17-2021');
    insert into email_event(email_id, event, user_id, created_at)values(7518, 'delivered', 19, '1-1-2021');
    insert into email_event(email_id, event, user_id, created_at) values(7518, 'delivered', 25, '1-1-2021');
    insert into email_event(email_id, event, user_id, created_at) values(7518, 'delivered', 73, '1-1-2021');
</code>```

first we will flag the event category:

```<code> select email_id, user_id,event, created_at,
 case when event in ('bounced', 'deferred', 'delivered') then 'Y' else 'N' end as pick_latest_flag
 from email_event;
</code>```

Then we will group pick_latest_flag and rank them based on user_id and flag.

```<code> select a.*,
 row_number () over (partition by email_id, user_id, pick_latest_flag order by created_at desc) rn
 from (
 select email_id, user_id,event, created_at,
 case when event in ('bounced', 'deferred', 'delivered') then 'Y' else 'N' end as pick_latest_flag
 from email_event
 ) A;
</code>```

then we will filter out the pick_latest_flag records based on their row number.

```<code> select * from (
 select a.*,
 row_number () over (partition by user_id, pick_latest_flag order by created_at desc) rn
 from (
 select email_id, user_id,event, created_at,
 case when event in ('bounced', 'deferred', 'delivered') then 'Y' else 'N' end as pick_latest_flag
 from email_event
 ) A
 ) b where pick_latest_flag = 'N' or (pick_latest_flag = 'Y' and rn = 1);
</code>```

in the final step, group them on email_id and event:

```<code> select email_id, event, count(*) from
 (
 select * from (
 select a.*,
 row_number () over (partition by user_id, pick_latest_flag order by created_at desc) rn
 from (
 select email_id, user_id,event, created_at,
 case when event in ('bounced', 'deferred', 'delivered') then 'Y' else 'N' end as pick_latest_flag
 from email_event
 ) A
 ) b where pick_latest_flag = 'N' or (pick_latest_flag = 'Y' and rn = 1)
 ) c group by email_id,event order by event;
</code>```

Body:
Have a single table of email events where each row is keyed with a specific outgoing email record fk and a specific recipient user fk. At any given time and in no specific order and even simultaneously from different threads I can have new records dropping into this table. Here are the relevant columns...

id (pk), email_id (fk), user_id (fk), event (string/name), created_at

I am calculating the overall event counts for a given email, like how many emails were delivered, how many bounced, etc. However I need to ignore specific combinations of email events for a specific user because they become outdated when a newer event comes in. For example if a row says the email was 'deferred' for a specific user but then later a new event row is inserted that says 'delivered' or 'bounced' then I only want the most recently added row of any of those related keywords to be counted once as the current state.

What's a good way to do this at read time? I am having trouble because of the multiple layers of grouping that I need to do and reaching the limits of my SQL chops, here is the query I am trying to enhance as described:

select `event`, COUNT(1) as count, COUNT(DISTINCT user_id) as unique_count
from `email_activity`
where `email_id` = 7518
group by `event`

For most of the events I want them all counted without any replacement so grouping by only event is fine in those cases, eg if something was a 'click' or 'open' event just total them up.

However, if there are any number of 'deferred', 'bounced', or 'delivered' events for the same email_id/user_id I only want to count the one with the most recent created_at date and ignore all the older ones.

Example row set (email_id, event, user_id, created_at):

7518, "click", 25, 1-20-2021
7518, "click", 73, 1-5-2021
7518, "bounced", 45, 1-19-2021
7518, "deferred", 45, 1-17-2021
7518, "delivered", 19, 1-1-2021
7518, "delivered", 25, 1-1-2021
7518, "delivered", 73, 1-1-2021

So the queried count for email 7518 would be:

2 "click", 3 "delivered", and 1 "bounced" as the "deferred" row would be ignored for user 45 since it is older (only "bounced", "deferred", and "delivered" events are part of this "only count the latest" rule, all other event names are always counted).

Body:
I did this in postgres db like below. step 4 is the main query which can be directly used. i have just added initial 3 steps for better understanding of each sub query.

    create table email_event(id serial, email_id integer, user_id integer, event varchar(10), created_at date);

    insert into email_event(email_id, event, user_id, created_at) values(7518, 'click', 25, '1-20-2021');
    insert into email_event(email_id, event, user_id, created_at) values(7518, 'click', 73, '1-5-2021');
    insert into email_event(email_id, event, user_id, created_at)values(7518, 'bounced', 45, '1-19-2021');
    insert into email_event(email_id, event, user_id, created_at) values(7518, 'deferred', 45, '1-17-2021');
    insert into email_event(email_id, event, user_id, created_at)values(7518, 'delivered', 19, '1-1-2021');
    insert into email_event(email_id, event, user_id, created_at) values(7518, 'delivered', 25, '1-1-2021');
    insert into email_event(email_id, event, user_id, created_at) values(7518, 'delivered', 73, '1-1-2021');

first we will flag the event category:

 select email_id, user_id,event, created_at,
 case when event in ('bounced', 'deferred', 'delivered') then 'Y' else 'N' end as pick_latest_flag
 from email_event;

Then we will group pick_latest_flag and rank them based on user_id and flag.

 select a.*,
 row_number () over (partition by email_id, user_id, pick_latest_flag order by created_at desc) rn
 from (
 select email_id, user_id,event, created_at,
 case when event in ('bounced', 'deferred', 'delivered') then 'Y' else 'N' end as pick_latest_flag
 from email_event
 ) A;

then we will filter out the pick_latest_flag records based on their row number.

 select * from (
 select a.*,
 row_number () over (partition by user_id, pick_latest_flag order by created_at desc) rn
 from (
 select email_id, user_id,event, created_at,
 case when event in ('bounced', 'deferred', 'delivered') then 'Y' else 'N' end as pick_latest_flag
 from email_event
 ) A
 ) b where pick_latest_flag = 'N' or (pick_latest_flag = 'Y' and rn = 1);

in the final step, group them on email_id and event:

 select email_id, event, count(*) from
 (
 select * from (
 select a.*,
 row_number () over (partition by user_id, pick_latest_flag order by created_at desc) rn
 from (
 select email_id, user_id,event, created_at,
 case when event in ('bounced', 'deferred', 'delivered') then 'Y' else 'N' end as pick_latest_flag
 from email_event
 ) A
 ) b where pick_latest_flag = 'N' or (pick_latest_flag = 'Y' and rn = 1)
 ) c group by email_id,event order by event;


问:
Get the last Wednesday from a given date
If a datetime field is passed, how do I determine when the last Wednesday was and set it to 10AM on that day?

Declare DateTime @datetime

For example:

if I pass in @datetime = '2022-Feb-7 5:00:00' then I should get 2022-Feb-2 10:00:00

if I pass in @datetime = '2022-Feb-10 16:00:00' then I should get 2022-Feb-9 10:00:00

I have an edge case here:

if the @datetime is Wednesday and the time is less than 10AM then it should set it to last Wednesday and if the time is greater than 10AM then it should set it current Wednesday 10AM.

For example:

if I pass in @datetime='2022-Feb-9 5:00:000' then I should get 2022-Feb-2 10:00:00

if I pass in @datetime = '2022-Feb-9 16:00:00' then I should get 2022-Feb-9 10:00:00

答:
Given this data:

```<code>CREATE TABLE #dates(source smalldatetime);

INSERT #dates(source) VALUES
('20220207 05:00:00'), -- should be 2/2
('20220210 16:00:00'), -- should be 2/9
('20220209 05:00:00'), -- should be 2/2
('20220209 16:00:00'), -- should be 2/9
('20220209 09:59:00'), -- should be 2/2
('20220209 10:00:00'); -- should be 2/9
</code>```

This query will shift the source datetime value by 14 hours so that anything from 10 AM on will technically be considered the next day. This "simplifies" the calculation and allows us to subtract an additional week only in the case where the day is Wednesday and the adjusted time is still on Wednesday. Works for any SET DATEFIRST n setting.

```<code>SELECT source, prev_wed = DATEADD(HOUR, 10, DATEADD(DAY,
  COALESCE(NULLIF((-@@DATEFIRST-DATEPART(WEEKDAY,adj)-3)%7,0),-7),adj))
FROM
(
  SELECT source, adj = CONVERT(smalldatetime,
    CONVERT(date, DATEADD(HOUR, 14, source)))
  FROM #dates
) AS adj;
</code>```

Results (example db<>fiddle):

source
prev_wed

2022-02-07 05:00
2022-02-02 10:00

2022-02-10 16:00
2022-02-09 10:00

2022-02-09 05:00
2022-02-02 10:00

2022-02-09 16:00
2022-02-09 10:00

2022-02-09 09:59
2022-02-02 10:00

2022-02-09 10:00
2022-02-09 10:00

A slightly simpler way that avoids the @@DATEFIRST complication is to take a known Wednesday in the past, and see how many 7-day intervals have happened since then.

```<code>DECLARE @base date = '20200101'; -- known Wednesday

SELECT source, prev_wed = DATEADD(DAY,DATEDIFF(DAY,@base,
    CONVERT(date, DATEADD(HOUR, -10, source)))/7*7, @base)
FROM #dates;
</code>```

Results are the same (db<>fiddle).

Body:
Given this data:

CREATE TABLE #dates(source smalldatetime);

INSERT #dates(source) VALUES
('20220207 05:00:00'), -- should be 2/2
('20220210 16:00:00'), -- should be 2/9
('20220209 05:00:00'), -- should be 2/2
('20220209 16:00:00'), -- should be 2/9
('20220209 09:59:00'), -- should be 2/2
('20220209 10:00:00'); -- should be 2/9

This query will shift the source datetime value by 14 hours so that anything from 10 AM on will technically be considered the next day. This "simplifies" the calculation and allows us to subtract an additional week only in the case where the day is Wednesday and the adjusted time is still on Wednesday. Works for any SET DATEFIRST n setting.

SELECT source, prev_wed = DATEADD(HOUR, 10, DATEADD(DAY,
  COALESCE(NULLIF((-@@DATEFIRST-DATEPART(WEEKDAY,adj)-3)%7,0),-7),adj))
FROM
(
  SELECT source, adj = CONVERT(smalldatetime,
    CONVERT(date, DATEADD(HOUR, 14, source)))
  FROM #dates
) AS adj;

Results (example db<>fiddle):

source
prev_wed

2022-02-07 05:00
2022-02-02 10:00

2022-02-10 16:00
2022-02-09 10:00

2022-02-09 05:00
2022-02-02 10:00

2022-02-09 16:00
2022-02-09 10:00

2022-02-09 09:59
2022-02-02 10:00

2022-02-09 10:00
2022-02-09 10:00

A slightly simpler way that avoids the @@DATEFIRST complication is to take a known Wednesday in the past, and see how many 7-day intervals have happened since then.

DECLARE @base date = '20200101'; -- known Wednesday

SELECT source, prev_wed = DATEADD(DAY,DATEDIFF(DAY,@base,
    CONVERT(date, DATEADD(HOUR, -10, source)))/7*7, @base)
FROM #dates;

Results are the same (db<>fiddle).


问:
How to add custom css in wix website
I am new at wix and editing a website and want to add css in a page. but not found any option for css.
Anybody know how to add custom css code in wix website?

Thanks

答:
As of 2022, you can add it from your Wix Dashboard under Settings > Advanced > Custom code.

Click the Add Custom Code button. Enter your CSS in the Paste the code snippet here: textarea. Make sure to wrap it within  tags. Set the Code Type as "Essential" as it doesn't require user consent to load.

Note: You won't be able to see your CSS from the page editor nor Preview mode. You have to Publish it and view it from the frontend.

Wix Add Custom Code screenshot

Title: How to add custom css in wix website

Body:
As of 2022, you can add it from your Wix Dashboard under Settings > Advanced > Custom code.

Click the Add Custom Code button. Enter your CSS in the Paste the code snippet here: textarea. Make sure to wrap it within <style type="text/css"></style> tags. Set the Code Type as "Essential" as it doesn't require user consent to load.

Note: You won't be able to see your CSS from the page editor nor Preview mode. You have to Publish it and view it from the frontend.

Wix Add Custom Code screenshot


问:
Setting Heartbeat when connecting to RabbitMQ via Amqplib
When connecting to RabbitMQ via amqplib, the value of the Heartbeat parameter cannot be set.

I do this:

```<code>// NPM Modules
const amqp = require('amqplib/callback_api');
const withAutoRecovery = require('amqplib-auto-recovery');

// Application configuration
const config = settings.getConfig();

withAutoRecovery(amqp, {
  onError: (err) => { console.log(err.message); },
  isErrorUnrecoverable: (err) => { console.log(err) }
}).connect(config.rabbitmq, (err, connection) => {
    // If there are connection errors
    if (err) {
        console.error(this.conn_str_amqp);
        console.error('[AMQP] Connection error:', err.message);
    } else if (connection) {
        // Connection Error Event
        connection.on('error', (err) => {
            if (err.message !== 'Connection closing') {
                console.error('[AMQP] Closing connection', err.message);
            }
        });
        // Error event when you close the connection
        connection.on('close', () => {
            console.error('[AMQP] Closing connection');
        });
        // Hint to user
        console.log('[AMQP] Connected');
    }
});
</code>```

Here config.rabbitmq is:

```<code>{
  protocol: 'amqp',
  hostname: 'localhost',
  port: 5672,
  username: 'guest',
  password: 'guest',
  locale: 'en_US',
  frameMax: 0x1000,
  heartbeat: 1800,
  vhost: '/',
}
</code>```

I expect to get the Heartbeat = 1800s parameter value, in the UI Managment window the default value Heartbeat = 60s is displayed.

Screenshot:

I tried to pass another object instead config.rabbitmq line (https://www.rabbitmq.com/uri-spec.html and https://www.rabbitmq.com/uri-query-parameters.html) in the format:

```<code>function getRabbitMQConnectionString() {
    const rabbitmq = config.rabbitmq;
    return `${rabbitmq.protocol}://${rabbitmq.username}:${rabbitmq.password}@${rabbitmq.hostname}:${rabbitmq.port}${encodeURIComponent(rabbitmq.vhost)}?heartbeat=${rabbitmq.heartbeat}`;
}
</code>```

Thus, too, it turned out similar to the above effect.

Tell me, please, how to correctly set the Heartbeat parameter through the Node.js client application on amqplib?

答: For some reason I set up the heartbeat to 30 s and it worked.</p>

Body:
When connecting to RabbitMQ via amqplib, the value of the Heartbeat parameter cannot be set.

I do this:

// NPM Modules
const amqp = require('amqplib/callback_api');
const withAutoRecovery = require('amqplib-auto-recovery');

// Application configuration
const config = settings.getConfig();

withAutoRecovery(amqp, {
  onError: (err) => { console.log(err.message); },
  isErrorUnrecoverable: (err) => { console.log(err) }
}).connect(config.rabbitmq, (err, connection) => {
    // If there are connection errors
    if (err) {
        console.error(this.conn_str_amqp);
        console.error('[AMQP] Connection error:', err.message);
    } else if (connection) {
        // Connection Error Event
        connection.on('error', (err) => {
            if (err.message !== 'Connection closing') {
                console.error('[AMQP] Closing connection', err.message);
            }
        });
        // Error event when you close the connection
        connection.on('close', () => {
            console.error('[AMQP] Closing connection');
        });
        // Hint to user
        console.log('[AMQP] Connected');
    }
});

Here config.rabbitmq is:

{
  protocol: 'amqp',
  hostname: 'localhost',
  port: 5672,
  username: 'guest',
  password: 'guest',
  locale: 'en_US',
  frameMax: 0x1000,
  heartbeat: 1800,
  vhost: '/',
}

I expect to get the Heartbeat = 1800s parameter value, in the UI Managment window the default value Heartbeat = 60s is displayed.

Screenshot:

I tried to pass another object instead config.rabbitmq line (https://www.rabbitmq.com/uri-spec.html and https://www.rabbitmq.com/uri-query-parameters.html) in the format:

function getRabbitMQConnectionString() {
    const rabbitmq = config.rabbitmq;
    return `${rabbitmq.protocol}://${rabbitmq.username}:${rabbitmq.password}@${rabbitmq.hostname}:${rabbitmq.port}${encodeURIComponent(rabbitmq.vhost)}?heartbeat=${rabbitmq.heartbeat}`;
}

Thus, too, it turned out similar to the above effect.

Tell me, please, how to correctly set the Heartbeat parameter through the Node.js client application on amqplib?


问:
Jenkins Pipeline (Workflow) Stage View disappears
I have the problem, that in some Jenkins Pipeline projects the Stage View becomes invisible.

Usually, you can see the stage view between "Recent Changes" and "Permalinks". After some runs of a project, the Stage View disappears. If I clone the project, then the view is visible in the clone, but not in the original project.

It's a workaround to clone the project, but not a good one because I cannot replace the job every week.

Has someone seen that problem before and has an idea, how to fix that?

The stage view div, is on the job overview page, but it's not visible:

    <link rel="stylesheet" href="/adjuncts/ee6b655e/org/jenkinsci/pipeline/stageview_adjunct.css" type="text/css">

```
</div>
</div>
</p>

<p>My Jenkinsfile:</p>

<pre class="lang-groovy prettyprint-override"><code>def sonarHostUrl = 'http://sonar.host.url:1234'

node('Build') {
    echo "enforce a clear workspace:" // because there were some other problems
    deleteDir()

    stage('Checkout') {
        checkoutFromSVN()
    }
    stage('Compile') {
        mvn 'clean compile test-compile'
    }
    stage('Unit Tests') {
        mvn '-B org.jacoco:jacoco-maven-plugin:prepare-agent test'
        step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
    }
    stage('Deploy to Nexus') {
        mvn 'install deploy -DskipTests'
        archiveArtifacts artifacts: '**/project-name*.jar', onlyIfSuccessful: false
    }
    stage('Local Integration Tests') {
        mvn '-B org.jacoco:jacoco-maven-plugin:prepare-agent-integration failsafe:integration-test failsafe:verify'
        step([$class: 'JUnitResultArchiver', testResults: '**/target/failsafe-reports/TEST-*.xml'])
    }
    stage('Sonar'){
        mvn "org.sonarsource.scanner.maven:sonar-maven-plugin:3.1.1:sonar -Dsonar.host.url=$sonarHostUrl"
    }
}
stage('Deploy to DEV') {
    build 'JobThatDeploysTheApplicationToDevEnv'
}
stage('Functional Tests') {
    build job: 'JobWithSoapUITests', parameters: [string(name: 'TESTENVIRONMENT', value: 'DEV')]
}

def checkoutFromSVN(){
    checkout([$class: 'SubversionSCM',
            excludedCommitMessages: '.*\\[maven-release-plugin\\].*',
            locations: [[credentialsId: 'a1a2b3c4-1234-ab1d-b56c-0ac4bff23a6c',
                       depthOption: 'infinity',
                       ignoreExternalsOption: true,
                       excludedRegions: 'Jenkinsfile',
                       local: 'project-dir',
                       remote: 'https://url.to/project-dir']],
            workspaceUpdater: [$class: 'CheckoutUpdater']])
}

def mvn(String args) {
    def mvnCmd = "${tool name: 'Maven 3.3.9', type: 'hudson.tasks.Maven$MavenInstallation'}/bin/mvn"

    wrap([$class: 'ConfigFileBuildWrapper',
          managedFiles: [[
                    fileId: 'org.jenkinsci.plugins.configfiles.maven.GlobalMavenSettingsConfig1234567',
                    targetLocation: '', // temporary file
                    variable: 'MAVEN_SETTINGS']]]) {
        bat "${mvnCmd} -s ${env.MAVEN_SETTINGS} ${args} -f project-dir/pom.xml"
    }
}
</code>```

My Job configuration exported as XML:

<?xml version='1.0' encoding='UTF-8'?>
<flow-definition plugin="workflow-job@2.9">
  <actions/>
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <jenkins.model.BuildDiscarderProperty>
      <strategy class="hudson.tasks.LogRotator">
        <daysToKeep>-1</daysToKeep>
        <numToKeep>10</numToKeep>
        <artifactDaysToKeep>-1</artifactDaysToKeep>
        <artifactNumToKeep>-1</artifactNumToKeep>
      </strategy>
    </jenkins.model.BuildDiscarderProperty>
    <org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
      <triggers>
        <hudson.triggers.TimerTrigger>
          <spec>H H * * *</spec>
        </hudson.triggers.TimerTrigger>
        <hudson.triggers.SCMTrigger>
          <spec>H/10 7-18 * * *</spec>
          <ignorePostCommitHooks>false</ignorePostCommitHooks>
        </hudson.triggers.SCMTrigger>
      </triggers>
    </org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
  </properties>
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition" plugin="workflow-cps@2.23">
    <scm class="hudson.scm.SubversionSCM" plugin="subversion@2.6">
      <locations>
        <hudson.scm.SubversionSCM_-ModuleLocation>
          <remote>https://url.to/project-dir</remote>
          <credentialsId>a1a2b3c4-1234-ab1d-b56c-0ac4bff23a6c</credentialsId>
          <local>.</local>
          <depthOption>infinity</depthOption>
          <ignoreExternalsOption>true</ignoreExternalsOption>
        </hudson.scm.SubversionSCM_-ModuleLocation>
      </locations>
      <excludedRegions></excludedRegions>
      <includedRegions>Jenkinsfile</includedRegions>
      <excludedUsers></excludedUsers>
      <excludedRevprop></excludedRevprop>
      <excludedCommitMessages></excludedCommitMessages>
      <workspaceUpdater class="hudson.scm.subversion.UpdateWithRevertUpdater"/>
      <ignoreDirPropChanges>false</ignoreDirPropChanges>
      <filterChangelog>false</filterChangelog>
    </scm>

  </definition>
  <triggers/>
</flow-definition>
```

答:
If you create a copy of the pipeline without the Stage View - the copy will have it.

Dashboard > New Item > on the left hand menu

Give it a name

Copy from > at the bottom > type name of you pipeline

Enjoy =)

Body:
I have the problem, that in some Jenkins Pipeline projects the Stage View becomes invisible.

Usually, you can see the stage view between "Recent Changes" and "Permalinks". After some runs of a project, the Stage View disappears. If I clone the project, then the view is visible in the clone, but not in the original project.

It's a workaround to clone the project, but not a good one because I cannot replace the job every week.

Has someone seen that problem before and has an idea, how to fix that?

The stage view div, is on the job overview page, but it's not visible:

    <link rel="stylesheet" href="/adjuncts/ee6b655e/org/jenkinsci/pipeline/stageview_adjunct.css" type="text/css">

My Jenkinsfile:

def sonarHostUrl = 'http://sonar.host.url:1234'

node('Build') {
    echo "enforce a clear workspace:" // because there were some other problems
    deleteDir()

    stage('Checkout') {
        checkoutFromSVN()
    }
    stage('Compile') {
        mvn 'clean compile test-compile'
    }
    stage('Unit Tests') {
        mvn '-B org.jacoco:jacoco-maven-plugin:prepare-agent test'
        step([$class: 'JUnitResultArchiver', testResults: '**/target/surefire-reports/TEST-*.xml'])
    }
    stage('Deploy to Nexus') {
        mvn 'install deploy -DskipTests'
        archiveArtifacts artifacts: '**/project-name*.jar', onlyIfSuccessful: false
    }
    stage('Local Integration Tests') {
        mvn '-B org.jacoco:jacoco-maven-plugin:prepare-agent-integration failsafe:integration-test failsafe:verify'
        step([$class: 'JUnitResultArchiver', testResults: '**/target/failsafe-reports/TEST-*.xml'])
    }
    stage('Sonar'){
        mvn "org.sonarsource.scanner.maven:sonar-maven-plugin:3.1.1:sonar -Dsonar.host.url=$sonarHostUrl"
    }
}
stage('Deploy to DEV') {
    build 'JobThatDeploysTheApplicationToDevEnv'
}
stage('Functional Tests') {
    build job: 'JobWithSoapUITests', parameters: [string(name: 'TESTENVIRONMENT', value: 'DEV')]
}

def checkoutFromSVN(){
    checkout([$class: 'SubversionSCM',
            excludedCommitMessages: '.*\\[maven-release-plugin\\].*',
            locations: [[credentialsId: 'a1a2b3c4-1234-ab1d-b56c-0ac4bff23a6c',
                       depthOption: 'infinity',
                       ignoreExternalsOption: true,
                       excludedRegions: 'Jenkinsfile',
                       local: 'project-dir',
                       remote: 'https://url.to/project-dir']],
            workspaceUpdater: [$class: 'CheckoutUpdater']])
}

def mvn(String args) {
    def mvnCmd = "${tool name: 'Maven 3.3.9', type: 'hudson.tasks.Maven$MavenInstallation'}/bin/mvn"

    wrap([$class: 'ConfigFileBuildWrapper',
          managedFiles: [[
                    fileId: 'org.jenkinsci.plugins.configfiles.maven.GlobalMavenSettingsConfig1234567',
                    targetLocation: '', // temporary file
                    variable: 'MAVEN_SETTINGS']]]) {
        bat "${mvnCmd} -s ${env.MAVEN_SETTINGS} ${args} -f project-dir/pom.xml"
    }
}

My Job configuration exported as XML:

<?xml version='1.0' encoding='UTF-8'?>
<flow-definition plugin="workflow-job@2.9">
  <actions/>
  <description></description>
  <keepDependencies>false</keepDependencies>
  <properties>
    <jenkins.model.BuildDiscarderProperty>
      <strategy class="hudson.tasks.LogRotator">
        <daysToKeep>-1</daysToKeep>
        <numToKeep>10</numToKeep>
        <artifactDaysToKeep>-1</artifactDaysToKeep>
        <artifactNumToKeep>-1</artifactNumToKeep>
      </strategy>
    </jenkins.model.BuildDiscarderProperty>
    <org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
      <triggers>
        <hudson.triggers.TimerTrigger>
          <spec>H H * * *</spec>
        </hudson.triggers.TimerTrigger>
        <hudson.triggers.SCMTrigger>
          <spec>H/10 7-18 * * *</spec>
          <ignorePostCommitHooks>false</ignorePostCommitHooks>
        </hudson.triggers.SCMTrigger>
      </triggers>
    </org.jenkinsci.plugins.workflow.job.properties.PipelineTriggersJobProperty>
  </properties>
  <definition class="org.jenkinsci.plugins.workflow.cps.CpsScmFlowDefinition" plugin="workflow-cps@2.23">
    <scm class="hudson.scm.SubversionSCM" plugin="subversion@2.6">
      <locations>
        <hudson.scm.SubversionSCM_-ModuleLocation>
          <remote>https://url.to/project-dir</remote>
          <credentialsId>a1a2b3c4-1234-ab1d-b56c-0ac4bff23a6c</credentialsId>
          <local>.</local>
          <depthOption>infinity</depthOption>
          <ignoreExternalsOption>true</ignoreExternalsOption>
        </hudson.scm.SubversionSCM_-ModuleLocation>
      </locations>
      <excludedRegions></excludedRegions>
      <includedRegions>Jenkinsfile</includedRegions>
      <excludedUsers></excludedUsers>
      <excludedRevprop></excludedRevprop>
      <excludedCommitMessages></excludedCommitMessages>
      <workspaceUpdater class="hudson.scm.subversion.UpdateWithRevertUpdater"/>
      <ignoreDirPropChanges>false</ignoreDirPropChanges>
      <filterChangelog>false</filterChangelog>
    </scm>

  </definition>
  <triggers/>
</flow-definition>


问:
Best way to import custom packages
I use python for data analysis. A lot of pandas. I have started writing modules to perform things I run often, like processing a file in a specific way.

To handle that, I created a folder named "packages", then I import the package like so:

```<code>import sys
sys.path.append('/packages')
import importlib
import mypackage
importlib.reload(mypackage)
</code>```

It's a bit of a hassle because I need to add the path (not the end of the world). I just keep the code block and copy and paste.

Is there a better way to handle custom local packages?

答:
I use python -m pip install -e path/to/local/package, preferably within a project-specific virtual environment. The package is set up in a pypi-compliant way (although not uploaded to pypi) with setup.py etc.

The -e option is "editable" and means any changes I make in the local package will be included in my client project, or at least as soon as I reimport it. (When working in interactive mode, import importlib; importlib.reload("mypackage") is invoked often.)

Title: Best way to import custom packages

Body:
I use python for data analysis. A lot of pandas. I have started writing modules to perform things I run often, like processing a file in a specific way.

To handle that, I created a folder named "packages", then I import the package like so:

import sys
sys.path.append('/packages')
import importlib
import mypackage
importlib.reload(mypackage)

It's a bit of a hassle because I need to add the path (not the end of the world). I just keep the code block and copy and paste.

Is there a better way to handle custom local packages?


问:
Eclipse obsolete methods on the stack
I'm using Eclipse for Java on my Macbook air, OS 10.9. I keep getting the error Obsolete Methods on the Stack, with a warning about how it may cause problems with the virtual machine when I run very basic programs that have no errors. I ran a program that just had the class and the main method and I got this error. After the error box, the bug referred to the main method, but I know the syntax is correct because I used Eclipse's main method.

```<code>import java.util.Scanner;

public class Dowhile {

    public static void main(String[] args) {
        /*Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number");
        int value = scanner.nextInt();
        System.out.println(value);*/
        /*do{
            System.out.println("Enter a number ");
            int value = scanner.nextInt();

        }
        while(value != 5);
        System.out.println("Got 5");*/
    }
}
</code>```

Update:

I'm not getting the obsolete methods error now, just Exception in thread "main"... at line 5.

答: I clicked on Terminate button and it no longer showed that warning message again.</p>

Title: Eclipse obsolete methods on the stack

Body:
I'm using Eclipse for Java on my Macbook air, OS 10.9. I keep getting the error Obsolete Methods on the Stack, with a warning about how it may cause problems with the virtual machine when I run very basic programs that have no errors. I ran a program that just had the class and the main method and I got this error. After the error box, the bug referred to the main method, but I know the syntax is correct because I used Eclipse's main method.

import java.util.Scanner;

public class Dowhile {

    public static void main(String[] args) {
        /*Scanner scanner = new Scanner(System.in);
        System.out.println("Enter a number");
        int value = scanner.nextInt();
        System.out.println(value);*/
        /*do{
            System.out.println("Enter a number ");
            int value = scanner.nextInt();

        }
        while(value != 5);
        System.out.println("Got 5");*/
    }
}

Update:

I'm not getting the obsolete methods error now, just Exception in thread "main"... at line 5.


问:
How do I Make My created_at Timestamps set to the User timezone?
I have a React/Rails app that allows users to submit a report. However, the reports are always being marked with a utc created_at timestamp. Since the users are in different timezones this can cause a problem.

For example, if I create a report at ~9pm PST for February 7, the utc timestamp will show February 8 - which messed with daily reporting.

I thought this could mitigated on the front end, but using the javascript Date() object, which I thought would be local to the machine running the js, but the rails db timestamps still show the UTC time.

So far I've tried that, adding this in the createReport component

```<code>  async function handleSubmit(e) {
    e.preventDefault();
    if (!rep_type) {
      alert("Please provide a rep_type")
      return
    }
    const date = new Date();
    let data = await axios.post(`${API_ROOT}/api/reports`, {
      report: {
        user_id: props.currentUser.id,
        rep_type: rep_type,
        rep_count: rep_count,
        created_at: date
      }
    })
</code>```

And then in my reports_controller.rb I am expecting created_at to be a parameter

```<code>  def create
    @report = Report.create!(
      user_id: params["report"]["user_id"],
      rep_type: params["report"]["rep_type"],
      rep_count: params["report"]["rep_count"],
      created_at: params["report"]["date"]
    )
  end
</code>```

What's interesting, is when I console.log(date) I see what I'd expect:

```<code>Mon Feb 07 2022 18:15:52 GMT-0800 (Pacific Standard Time)
</code>```

But when I look at the network request I see the date is back to UTC

Edit:

By changing my POST request in createReport to send date as a string I can see in the network request I am sending the date/timezone I want, but rails is automatically changing it to UTC so I think it's a rails thing to fix.

What would be the most straightforward approach to make sure the date is at least accurate to the date in which the user created the report?

答:
What I usually do is to ask the user to select the timezone that he/she wants to use in the system and then in a around_action I set the timezone for the request. In that way all dates are saved in UTC but are visible in the user's timezone

around_action :set_time_zone
...
def set_time_zone
  old_time_zone = Time.zone
  Time.zone = current_user.timezone
  yield
ensure
  Time.zone = old_time_zone
end
```
<p>Another option is to send the offset (not the date) from the browser and set the <code>Time.zone</code> based on that</p>
<pre class="lang-js prettyprint-override"><code>const date = new Date();
const offset = date.getTimezoneOffset()/60;
</code>```

and then in rails

Time.zone = ActiveSupport::TimeZone[-offset]
```

But, it could be tricky for DST

My advice is to keep the timestamps as UTC in the database and only transform it to show to the user, for reporting just be careful doing the searches using times that include timezones

Body:
I have a React/Rails app that allows users to submit a report. However, the reports are always being marked with a utc created_at timestamp. Since the users are in different timezones this can cause a problem.

For example, if I create a report at ~9pm PST for February 7, the utc timestamp will show February 8 - which messed with daily reporting.

I thought this could mitigated on the front end, but using the javascript Date() object, which I thought would be local to the machine running the js, but the rails db timestamps still show the UTC time.

So far I've tried that, adding this in the createReport component

  async function handleSubmit(e) {
    e.preventDefault();
    if (!rep_type) {
      alert("Please provide a rep_type")
      return
    }
    const date = new Date();
    let data = await axios.post(`${API_ROOT}/api/reports`, {
      report: {
        user_id: props.currentUser.id,
        rep_type: rep_type,
        rep_count: rep_count,
        created_at: date
      }
    })

And then in my reports_controller.rb I am expecting created_at to be a parameter

  def create
    @report = Report.create!(
      user_id: params["report"]["user_id"],
      rep_type: params["report"]["rep_type"],
      rep_count: params["report"]["rep_count"],
      created_at: params["report"]["date"]
    )
  end

What's interesting, is when I console.log(date) I see what I'd expect:

Mon Feb 07 2022 18:15:52 GMT-0800 (Pacific Standard Time)

But when I look at the network request I see the date is back to UTC

Edit:

By changing my POST request in createReport to send date as a string I can see in the network request I am sending the date/timezone I want, but rails is automatically changing it to UTC so I think it's a rails thing to fix.

What would be the most straightforward approach to make sure the date is at least accurate to the date in which the user created the report?

Body:
What I usually do is to ask the user to select the timezone that he/she wants to use in the system and then in a around_action I set the timezone for the request. In that way all dates are saved in UTC but are visible in the user's timezone

around_action :set_time_zone
...
def set_time_zone
  old_time_zone = Time.zone
  Time.zone = current_user.timezone
  yield
ensure
  Time.zone = old_time_zone
end

Another option is to send the offset (not the date) from the browser and set the Time.zone based on that

const date = new Date();
const offset = date.getTimezoneOffset()/60;

and then in rails

Time.zone = ActiveSupport::TimeZone[-offset]

But, it could be tricky for DST

My advice is to keep the timestamps as UTC in the database and only transform it to show to the user, for reporting just be careful doing the searches using times that include timezones