text:
Q: How to store 800 billion GPS markers in database I need to store GPS tracks that users record into a database. The tracks will consist of a marker every 5 meter of movement for the purpose of drawing a line on a map. I am estimating 200 km tracks which means 40,000 lnlt markers. I estimate 50,000 users minimum and 20 pieces of 200 km tracks for each. That means at least 40 billion lnlt markers.
This needs to scale too, so for 1 million users I need capacity for 800 billion GPS markers.
Since each set of 40,000 markers belong to a single track, we are talking 1 - 20 million records/sets of GPS tracks.
Requirements:
Users will request to view these tracks on top of a Google map in a mobile application.
Relations:
I currently have 2 tables. Table one has:[trackid], [userid], [comment], [distance], [time], [top speed].
Table 2 has [trackid] [longitude] [latitude] and this is where all GPS markers are stored. What is an efficient way of storing this volume of GPS data while maintaining read performance?
New information:
Storing the GPS data in a KML file for the purpose of displaying them as a track on top of a Google map is a good solution that saves database space. Compressing the KML into a KMZ (basically a zipped KML wit a KMZ extension) greatly reduces file size further. KMZ loads much quicker than GPX and can be integrated with the Google Maps API as a KML layer. See this information from Google for further assistance. This seems to be the best solution so far for the intended requirement.

A: The choice of a particular database, as always, is tied to how you want to store the information and how you want to use it. As such, without knowing the exact requirements of your project, as well as the relationships of the data, the best thing to do would be to do some reading on the topic to determine what particular product or storage model is best suited to you.
A good place to start is reading blogs that compare the performance and uses of the databases (see attached):
http://kkovacs.eu/cassandra-vs-mongodb-vs-couchdb-vs-redis


text:
Q: In October CMS, how can I make an image editable in a Static Page? I'd like to set up a generic marketing template using the October CMS "Static Pages" plug-in.  The intention is to allow my clients to create their own marketing pages.  Let's assume that my layout contains HTML similar to this:

Some uneditable copy

{% placeholder copy default title="Main Page Copy" type="html" %}

Some Awesome Headline

Sea no omnium deserunt, eum tale movet sensibus te.

{% endplaceholder %}

How could I allow my clients to change the image?

A: You have a full explenation here
https://octobercms.com/blog/post/building-client-friendly-websites
Add this code to your layout
{variable name="banner" label="Banner" tab="Header" type="mediafinder" mode="image"}{/variable}

and this into your html markup

You will see the extra field in your backend

A: It doesn't seem to be currently supported: https://github.com/rainlab/pages-plugin/issues/13, but maybe you can use the media manager

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to mock the cls argument of a classmethod? I have a class that uses a classmethod as a custom constructor.
# my_module.py
class MyClass:
    def __init__(self, my_arg):
        self.my_arg = my_arg

    @classmethod
    def my_constructor(cls):
        return cls("my val")

I would like to assert in a test that the constructor has been called with a proper value and the instance returned.
I tried several ways of patching, but I couldn't get it working.
I tried patching the whole class, using the wraps argument to have the real method executed.
# my_test.py
from unittest import TestCase
from unittest.mock import patch

from my_module import MyClass

class MyClassTestCase(TestCase):
    @patch("my_module.MyClass", wraps=MyClass)
    def test_my_constructor(self, my_class):
        result = my_class.my_constructor()
        my_class.assert_called_once_with("my val")
        self.assertEqual(result, my_class.return_value)

The problem here is that the cls argument that the _my_module.MyClass.my_class_ method gets is not my Mock, but the real MyClass class.
My other idea was to use patch.object to patch the real __init__ constructor, but that doesn't work either. This time because __init__ should not return anything, but MagicMock has a return value.
# my_test.py
from unittest import TestCase
from unittest.mock import patch

from my_module import MyClass

class MyClassTestCase(TestCase):
    @patch.object(MyClass, "__init__")
    def test_my_constructor(self, init):
        result = MyClass.my_constructor()
        init.assert_called_once_with("my val")
        self.assertEqual(result, init.return_value)

Is there an actual way to assert the MyClass class has been instantiated by the _my_constructor_ with the given arguments and returned?

A: mock __new__ instead __init__
and assert will be
init.assert_called_once_with(MyClass, "my val")


text:
Q: Python Pandas conditional value elimination I am trying to drop values in one data frame based on value-based on another data frame. I would appreciate your expertise on this, please.
Data frame 1 – df1:
| A        | C              |
| -------- | -------------- |
| f        | 10             |
| c        | 15             |
| b        | 20             |
| d        | 30             |
| h        | 35             |
| e        | 40             |
-----------------------------

Data frame 2 – df2:
| A        | B              |
| -------- | -------------- |
| a        | w              |
| b        | 1              |
| c        | w              |
| d        | 1              |
| e        | w              |
| f        | 0              |
| g        | 1              |
| h        | 1              |
-----------------------------

I want to modify the df1 and drop(eliminate) values in column A if corresponding values in column B is 'w' in df2.
Resulted data frame looks like below.
| A        | C              |
| -------- | -------------- |
| f        | 10             |
| b        | 20             |
| d        | 30             |
| h        | 35             |
-----------------------------

A: You can first create a list from df2 with the values of A that have associated value of 'w' in B, and then use isin and ~ (which means not in essentially):
a = df2.loc[df2['B'].str.contains(r'w',case=False,na=False),'A'].tolist()
b = df1[~df1['A'].isin(a)]

And get back your desired outcome:
print(b)

   A   C
0  f  10
2  b  20
3  d  30
4  h  35

I find this link particularly helpful if you want to read more on Python's operators:
https://www.w3schools.com/python/python_operators.asp

A: What you're looking for is a merge with certain conditions:
# recreating your data
>>> import pandas as pd
>>> df1 = pd.DataFrame.from_dict({'A': list('fcbdhe'), 'B': [10, 15, 20, 30, 35, 40]})
>>> df2 = pd.DataFrame.from_dict({'A': list('abcdefgh'), 'B': list('w1w1w011')})

# merge but we further need to project that to fit the desired output
>>> df1.merge(df2[df2['B'] != 'w'], how='inner', on='A')
   A  B_x B_y
0  f   10   0
1  b   20   1
2  d   30   1
3  h   35   1

# what you're looking for
>>> df1.merge(df2[df2['B'] != 'w'], how='inner', on='A')[['A', 'B_x']].rename(columns={'B_x': 'C'})
   A   C
0  f  10
1  b  20
2  d  30
3  h  35

A: I assume that your first dataframe is df1 and second dataframe is df2.
First of all, list all the values of column A of df2 that value is 'w' in column B of df2.
df2_A = df2[df2['B'] == 'w']['A'].values.tolist()

# >>>output = ['a','c','e']

It will list all the values of column A of df2 that has value 'w' in column B of df2.
Then you can drop the values of df1 whose values lies in the list of above.
for i, val in enumerate(df1['A'].values.tolist()):
  if val in df2_A:
    df1.drop(i, axis=0, inplace=True)

Full code:
df2_A = df2[df2['B'] == 'w']['A'].values.tolist()

for i, val in enumerate(df1['A'].values.tolist()):
  if val in df2_A:  #checking if A column of df1 has values similar to above list
    df1.drop(i, axis=0, inplace=True)

df1

A: df1.merge(df2[df2['B']!='w'],how='inner').drop(["B"], axis=1)


text:
Q: How to send a Wake-on-LAN magic packet using PowerShell? I want to send a WOL magic packet using PowerShell, without falling back on any third party tools.

A: Here is the working PowerShell one-liner I am using to send a WakeOnLan packet:
$mac = '01-23-45-67-89-AB'; [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | Where-Object { $_.NetworkInterfaceType -ne [System.Net.NetworkInformation.NetworkInterfaceType]::Loopback -and $_.OperationalStatus -eq [System.Net.NetworkInformation.OperationalStatus]::Up } | ForEach-Object { $targetPhysicalAddressBytes = [System.Net.NetworkInformation.PhysicalAddress]::Parse(($mac.ToUpper() -replace '[^0-9A-F]','')).GetAddressBytes(); $packet = [byte[]](,0xFF * 102); 6..101 | Foreach-Object { $packet[$_] = $targetPhysicalAddressBytes[($_ % 6)] }; $client = [System.Net.Sockets.UdpClient]::new([System.Net.IPEndPoint]::new(($_.GetIPProperties().UnicastAddresses | Where-Object { $_.Address.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork })[0].Address, 0)); try { $client.Send($packet, $packet.Length,[System.Net.IPEndPoint]::new([System.Net.IPAddress]::Broadcast, 9)) | Out-Null } finally { $client.Dispose() } }
And here is a more readable version:
$mac = '01-23-45-67-89-AB';
[System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | Where-Object { $_.NetworkInterfaceType -ne [System.Net.NetworkInformation.NetworkInterfaceType]::Loopback -and $_.OperationalStatus -eq [System.Net.NetworkInformation.OperationalStatus]::Up } | ForEach-Object {
    $networkInterface = $_
    $localIpAddress = ($networkInterface.GetIPProperties().UnicastAddresses | Where-Object { $_.Address.AddressFamily -eq [System.Net.Sockets.AddressFamily]::InterNetwork })[0].Address
    $targetPhysicalAddress = [System.Net.NetworkInformation.PhysicalAddress]::Parse(($mac.ToUpper() -replace '[^0-9A-F]',''))
    $targetPhysicalAddressBytes = $targetPhysicalAddress.GetAddressBytes()
    $packet = [byte[]](,0xFF * 102)
    6..101 | Foreach-Object { $packet[$_] = $targetPhysicalAddressBytes[($_ % 6)] }
    $localEndpoint = [System.Net.IPEndPoint]::new($localIpAddress, 0)
    $targetEndpoint = [System.Net.IPEndPoint]::new([System.Net.IPAddress]::Broadcast, 9)
    $client = [System.Net.Sockets.UdpClient]::new($localEndpoint)
    try { $client.Send($packet, $packet.Length, $targetEndpoint) | Out-Null } finally { $client.Dispose() }
}

All common MAC address formats are supported and casing doesn't matter, for example:

*

*0123456789aB

*01-23-45-67-89-aB

*01:23:45:67:89:aB

*0123.4567.89aB
Works in powershell.exe (.NET Framework) and pwsh.exe (.NET/.Net Core).
Loosely based on code from Wake on LAN using C#.


text:
Q: How can I filter distinct values on a dropdown menu coming from an excel sheet on PowerApps? I have a dropdown menu, which accesses an Excel sheet called Clothes and takes in the distinct values from the column Color and then sorts them in ascending order with the following statement:
Sort(Distinct(Clothes,Color),Result,Ascending)

My Color column contains the following values:
Green
Blue
Grey
Red
Yellow
Pink

What I wanna do is filter the colors that contain the color letter g inside them in the dropdown. I would like for instance to only see Green and Grey after applying the filter. I tried the following:
Sort(Distinct(Filter(Clothes, "g" in Lower(Color))),Result,Ascending)

But I get an error saying:
The function 'Sort' has some invalid arguments. Invalid number of arguments
received 1, expected: 2

Can someone help me understand what I am doing wrong? Thanks in advance for any help you can provide

A: it looks like your distinct function is lacking a required argument! According to the Distinct reference docs found here, the Distinct function takes a Table argument, and a Formula argument. Your Table argument is the result of the Filter being applied, the Formula may be something like the column name you are trying to get distinct values from. In your case, most likely 'Clothes'.
Sort(Distinct(Filter(Clothes, "g" in Lower(Color)), <Formula goes here>),Result, Ascending)

Here is the example on how Distinct works from the documentation mentioned above.
Example
If you had an Employees table that contained a Department column, this function would list each unique department name in that column, no matter how many times each name appeared in that column:
Distinct(Employees, Department)


text:
Q: Negation of Bi-Lipschitz Condition If I have two distance functions $d',d$ on a set $X$ and I want to show that the Bi-Lipschitz condition is not satisfied by these distance functions, then how do I do so? I am confusing myself when it comes to negating the quantifiers in the statement.
Statement: $d$ and $d'$ satisfy the condition when there exists constants $\alpha, \beta > 0$ s.t $\alpha \leq d(x,y)/d'(x,y) \leq \beta$ for every $x,y \in X$ with $x \neq y$

A: For all $\alpha,\beta>0$ there exist $x_,y\in X$ such that
$$
\frac{d(x,y)}{d'(x,y)}<\alpha\quad\text{or}\quad\frac{d(x,y)}{d'(x,y)}>\beta.
$$


text:
Q: Solve for $x$ in $x(x-4)>0$ I tried:
$$x(x-4)>0 \Leftrightarrow x > 0 \cdot (x-4) \lor x-4 > 0 \cdot x \Leftrightarrow x > 0 \lor x > 4$$
And thus I get $x > 0 \lor x > 4$, but the right answer is $x < 0 \lor x > 4$.
What did I do wrong?

A: I've often found logical symbols just confuse the matter, so I'm going to use plain English here.
$(x)(x-4)>0$
For a product to be positive, EITHER both terms are positive (case 1) OR both terms are negative (case 2).
Case 1:
$x > 0$ AND $x > 4$. The latter case covers the former case completely, so you only require $x > 4$.
Case 2:
$x < 0$ AND $x < 4$. The former case covers the latter case completely, so you only require $x < 0$.
Those two cases are linked by an OR condition, so the final solution is $x < 0$ OR $x > 4$.


text:
Q: Construction of a system differential equation from the projected 2D solution curves !
A 3 variable system.I've been give the behaviors on the 2 projected planes. How do I arrive at the final 3d curve?
My question is a very simple one.I have a system of 3 variables:- X,Y,Z.I have been provided the solution curves for a couple of the 3 variables with respect to the other(fig.X vs Y,X vs Z). I know that for the X vs Z parabola graph,the system gradually changes as the time changes(like a limit cycle except that it is a open curve) thereby making it possible for the existence of 2 implicit functions at different times.
Is it possible to go from just these 2D solution plots
option (A) to a pair of 2 d.o.f system of autonomous/NON-autonomous differential equations? I'm thinking this would be on the same lines as the Kolmogorov theorem and hence easier to solve,since the theorem makes it clear about the existence of stability points and limit cycles.
$\frac{\mathrm{dX} }{\mathrm{d} t}=\\
 \frac{\mathrm{dY} }{\mathrm{d} t}=\\$
$\frac{\mathrm{dX} }{\mathrm{d} t}=\\
 \frac{\mathrm{dZ} }{\mathrm{d} t}=$
OR
option(B)  to a 3 system differential equation(like the Lorenz system)?
$\frac{\mathrm{dX} }{\mathrm{d} t}=\\
 \frac{\mathrm{dY} }{\mathrm{d} t}=\\
 \frac{\mathrm{dZ} }{\mathrm{d} t}=$
Can I think of these as the projected curves of the 3d phase plot and proceed from there on to maybe arrive at a 3dof system of d.e's(like the Lorenz system)?


text:
Q: Exception with batch insert I'm actually trying to use sql-batch insert with pyorient.
I actually have unique index on Edge(in, out) to prevent duplication because i didn't find a way to UPSERT Edge.
session_orientdb.command("CREATE INDEX indexRegroupe ON Regroupe (out, in) UNIQUE")

If I send my command every 100 rows and if one row throw an expection because orientdb found duplicateIndex (in, out) then the entire 100 rows are not insert.
So here is my loop :
 i = 0
 cmd = "BEGIN;"
 # Loop untill receiving the "poison pill" item (meaning : no more element to read)
 poison_pill = False
 while not(poison_pill):
     queries = p_queue.get()
     # Manage poison pill
     if queries is None:
         poison_pill = True
         p_queue.task_done()
         cmd += "commit;"
         session_orientdb.batch(cmd)
     else:
         for query in queries:
             i += 1
             cmd += query + ";"
     if (i > 100):
         i = 0
         cmd += "COMMIT retry 20;"
         try:
             session_orientdb.batch(cmd)
         except Exception as e:
             print (e)
             cmd = "BEGIN;"

queries are something like :
[
'UPDATE Expression SET libelle = "internat fille" UPSERT WHERE libelle = "internat fille";',
'CREATE EDGE Regroupe FROM (SELECT FROM Ontologie WHERE id = "40") to (SELECT FROM Expression WHERE libelle = "internat fille") set score=8;',
'UPDATE Cri SET id = "INTERNAT", libelle = "internat" UPSERT WHERE id = "INTERNAT";',
'CREATE EDGE Identifie FROM (SELECT FROM Expression WHERE libelle = "internat fille") to (SELECT FROM Cri WHERE id = "INTERNAT");'
]

What can i do?

A: You shoud use the condition if
Example
begin
let a= select from Regroupe where out=#9:0 and in=#10:0
if($a.size()>0){
    // edge exists so do other query
}
return $a

Hope it helps.


text:
Q: Apache Ignite cluster mode examples Does any one have any good tutorials of Apache Ignite.There seems to be very few practical tutorials or articles of Apache Ignite.

A: Have you seen Getting Started on readme.io?
Please indicate what you are missing from there.


text:
Q: Why startActivityForResult doesn't show the button "USE THIS FOLDER" on Android 11 emulator, as it does on Android 10 emulator in Android Studio? I have exactly the same problem like in this question:
How to hint content manager chooser to open directly on a selectable position with ACTION_OPEN_DOCUMENT_TREE
And there is no answer there.
This is my code:
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT_TREE);
startActivityForResult(intent, 43);

On Android 10 emulator it worked perfectly - it showed the button "USE THIS FOLDER".
But now i've reinstalled Android Studio and on Android 11 emulator it doesn't work - you must go to another folder and then return to the current one - only after that the button "USE THIS FOLDER" appears.

*

*folder chooser appears at folder "/storage/0F0F-2B1E/_Temp/2005" - there is no button "USE THIS FOLDER":
https://live.staticflickr.com/65535/51062052026_10183b6569_b.jpg

*i go to parent folder "/storage/0F0F-2B1E/_Temp" - the button appears:
https://live.staticflickr.com/65535/51062135572_6af2e01e2d_b.jpg

*i go back to "/storage/0F0F-2B1E/_Temp/2005" - the button is here and is selectable:
https://live.staticflickr.com/65535/51062135552_36e318ee19_b.jpg


text:
Q: Central Logging Service across Line-of-Business applications We have an Enterprise with various technologies: Web clients, Windows clients, .Net Services, Java Services, Cobol....
Most communication between systems is via web services. We have a standard which includes a corelation id in the header of the web service calls, which allows us to trace a request across systems.
What we would like to do is to have one place where we could go and check what has gone wrong and where did it get stuck. Our problem currently is that we have to check the log files of the individual systems.
Could anyone suggest a product or an implementation pattern to solve this problem.

A: The implementation pattern is centralized logging. Using a tool such as logstash, scribe, nxlog (note: I'm affiliated with this project) you can collect the logs at a central server where you can then analyze your data (with elasticsearch, graylog2, splunk, etc).

A: Even Splunk does an awesome job. But it's not free.

A: Checkout Graylog2: http://graylog2.org/

Manage your logs in the dark and have lasers going and make it look
  like you're from space.

It's the best (central) log mamnagement tool I've seen so far. Graylog is build to centralize syslog messages, but can also be feeded with log messages within your application send in AMQP.
There are libraries for PHP, Perl, Ruby, Python, node.js, .NET. Not sure, if there is a suitable library for you, but I bet you can implement Graylog pretty easy using the standard message protocols.


text:
Q: Generate charts with Google chart API i'am trying to generate a chart like this one: http://chartpart.com/ but i don't know how to do that exactly.Do i need to make the string that generates the chart manually or do i need to send the data to a google  server and receive the string?(if so how do i send the data?)
PS:i would like to do all this in c# and send the resulting string via web service.

A: apparently you need to generate the string yourself.I did just that and send the result to android via web service.
 [WebMethod]
        public ChartsClass GetChart(string UserId)
        {
            ChartsClass chart = new ChartsClass();
            DataSet1TableAdapters.WS_ChartIndicatorsTableAdapter adapter  =  new DataSet1TableAdapters.WS_ChartIndicatorsTableAdapter();
            DataSet1.WS_ChartIndicatorsDataTable table = adapter.GetChartIndicators(UserId);

            StringBuilder sbDescriptions = new StringBuilder();
            StringBuilder sbValues = new StringBuilder();

            for(int i= 0 ;i< table.Rows.Count ;i++)
            {
                DataSet1.WS_ChartIndicatorsRow chartRow = (table.Rows[i] as DataSet1.WS_ChartIndicatorsRow);
                if (i > 0)
                {
                    sbDescriptions.Append("|");
                    sbValues.Append(",");
                }

                sbDescriptions.Append(chartRow.SectorId + " - " + chartRow.SectorDescription );
                sbValues.Append(chartRow.NetSaleValue.ToString());
            }

            chart.ChartString = String.Format("http://chart.apis.google.com/chart?cht=p3&chtt={0}&chd=t:{1}&chs=480x200&chl={2}&chco=ff0000,0000ff",
              "Live Sales", sbValues.ToString(), sbDescriptions.ToString());

            return chart;
        }

And in android you can load the result in a web view.
 chartView  = (WebView)findViewById(R.id.activity_chart_view);
 ChartsClass chart = new ChartsClass(soapObject);
 chartView.loadUrl(chart.chartStringSource);

A: If you are trying to create a chart with user input, there's a wikiHow on that
 wikiHow Link: http://www.wikihow.com/Make-a-Google-Chart-with-User-Input
The graph this wikiHow creates is the same as the one on this website:
Website Link: http://www.quickcompromise.com/index.html


text:
Q: Calculating Time Difference between Each Users Attempt I have table in my Oracle database (v12.2.0.2.1) that tracks a users attempt to register an event and the timestamp of that attempt. The question I am trying to answer is the time difference between each users attempt.
The original table looks something like this:

USER_ACQUISITION_ATTEMPT_ID
USER_ID
RECORDING_DATE_ATTEMPT

1
189590
2022-OCT-12 14:57:54

2
189590
2022-OCT-12 14:58:15

3
189590
2022-OCT-12 15:01:50

4
189590
2022-OCT-12 15:02:11

5
189590
2022-OCT-12 15:02:40

6
189590
2022-OCT-12 15:03:51

7
22809
2022-OCT-12 15:04:32

8
189590
2022-OCT-12 15:09:05

9
189590
2022-OCT-12 15:10:16

10
189590
2022-OCT-12 15:10:24

11
189590
2022-OCT-12 15:10:42

12
189590
2022-OCT-12 15:13:00

13
178275
2022-OCT-12 15:45:22

14
180336
2022-OCT-12 15:53:25

15
180336
2022-OCT-12 15:53:50

Where each attempt is uniquely registered in order by the USER_ACQUISITION_ATTEMPT_ID. The USER_ID is the ID of the user that makes the attempt and the RECORDING_DATE_ATTEMPT is the timestamp.
I've created the following query that will show the time different between each attempt throughout the whole table using the LAG function to compare the dates from one row to the next and then just some math to calculate the time difference.
WITH dat AS
  (
  SELECT
    a.USER_ACQUISITION_ATTEMPT_ID,
    a.USER_ID,
    a.RECORDING_DATE_ATTEMP DAT1,
    a.RECORDING_DATE_ATTEMP DAT2
  FROM
    USER_ACQUISITION_ATTEMPT a

  UNION ALL

  SELECT
    c.USER_ACQUISITION_ATTEMPT_ID,
    c.USER_ID,
    c.RECORDING_DATE_ATTEMP DAT1,
    c.RECORDING_DATE_ATTEMP DAT2
  FROM
    USER_ACQUISITION_ATTEMPT c
   )

SELECT
  USER_ACQUISITION_ATTEMPT_ID,
  USER_ID,
  DAT1,
  LAG(DAT1,1) OVER (ORDER BY DAT1) LAG,
  TO_CHAR(DATE '1900-01-01' + ABS (LAG(DAT1,1) OVER (ORDER BY DAT1) - DAT1), 'HH24:MI:SS') as TIME_DIFF
FROM dat
group by
  USER_ACQUISITION_ATTEMPT_ID,
  USER_ID,
  DAT1

Which yields something like this:

USER_ACQUISITION_ATTEMPT_ID
USER_ID
DAT1
LAG
TIME_DIFF

1
189590
2022-OCT-12 14:57:54
NULL
NULL

2
189590
2022-OCT-12 14:58:15
2022-OCT-12 14:57:54
00:00:21

3
189590
2022-OCT-12 15:01:50
2022-OCT-12 14:58:15
00:03:35

4
189590
2022-OCT-12 15:02:11
2022-OCT-12 15:01:50
00:00:21

5
189590
2022-OCT-12 15:02:40
2022-OCT-12 15:02:11
00:00:29

6
189590
2022-OCT-12 15:03:51
2022-OCT-12 15:02:40
00:01:11

7
22809
2022-OCT-12 15:04:32
2022-OCT-12 15:03:51
00:00:41

8
189590
2022-OCT-12 15:09:05
2022-OCT-12 15:04:32
00:04:33

9
189590
2022-OCT-12 15:10:16
2022-OCT-12 15:09:05
00:01:11

10
189590
2022-OCT-12 15:10:24
2022-OCT-12 15:10:16
00:00:08

11
189590
2022-OCT-12 15:10:42
2022-OCT-12 15:10:24
00:00:18

12
189590
2022-OCT-12 15:13:00
2022-OCT-12 15:10:42
00:02:18

13
178275
2022-OCT-12 15:45:22
2022-OCT-12 15:13:00
00:32:22

14
180336
2022-OCT-12 15:53:25
2022-OCT-12 15:45:22
00:08:03

15
180336
2022-OCT-12 15:53:50
2022-OCT-12 15:53:25
00:00:25

A mentioned, I want to look at each user individually. The above query doesn't do that. For example, in the result table you will see the first row has the very first attempt and its timestamp. Under the LAG and TIME_DIFF column, there are nulls because no other attempt came before it. Each subsequent row grabs the last DAT1 and places it in the next row under the LAG column. That works fine until the next user tries an attempt. Where you see the USER_ID change from 189590 on USER_ACQUISITION_ATTEMPT_ID #6 to USER_ID 22809 on USER_ACQUISITION_ATTEMPT_ID #7, the last time stamp from the previous user is used against the first timestamp of the next user which is not what I want. The first attempt for any given user should have NULL for both the LAG and TIME_DIFF columns so that the query can sort of reset the calculation of the time differences for each user.
I hope I have explained the issue clearly, however if clarification is needed, please add some comments.

A: You don't need the UNION ALL in the common table expression.  It's just duplicating the data, which you then use GROUP BY to de-duplicate it.
Removing the UNION ALL means that you can remove the GROUP BY.
Then just use PARTITION BY in the analytic functions.
SELECT
  USER_ACQUISITION_ATTEMPT_ID,
  USER_ID,
  RECORDING_DATE_ATTEMP,
  LAG(RECORDING_DATE_ATTEMP)
    OVER (
      PARTITION BY USER_ID
          ORDER BY RECORDING_DATE_ATTEMP
    )
      AS LAG_RECORDING_DATE_ATTEMP
FROM
  USER_ACQUISITION_ATTEMPT


text:
Q: Initializing VBA classes - looking for a more elegant solution I'm currently working on a project where I want to initialize two different classes. I'm using a collection-class to store the sheets data.
First of all I'd like to iterate through the classes' properties; sadly it doesn't seem to be possible in VBA (without making some hacked solution).
The two functions below are almost the same, with the difference of one property. Can I somehow make a function that is more reusable in VBA?
Private Sub PasteCMSData()

    Dim PipelineCMSData As Collection
    Dim WonCMSData As Collection
    Dim I As Integer: I = 0

    Set PipelineCMSData = CollectPipeline()
    Set WonSheetName = CollectWon()

End Sub

Private Function CollectPipeline() As Collection
Private Function CollectPipeline() As Collection

    Const StartPos As Integer = 2

    Dim I As Integer: I = 0
    Dim PL As cPipeline
    Dim WorkbookData As Worksheet

    Set CollectPipeline = New Collection

    Set WorkbookData = Workbooks(WorkbookName).Worksheets(PLSheetName)

    For I = StartPos To WorkbookData.UsedRange.Rows.Count
        Set PL = New cPipeline
        With PL
            .ProjectType = WorkbookData.Cells(I, PLProjectType)
            .Segment = WorkbookData.Cells(I, PLSegment)
            .Customer = WorkbookData.Cells(I, PLCustomer)
            .Project = WorkbookData.Cells(I, PLProject)
            .Note = WorkbookData.Cells(I, PLNote)
            .CRM = WorkbookData.Cells(I, PLCRM)
            .Probability = WorkbookData.Cells(I, PLProbability)
            .Owner = WorkbookData.Cells(I, PLOwner)
            .SalesPhase = WorkbookData.Cells(I, PLSalesPhase)
            .NREPotential = WorkbookData.Cells(I, PLNREPotential)
            .RoyaltyPotential = WorkbookData.Cells(I, PLRoyaltyPotential)
            .Defcon = WorkbookData.Cells(I, PLDefcon)
            .ProjectStart = WorkbookData.Cells(I, PLProjectStart)
            .ProjectDuration = WorkbookData.Cells(I, PLProjectDuration)
        End With
        CollectPipeline.Add PL
    Next I

End Function

Private Function CollectWon() As Collection
Private Function CollectWon() As Collection

    Const StartPos As Integer = 2

    Dim I As Integer: I = 0
    Dim WO As cWon
    Dim WorkbookData As Worksheet

    Set CollectWon = New Collection

    Set WorkbookData = Workbooks(WorkbookName).Worksheets(WonSheetName)

    For I = StartPos To WorkbookData.UsedRange.Rows.Count
        Set WO = New cWon
        With WO
            .ActualCloseDate = WorkbookData.Cells(I, WOActualCloseDate)
            .ProjectType = WorkbookData.Cells(I, WOProjectType)
            .Segment = WorkbookData.Cells(I, WOSegment)
            .Customer = WorkbookData.Cells(I, WOCustomer)
            .Project = WorkbookData.Cells(I, WOProject)
            .Note = WorkbookData.Cells(I, WONote)
            .CRM = WorkbookData.Cells(I, WOCRM)
            .Probability = WorkbookData.Cells(I, WOProbability)
            .Owner = WorkbookData.Cells(I, WOOwner)
            .SalesPhase = WorkbookData.Cells(I, WOSalesPhase)
            .NREPotential = WorkbookData.Cells(I, WONREPotential)
            .RoyaltyPotential = WorkbookData.Cells(I, WORoyaltyPotential)
            .Defcon = WorkbookData.Cells(I, WODefcon)
            .ProjectStart = WorkbookData.Cells(I, WOProjectStart)
            .ProjectDuration = WorkbookData.Cells(I, WOProjectDuration)
        End With
        CollectWon.Add WO
    Next I

End Function

A: You could;

*

*Create a CommonAttributes class that stores the data shared by both classes (.ProjectType to .ProjectDuration). Both cWon & cPipeline hold an internal instance of this class.

*Move the initialize logic into the classes: CollectionWon.Add PL.LoadFromRange(I)

*Make the index values enumerations within the classes;
enum WOStuff
  WOActualCloseDate = 1
  WONREPotential = 9
  ...
end enum
Make LoadFromRange parse & store any class specific data (.ActualCloseDate), create an instance of CommonAttributes and invoke a method to load the common data:
myCommonAttributes.LoadFromRange(I, [paramArray of enum indexes])

A: This will never get too elegant, but there is one improvement that can be made on the list of initializing variables.
On the sheet where they are saved, you can put them in a two-column {UniqueKey}{Value} pair and convert that range into a table Ctrl-NT.
The table can be given some column names, like Key and Value, and a unique name. Then in VBA, you can access the values by looking up the Key programmatically and finding its corresponding value. That way the table can be reordered, and some keys can be 'missed' allowing the VBA code to pump in pre-programmed default values.
The table can be accessed in VBA as a ListObject.

On the internal storage of the Key-Value pairs. You may want to consider storing it in a Dictionary if that is more suitable for your implementation. That way you can lookup the Object by Key rather than only sequentially as in a Collection.
Have a look here to see examples of a Dictionary:
Does VBA have Dictionary Structure?


text:
Q: How we can screen sharing of particular portion of screen and customize screen in Web I have need to customize screen share of particular portion of screen part and need to customize fix part of agora please give some solution

A: Unfortunately you cannot do this from the Agora Web SDK yet. You can use our desktop versions for Mac or Windows and add this feature natively using Agora's SDK.
You may have to work with a canvas covering the whole screen and share just a small part through JavaScript.

*

*Documentation for screen-sharing on the web


text:
Q: Sum of Columns for multiple variables Using Shell Script (Bash), I am trying to sum the columns for all the different variables of a list. Suppose I have the following input of a Test.tsv file
           Win  Lost
Anna        1   1
Charlotte   3   1
Lauren      5   5
Lauren      6   3
Charlotte   3   2
Charlotte   4   5
Charlotte   2   5
Anna        6   4
Charlotte   2   3
Lauren      3   6
Anna        1   2
Anna        6   2
Lauren      2   1
Lauren      5   5
Lauren      6   6
Charlotte   1   3
Anna        1   4

And I want to sum up how much each of the participants have won and lost. So I want to get this as a result:
          Sum Win    Sum Lost
Anna        57         58
Charlotte   56         57
Lauren      53         56

What I would usually do is take the sum per person and per column and repeat that process over and over. See below how I would do it for the example mentioned:
cat Test.tsv | grep -Pi '\bAnna\b' | cut -f2 -d$'\t' |paste -sd+ | bc > Output.tsv
cat Test.tsv | grep -Pi '\bCharlotte\b' | cut -f2 -d$'\t' |paste -sd+ | bc >> Output.tsv
cat Test.tsv | grep -Pi '\bLauren\b' | cut -f2 -d$'\t' |paste -sd+ | bc >> Output.tsv
cat Test.tsv | grep -Pi '\bAnna\b' | cut -f3 -d$'\t' |paste -sd+ | bc > Output.tsv
cat Test.tsv | grep -Pi '\bCharlotte\b' | cut -f3 -d$'\t' |paste -sd+ | bc >> Output.tsv
cat Test.tsv | grep -Pi '\bLauren\b' | cut -f3 -d$'\t' |paste -sd+ | bc >> Output.tsv

However I would need to repeat this line for every participant. This becomes a pain when you have to many variables you want to sum it up for.
What would be the way to write this script?
Thanks!

A: This is pretty straightforward with awk. Using GNU awk:
 awk -F '\t' 'BEGIN { OFS = FS } NR > 1 { won[$1] += $2; lost[$1] += $3 } END { PROCINFO["sorted_in"] = "@ind_str_asc"; print "", "Sum Win", "Sum Lost"; for(p in won) print p, won[p], lost[p] }' filename

-F '\t' makes awk split lines at tabs, then:
BEGIN { OFS = FS }  # the output should be separated the same way as the input

NR > 1 {            # From the second line forward (skip header)
  won[$1] += $2     # tally up totals
  lost[$1] += $3
}

END {               # When done, print the lot.

  # GNU-specific: Sorted traversal or player names
  PROCINFO["sorted_in"] = "@ind_str_asc"

  print "", "Sum Win", "Sum Lost"
  for(p in won) print p, won[p], lost[p]
}


text:
Q: Send email from cell value google sheet, with other columns in email Apologises as I know this has been asked a few times, which I have learnt from other questions, however I'm still stuck and not sure how to continue.
I'm trying to make a google script to send an email notification to more then one person, based on a cell change, also sending in the email multiple cell values in the same row?
e.g. If Column 'C' changes, can I send an email with data from Column 'A' and 'B' in the same Row of the change in column 'C'?
This is the script I've been trying to play around with but not sure how to add multiple e-mails, and values from two more cells.
function sendNotifications() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var cell = ss.getActiveCell().getA1Notation();
var row = sheet.getActiveRange().getRow();
var cellvalue = ss.getActiveCell().getValue().toString();
var recipients = email@domain.com";
var message = '';
var cellA = ''
if(cell.indexOf('B')!=-1){
message = sheet.getRange('A'+ sheet.getActiveCell().getRowIndex()).getValue()
}
var subject = 'Update to '+sheet.getName();
var body = + cellvalue + '». For message: «' + message + '»';
MailApp.sendEmail(recipients, subject, body);
};

A: The code below checks if the edited cell was in column C and, if the condition is met, gets the values for columns A and B from the edited row. In Google Apps Script, onEdit() is the built-in function that fires automatically when you make changes in your spreadsheet. The 'e' parameter represents the event object that you can inspect to get more details about the context in which the event occurred
function onEdit(e){

  var editRange = e.range; // e is the event object generated by the Edit event
  var editRow = editRange.getRow();   // get row and column for the edited cell
  var editCol = editRange.getColumn();

  var sheet = SpreadsheetApp.getActiveSpreadsheet()
                            .getSheetByName("Sheet1"); // put your sheet name between the brackets

  if (editCol == 3) {   // checking if the edited cell was in column C

      var range = sheet.getRange(editRow, 1, 1, editCol - 1); // Take 1st cell in the edited row and make it span 1 row and 2 columns
      var values = range.getValues(); // get values array for the range
      Logger.log(values);

  }

}

The resulting variable ('values') is an array, so you must loop through it to get string values. As for the emails, you could store multiple emails in a cell, separated by comma. Calling split() method on a string will get you an array of values (emails) that you can then pass to the sendEmail method as the first parameter.
  var cellValue = "email@example.com,anotheremail@example.com,yetanotheremail@example.com";
  var recipients = cellValue.split(",");
  MailApp.sendEmail(recipients, "From google-apps-script", "hello from google apps script")


text:
Q: Azure function nodejs return 200 OK with empty response I'm using an Azure function to do some work, all is good except that I can not get the response body from the result:
module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    const fetch = require('node-fetch');
    const myURL= (req.query.apiURL|| (req.body && req.body.apiURL));

    fetch(myURL)
        .then(data => {
            if (!data.ok) {
                throw new Error('some error occurred');
            }

            return data;
        })
        .then(data => data.text())
        .then(text =>
            context.res = {
                body: text //here is the problem
            });
}

function.json
{
  "bindings": [
    {
      "authLevel": "anonymous",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    }
  ]
}

Fix
The empty response was related to using an async method without await
so just remove the async or use await with async.

A: Please do not use lambda expressions, you need to execute them like this, and there will be a result (not sure what you are doing, but I think there is something wrong with your design):
const fetch = require('node-fetch');

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');
    const myURL= (req.query.apiURL|| (req.body && req.body.apiURL));

    fetch(myURL)
        .then(
            //some logic here.
            context.res = {
                body: "This is a test." //here is the problem
            }
        );
}

A: Enhanced async/await, version of @BowmanZhu
    const fetch = require('node-fetch');
    module.exports = async function (context, req) {

     try{
      context.log('JavaScript HTTP trigger function processed a request.');
      const myURL= (req.query.apiURL || (req.body && req.body.apiURL)),
            fetchResp = await fetch(myURL),
            resBody =fetchResp.text();

      /** TODO LOGIC **/

      context.res = {
                        status:200,
                        body: resBody
                     };

     }catch(err){
       context.res = {
                        status:500,
                        body: err.message
                     };
     }
    }

A: In my case, I didn't updated the environment variable for database.


text:
Q: airflow pass jinja template to dag parameters I am trying to pass jinja template to the DAG constructor. As the airflow best practice suggest don't call Variables outside the execute method.
Below is the code snippet.
 dag = DAG(
        dag_id=dag_id,
        schedule_interval=schedule_interval,
        dagrun_timeout=timedelta(hours=max_dagrun),
        template_searchpath='{{var.value.sql_path}}')

But its failing to parse this.
Any suggestion how to pass these type of variables ? These are passed to dags not to the airflow operators.
Thanks in advance.


text:
Q: Como mandar 1 objeto e 1 vetor para uma API em C# com $http.post? Em minha aplicação criei uma API em C#, que é consumida por minha aplicação web em Angular. Preciso passar 1 objeto e 1 vetor como parâmetros para a API, mas o conteudo chega vazio na API, como resolver?
Segue abaixo meus códigos:
Parte em JavaScript:
    $scope.Exportar = function () {

   var listProdutos = {
       ListaCompraVenda : {listacompravenda: $scope.modelcompraevenda.listProdutos},
       ListaMeses : {meses:[$scope.dataBase.data1,
       $scope.dataBase.data2,
       $scope.dataBase.data3,
       $scope.dataBase.data4,
       $scope.dataBase.data5,
       $scope.dataBase.data6,
       $scope.dataBase.data7,
       $scope.dataBase.data8,
       $scope.dataBase.data9,
       $scope.dataBase.data10,
       $scope.dataBase.data11,
       $scope.dataBase.data12]}
    };

    $http.post($rootScope.raiz_ws + "/local/funcao", listProdutos )
     .then(function (response) {
        });
    };

Controller em C#
 [HttpPost]
    [Route("funcao")]
    public HttpResponseMessage Gerar(Classe listProdutos)
    {..}

Clase em C#:
public class Classe
{
    public List<CompraeVenda> ListaCompraVenda { get; set; }
    public List<string> ListaMeses { get; set; }

}

A: Consegui resolver mudando apenas o minha var listProdutos
var listProdutos = {
        ListaCompraVenda: $scope.modelcompraevenda.listProdutos,
        ListaMeses: [$scope.dataBase.data1,
        $scope.dataBase.data2,
        $scope.dataBase.data3,
        $scope.dataBase.data4,
        $scope.dataBase.data5,
        $scope.dataBase.data6,
        $scope.dataBase.data7,
        $scope.dataBase.data8,
        $scope.dataBase.data9,
        $scope.dataBase.data10,
        $scope.dataBase.data11,
        $scope.dataBase.data12]
    };

A: Tente colocar [FromBody] pro parâmetro ser passado no corpo da Request:
public HttpResponseMessage Gerar([FromBody]Classe listProdutos)


text:
Q: Switching from roaming profiles to folder redirection in a painless way We have a windows 2008 domain. We used to have roaming profiles which were pointing to "\nas\homes\\Profile.V2". Now we want to switch to local profile + redirected folders (Desktop and My Documents).
That's what we've done:

*

*go in A.D. and emptied "Profile path" and "Home folder" attribute.

*go phisically to the user computer, then go Computer > User profiles >   changed from "Roaming" to "Local"

*applied desktop & My documents redirection policy.

Now, the desktop & My documents folders have been redirected correctly. The problem is the profile. For instance, the AppData folder is still the one used with the roaming profiles, so if I delete it, the user profile on the client computer become unusable.
How can I tell to the clients that they need to keep the profile on the local computer?
I hope I've explained the problem in a clearly way.
Thanks in advance.
Matteo
EDIT
I didn't mention that there was a policy which redirected the AppData onto a shared folders, but now it's disabled (checked through gpresult on the client). Unfortunately the AppData folder still points there.

A: Redirection of the AppData folder is done via group policy, not by specifying a roaming profile.  You don't mention removing or reverting this group policy setting, so I'm guessing that's the problem.
Use gpresult to check whether there is still a policy in place.  You'll find it under Folder Redirection, the same place as the policy redirecting the desktop and documents folders.
Note that folder redirection policy has an option to keep the redirection in place even when the group policy no longer applies.  So you might have to explicitly set new policy with the "Redirect to the local userprofile location" option.


text:
Q: Deletion from vector took less time than deletion from list. Why? In C++ manual I found next:

Vectors are relatively efficient adding or removing elements from its
  end. For operations that involve inserting or removing elements at
  positions other than the end, they perform worse than the others, and
  have less consistent iterators and references than lists and
  forward_lists.

Also, in 'complexity' of 'erase' method of vector I found next:

Linear on the number of elements erased (destructions) plus the number
  of elements after the last element deleted (moving).

In 'complexity' of 'erase' method of list next:

Linear in the number of elements erased (destructions).

But when I tested it in the 30 millions elements in each container (I deleted from 24357 element to 2746591 element), I got that deleting from vector took 5 ms, but from list 8857 ms. Difference is huge and confusing...
Here is my code:
#include "stdafx.h"
#include <vector>
#include <list>
#include <iostream>
#include <ctime>

using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    const long int x = 30000000;
    vector<char> v;
    vector<char>::iterator itv1, itv2;
    list<char> l;
    list<char>::iterator itl1, itl2;
    unsigned start, end;

    long int first, last;

    cout << "Please enter first position: \n";
    cin >> first;
    cout << "Please enter last position: \n";
    cin >> last;

    for (long int i = 0; i < x; ++i)    {
        char c;
        c = (rand() % 26) + 'a';
        v.push_back(c);
        l.push_back(c);
    }

    cout << "Starting deletion\n";
    start = clock();
    itv1 = v.begin() + first;
    itv2 = v.begin() + last;
    v.erase(itv1, itv2);
    end = clock();
    cout << "End " << end-start << "\n";

    start = clock();
    itl1 = itl2 = l.begin();
    advance(itl1, first);
    advance(itl2, last);
    l.erase(itl1, itl2);
    end = clock();
    cout << "End " << end-start << "\n";
    return 0;
}

Could you explain - what causes such difference? My opinion - moving iterators in list much slower than in vectors - but I don't sure.
Many thanks!

A: In your case, likely because you're not measure the erase time, you're measuring the time taken for two advance calls and the erase call.
But more generally: because O() complexity only tells you about the algorithmic complexity not the actual time taken. O(1) can have a huge constant time value. Worse, the complexity is theoretical; it does not consider the realities of how hardware works.
In fact because the vector delete accesses memory in a linear fashion it can be efficiently cached and predicted whilst the list delete operates in a random access fashion. This can mean that vector delete is faster in practice than list delete when you have a small vector.

A: Erasing a range of elements from a vector requires merely the move of all trailing elements forward, to the start of the gap. This can be done with a memory move instruction, which is very efficient. It depends on the number of trailing elements and not on the number of deleted elements.
Deleting the same number of elements from a list requires iterating over the deleted range in the list and returning each element to the dynamic memory management which is clearly dependent on the number of elements you delete.
Later
Compare a delete of a range of 1000 near the start of the vector with the same operation almost at the end, and then do the same with the list. I predict that the vector will be slower in the first case and (much) faster in the second case.
And here's the result:
Please enter first position:
1
Please enter last position:
1000
Starting deletion
End 10000
End 0
/tmp$ ./del
Please enter first position:
29999000
Please enter last position:
29999999
Starting deletion
End 0
End 360000

:-)

A: It depends on the task you want to do.
Your task takes advantage of random access and contains only a single erase(): this plays to the strengths of vector.
I think a more interesting task would be to iterate the list and the vector one element at a time deleting every other element.
This forces sequential access and multiple calls to erase(): this will play to the strength of list.

A: The textbook answer is that list will be faster, but the textbook isn't always right! I can't prove it, but I suspect it is due to the fact that modern computers have special circuitry that allows them to shift blocks of memory around very fast. So while vector deletion is O(N) in some academic sense, in reality it boils down to (can boil down to) a single hardware operation, which ends up being faster than all the traversal and pointer fiddling you have to do when your remove an element from a list.

A: You are deleting all elements with a single call to erase, that means when you delete from vector you get an O(n), but only once. When you delete from list, you will have to iterate to the position 1 (itl1) and to position 2 (itl2), also if you are the deleting a lot of elements, the erase method will have a lot of elements to erase. In other words, unless you are erasing few elements from the begining of the list, you will also have O(n) for lists. Note that for iterating through elements in a vector is much faster than in a list, which may be the cause of those results.
Try deleting only the first element, and you should see the list being much faster than vector.


text:
Q: How do I use a power apps form for a lookup column? I have a SharePoint List (say "List-A") with plenty of columns, some of which are lookup columns.
These are just used to construct a choice columns, where the items in the choice drop down are the items of a column in a different List ("List-B").
I have used the function on SharePoint to integrate List-A with Power Apps Form. This creates a Power Apps form that is readily available.

For the Lookup choice columns, I have added List-B as the data source, and am using the items from the correct column as items in the choice that is linked to the lookup column. This correctly populates the drop down menu as expected.

Now when I publish this form and fill it from sharepoint (it pops up as it should hafter clicking New in the List view) I can fill the entire form and submit with no issue. However all the lookup columns remain blank, as if the form returned a null value instead of the selected.
I have both datasources set up:

The update property of the datacard connecting to the SharePoint List is equal to the Selected of the datacard containing the combobox (combobox is called DataCardValue43).

The items property of the combobox is equal to the correct column of List-B.

As an alternative solution, I have attempted to make a different column that is just one line of text. For this column, I have made a combobox once again setting the items property to the column in List-B. The intention was to return the selected value as a string. It was attempted thus:

where combobox1 once again manages to give the correct options in the drop down box but returns only Null.
To study it further, I have made a power apps flow that takes Create New Sharepoint List object as input. Here I see that the values are indeed Null

The one called "Return" is the text column that I made, and the other being the lookup column. I do notice that the Lookup column isn't called Value, but id. I don't know what to do with that information though.
I really just want to have a column in my power apps form that lets you choose and the choices are values from a column in a different List. What do I do, and why doesn't what I've already done work?
Thank you.

A: Please follow the steps below to solve the issue.
1: Add a Lookup column in SharePoint List.
2: Open that list in Power Apps by using the Customise Forms Option From SharePoint.
3: The Item property of Lookup field will be by default as follow:
Choices([@'CustomisingSharePointList'].LookupColumnListName)

4: There is no need to change/delete the lookup field with any custom dropdown or combo box. This is the point, where you are doing mistake by adding a custom combobox and replacing the original Lookup dropdown. If you want to change datasource, apply filter or sort the data, you can do all these thing to the same original lookup column.
e.g I have applied filter and sort functions to the existing data:
Sort(Filter(Choices([@'CustomisingSharePointList'].'LookupColumnListName'), Value in Filter(LookupColumnListDataSoure,Progress.Value = "Open").ID),Id)

5: When you will publish the list, it will work fine.
Note:
CustomisingSharePointList: List in which we have added a lookup column.
LookupColumnListName: List to which the lookup column actually belongs to.
LookupColumnListDataSoure: You need to add the original list as data source in power apps to use the above filter. This step is optional and applicable only if you apply filter like I did in step 4


text:
Q: pandas loc code to replace column contents no longer working following software update, key error but key is there I have some code which looks for the full name of a browser in a column and where found overwrites with a short name. this is to allow simplified filtering without version numbers in visualisations.
This code has worked fine for most of 2020. I get a new work laptop, reinstalled and updated anaconda and now it is giving a KeyError.
The code:
#clean up browser column data to remove version numbers
#for column 'Browser' in dataframe if object (string) contains Ch   Chrome else Sa  Safari else Ed  Edge else MS    MSIE else Fi    Firefox else Mo Mozilla else    Other

def browser_clean(webchat):

    webchat.loc[webchat['Browser'].str[:2] == 'Ch', 'Browser'] = 'Chrome'
    webchat.loc[webchat['Browser'].str[:2] == 'Sa', 'Browser'] = 'Safari'
    webchat.loc[webchat['Browser'].str[:2] == 'Ed', 'Browser'] = 'Edge'
    webchat.loc[webchat['Browser'].str[:2] == 'MS', 'Browser'] = 'MSIE'
    webchat.loc[webchat['Browser'].str[:2] == 'Fi', 'Browser'] = 'Firefox'
    webchat.loc[webchat['Browser'].str[:2] == 'Mo', 'Browser'] = 'Mozilla'

    return webchat

I've checked the key is there using:
print (webchat['Browser'])

with the output:
0               Safari 13.1.1
1         Chrome 85.0.4183.83
2        Chrome 84.0.4147.136
3        Chrome 79.0.3945.136
4         Chrome 85.0.4183.81
                 ...
17813     Chrome 85.0.4183.81
17814           Safari 13.1.2
17815     Chrome 85.0.4183.83
17816    Chrome 75.0.3770.143
17817           Safari 13.1.2
Name: Browser, Length: 17818, dtype: object

so it looks to me like the key is there?
The error message I see when I now run the code is as follows:
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-11-bcf8735bc33d> in <module>()
      5 webchat_drop_uw = drop_unwanted(webchat_dropped)
      6 webchat_new_cols = month_year(webchat_drop_uw)
----> 7 webchat_cleaned = browser_clean(webchat_new_cols)
      8 webchat_newOScol = short_OS(webchat_cleaned)
      9 webchat_final = strip_data(webchat_newOScol)

<ipython-input-8-b9c27fc07f46> in browser_clean(webchat)
      4 def browser_clean(webchat):
      5
----> 6     webchat.loc[webchat['Browser'].str[:2] == 'Ch', 'Browser'] = 'Chrome'
      7     webchat.loc[webchat['Browser'].str[:2] == 'Sa', 'Browser'] = 'Safari'
      8     webchat.loc[webchat['Browser'].str[:2] == 'Ed', 'Browser'] = 'Edge'

C:\Users\8485823\Anaconda\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    880
    881         elif key_is_scalar:
--> 882             return self._get_value(key)
    883
    884         if is_hashable(key):

C:\Users\8485823\Anaconda\lib\site-packages\pandas\core\series.py in _get_value(self, label, takeable)
    988
    989         # Similar to Index.get_value, but we do not fall back to positional
--> 990         loc = self.index.get_loc(label)
    991         return self.index._get_values_for_loc(self, loc, label)
    992

C:\Users\8485823\Anaconda\lib\site-packages\pandas\core\indexes\range.py in get_loc(self, key, method, tolerance)
    356                 except ValueError as err:
    357                     raise KeyError(key) from err
--> 358             raise KeyError(key)
    359         return super().get_loc(key, method=method, tolerance=tolerance)
    360

KeyError: 'Browser'

updated
key error coming in from column being dropped by this prior function, which it didn't used to do:
# remove unwanted columns (contain data)
def drop_unwanted(webchat):

    webchat.drop(
        labels = ["Visitor Name",
                "MCS",
                "Agent Name",
                "Agent Login Name",
                "Agent Full Name",
                "Agent Group",
                "Chat Start Reason",
                "Interactive",
                "Engagement ID",
                "Goal",
                "Campaign",
                "Target Audience",
                "Country",
                "State",
                "City",
                "Organization",
                "IP Address",
                "Personal Info Exists",
                "Customer Info Exists",
                "Marketing Source Exists",
                "Lead Exists",
                "Visitor Error Exists",
                "Service Activity Exists",
                "Viewed Product Exists",
                "Transaction Exists",
                "Cart Update Exists",
                "Pre-Chat Survey Exists",
                "Search Content Exists",
                "CoBrowse - Num Sessions",
                "CoBrowse - Num Interactive Sessions",
                "Alerted MCS",
                "Chat MCS"
               ],
        axis = 1,
        #index = None,
        errors ='ignore',
        inplace = True,
        )

    return webchat

Any ideas why it would drop a column that's not listed in my drop list?


text:
Q: Excel - Conditional Formatting fo When Any Cell in UsedRange Changes Value Also posted here:
https://www.tek-tips.com/viewthread.cfm?qid=1787250
I have to send workbooks off to managers in different departments and in each workbook, the managers might amend/change certain fields. The fields are not necessarily the same all the time, for example:
Manager 1 - Changes 3 fields in column A, 2 fields in column M and nothing on the rest of the sheet
Manager 2 - Changes 1 field in columns C - F, 5 fields in column J and 7 fields in column Y
Manager 3 - Changes 2 fields in column A, 4 fields in column B and nothing on the rest of the sheet
So I have a macro I am using in another workbook that will compare an 'original' version of a workbook with an 'updated' version but it only looks for differences in one specific column - so perhaps I could modify that macro to accomplish this task.
Here is the link to the macro I am referring to:
VBA - Copy Cells from Column A and B and Paste in New Sheet
I was however wondering, is there no kind of conditional formatting rule that can be applied to the workbooks - BEFORE they are sent to the managers - that highlights a row when a value in that row has been changed and changes the colour of the text in that cell? If there is even something like that which exists...

A: Answer received here and working perfectly:
https://www.tek-tips.com/viewthread.cfm?qid=1787250
COPY the SHEET and name it Review, for instance.
Then HIDE the original sheet.
Given that the original (hidden) sheet name is Original, in the Review sheet:
Select the Used Range. The TOP LEFT cell in my selection is A2.
Open the CF Wizard
Use a formula to determine which cell to format
=A2<>Original!A2
...and select a FORMAT.


text:
Q: facebook data deletion callback implementation in laravel using socialite I am implementing facebook data deletion callback but I got really lost and i can't continue on the JSON response that facebook is expecting.

*

*Return a JSON response that contains a URL where the user can check the status of their deletion request and an alphanumeric confirmation code. The JSON response has the following form:

{ url: '<url>', confirmation_code: '<code>' }
that is the part that I got lost and stuck. My question is

*

*what is the URL should do or show.

*what is the logic between the confirmation code

so far here is what I did on my controller.
<?php

namespace App\Http\Controllers\User\Auth\Socialite;

use App\Models\User;
use Illuminate\Http\Request;

class FacebookSocialLoginController extends SocialLoginFactory
{

    public function provider(): string
    {
        return 'facebook';
    }

    public function dataDeletionCallback(Request $request)
    {
        $signed_request = $request->get('signed_request');
        $data = $this->parse_signed_request($signed_request);
        $user_id = $data['user_id'];

        // here will delete the user base on the user_id from facebook
        User::where([
            ['provider' => 'facebook'],
            ['provider_id' => $user_id]
        ])->forceDelete();

        // here will check if the user is deleted
        $isDeleted = User::withTrashed()->where([
            ['provider' => 'facebook'],
            ['provider_id' => $user_id]
        ])->find();

        if ($isDeleted ===null) {
            return response()->json([
                'url' => '', // <------ i dont know what to put on this or what should it do
                'code' => '', // <------ i dont know what is the logic of this code
            ]);
        }

        return response()->json([
            'message' => 'operation not successful'
        ], 500);
    }

    private function parse_signed_request($signed_request) {
        list($encoded_sig, $payload) = explode('.', $signed_request, 2);

        $secret = config('service.facebook.client_secret'); // Use your app secret here

        // decode the data
        $sig = $this->base64_url_decode($encoded_sig);
        $data = json_decode($this->base64_url_decode($payload), true);

        // confirm the signature
        $expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
        if ($sig !== $expected_sig) {
            error_log('Bad Signed JSON signature!');
            return null;
        }

        return $data;
    }

    private function base64_url_decode($input) {
        return base64_decode(strtr($input, '-_', '+/'));
    }
}

A:

*

*what is the URL should do or show.

The purpose of this URL, is what the documentation said - to provide a way for the user, to check on the status of their deletion request.
Not all apps will be able to delete all personal user data immediately, the moment the user requests it.
Some might need to keep a subset of the data for legal reasons; others might simply need some extra processing time, because the process can not be handled in a totally automated matter, and a human needs to get involved.
So the user is given this status check URL in response to their request – so that they can go visit that URL tomorrow, or two weeks or six months from now, and check on the status of their deletion request - were you able to delete all data by now, will it still take some time, is there some data that won't be deleted for legal reasons, etc.

*what is the logic between the confirmation code

Just a different way to access the same information. Maybe checking the status via the URL you provided is not enough for the user, so they might want to call or send an email to your support staff, to inquire about the status of their deletion request. Then they can give your support people that code, and they can go look up the necessary information via that.
If you check the code examples in the documentation, they are using the same code value in the status check URL, and as the confirmation code. So you can use the same code for both.
Create it, store it in your database, and associate the status of a particular user's deletion request with that code.


text:
Q: Handling set-based operations in SQL I'm trying to better understand set-based logic and simplify a piece of code I'm working on. Here's an example of what I am currently working with (it doesn't work currently for reasons that will quickly become apparent):
SELECT
    userid,
    rn = ROW_NUMBER() OVER (ORDER BY username)
    FROM user
    WHERE username like 'test%'

WHILE rn between 1 and 100
    <RUN SP USING INFORMATION>
WHILE rn between 101 and 200
    <RUN SP WITH DIFFERENT INFORMATION>

For the purposes of example, assume there are 200 rows that meet the criteria in the SELECT statement. Also assume that we can't make changes to the user table. My question is, without using a temp table and without (hopefully) using a WHILE loop, how else could I handle this?
Note that the SP referenced is a rather complex stored procedure that needs to use the information within that SELECT statement. I could handle this by using a temp table and going row by row, but I'm trying to understand other approaches to this where I could handle it in batches.

A: Several years ago I wrote a SQL-based utility specifically to address needs like this.  It is detailed in this article at another site here: http://www.sqlservercentral.com/scripts/Administration/69737/. (If you want, I can include it here as well, but it is fairly long)
Please note the following about it:

*

*It is written entirely in T-SQL, and

*It uses no Cursors or While loops whatsoever.

You would probably address your problem with this tool something like this:
EXECUTE OVER_SET '
    IF {rn} between 1 and 100
        <RUN SP USING INFORMATION>
    IF {rn} between 101 and 200
        <RUN SP WITH DIFFERENT INFORMATION>
    ',
@from = '
    (SELECT
            userid,
            rn = ROW_NUMBER() OVER (ORDER BY username)
    FROM user
    WHERE username like ''test%'') aa '
@subs1 = '{userid}=userid',
@subs2 = '{rn}=rn',
@quote = '"'        -- Allows you to use (") for quotes inside the 1st string
;

Since that is a sign-up site, I am posting the code below (long):
CREATE PROC
  OVER_SET (
    @command AS NVARCHAR(MAX),       -- Template SQL command
    @from    AS NVARCHAR(MAX),       -- FROM..WHERE clause string
    @subs1   AS NVARCHAR(MAX) = N'', -- Substitution parameters, these are
    @subs2   AS NVARCHAR(MAX) = N'', -- of the form "<find>=<repl>" where:
    @subs3   AS NVARCHAR(MAX) = N'', -- <find> will be searched for in @command, and
                     -- <repl> will replace it, if it was found
                     -- (typically, <repl> should be a column name
                     -- returned by the FROM clause)
    @print   AS BIT = 1,             -- 0 = suppress PRINT of the SQL before executing
    @catch   AS VARCHAR(12) = 'continue',
                     -- TRY/CATCH option parameters. Choices are:
                     -- 'continue' on an error, print a message & continue
                     -- 'ignore' attempt to suppress all errors
                     -- 'fail' try to re-raise the error
                     -- 'none' no TRY/CATCH blocks
    @use_db  AS NVARCHAR(255) = N'', -- DB to switch to befor execution of the SQL text
    @quote   AS NVARCHAR(8)   = N''  -- search for this character & replace with (').
    )
AS
--
DECLARE @qt AS NVARCHAR(1), @cr AS NVARCHAR(1);
SELECT  @qt = N'''',        @cr = N'
';
DECLARE @find1  AS NVARCHAR(MAX), @prfx1  AS NVARCHAR(MAX), @sufx1 AS NVARCHAR(MAX)
DECLARE @find2  AS NVARCHAR(MAX), @prfx2  AS NVARCHAR(MAX), @sufx2 AS NVARCHAR(MAX)
DECLARE @find3  AS NVARCHAR(MAX), @prfx3  AS NVARCHAR(MAX), @sufx3 AS NVARCHAR(MAX)
DECLARE @prtst  AS NVARCHAR(MAX), @prfxC  AS NVARCHAR(MAX), @sufxC AS NVARCHAR(MAX)
DECLARE @newdb  AS NVARCHAR(MAX), @declr  AS NVARCHAR(MAX)
DECLARE @NewCmd AS NVARCHAR(MAX), @GenCmd AS NVARCHAR(MAX)
;
SELECT
 @find1 = CASE WHEN @subs1 = N'' THEN N'' ELSE LEFT(@subs1,CHARINDEX(N'=',@subs1)-1) END,
 @prfx1 = CASE WHEN @subs1 = N'' THEN N'' ELSE N'REPLACE(' END,
 @sufx1 = CASE WHEN @subs1 = N'' THEN N'' ELSE N',@find1,'+RIGHT(@subs1,LEN(@subs1)-CHARINDEX(N'=',@subs1))+N')' END,
 @find2 = CASE WHEN @subs2 = N'' THEN N'' ELSE LEFT(@subs2,CHARINDEX(N'=',@subs2)-1) END,
 @prfx2 = CASE WHEN @subs2 = N'' THEN N'' ELSE N'REPLACE(' END,
 @sufx2 = CASE WHEN @subs2 = N'' THEN N'' ELSE N',@find2,'+RIGHT(@subs2,LEN(@subs2)-CHARINDEX(N'=',@subs2))+N')' END,
 @find3 = CASE WHEN @subs3 = N'' THEN N'' ELSE LEFT(@subs3,CHARINDEX(N'=',@subs3)-1) END,
 @prfx3 = CASE WHEN @subs3 = N'' THEN N'' ELSE N'REPLACE(' END,
 @sufx3 = CASE WHEN @subs3 = N'' THEN N'' ELSE N',@find3,'+RIGHT(@subs3,LEN(@subs3)-CHARINDEX(N'=',@subs3))+N')' END,
 @newdb = CASE WHEN @use_db= N'' THEN N'' ELSE N'USE [' + @use_db + N'];' + @cr END,
 @declr = N'DECLARE @_Num AS INT, @_Lin AS INT, @_Err AS NVARCHAR(MAX), @_Msg AS NVARCHAR(MAX);'+@cr
;
;WITH
 [base] AS (SELECT cmd = @command),
 [quot] AS (SELECT cmd = CASE @quote WHEN N'' THEN cmd ELSE REPLACE(cmd, @quote, @qt) END FROM [base]),
 [dble] AS (SELECT cmd = N'N'+@qt+REPLACE(cmd, @qt, @qt+@qt)+@qt FROM [quot]),
 [prnt] AS (SELECT cmd = CASE @print WHEN 1 THEN N' PRINT '+cmd+';'+@cr ELSE N'' END
                       + N' EXEC('+cmd+N');' FROM [dble]),
 [ctch] AS (SELECT cmd =
    CASE @catch WHEN N'none' THEN cmd
    ELSE N'BEGIN TRY'+@cr+cmd+@cr+N'END TRY'+@cr+N'BEGIN CATCH'+@cr
    + N' SELECT @_Num=ERROR_NUMBER(), @_Lin=ERROR_LINE(), @_Err=ERROR_MESSAGE()'+@cr
    + CASE @catch
        WHEN N'continue' THEN
                N' SELECT @_msg=''Continuing after Error(''+CAST(@_Num AS NVARCHAR)+'') at Line ''+CAST(@_Lin AS NVARCHAR)+'''
                         +@cr+' ''+@_Err;'+@cr
               +N' PRINT @_msg; '+@cr
               +N' PRINT '' ''; '+@cr
        WHEN N'ignore' THEN N' -- ignore = do nothing'+@cr
        WHEN N'fail' THEN
                N' SELECT @_msg=''Failing after Error(''+CAST(@_Num AS NVARCHAR)+'') at Line ''+CAST(@_Lin AS NVARCHAR)+'''
                         +@cr+' ''+@_Err;'+@cr
               +N' RAISERROR(@_Num, 16, 1);'+@cr
               +N' PRINT '' ''; '+@cr
        ELSE N' --BAD else branch, shouldnt get here' END
    + N'END CATCH;' END FROM [prnt])
SELECT
    @NewCmd = @prfx1+@prfx2+@prfx3+ N'@command' +@sufx1+@sufx2+@sufx3,
    @command = cmd + @cr
FROM [ctch]
;
SELECT @GenCmd = '
DECLARE @sql AS NVARCHAR(MAX); SET @sql = '''+@newdb+ +@declr+ '''
;WITH
  [-@from]  AS ( SELECT * FROM ' +@from+ ' )
, [-@subs]  AS ( SELECT [-NewCmd] = ' +@NewCmd+ ' FROM [-@from] )
, [-@print] AS ( SELECT [-NewCmd] = [-NewCmd] FROM [-@subs] )
SELECT
  @sql = @sql + ''
'' + [-NewCmd]
FROM [-@subs]
;
EXEC sp_executesql @sql;
'
;
EXEC sp_executesql @GenCmd
, N'@command NVARCHAR(MAX), @from NVARCHAR(MAX), @find1 NVARCHAR(MAX), @find2 NVARCHAR(MAX), @find3 NVARCHAR(MAX)'
, @command, @from, @find1, @find2, @find3
;

Here are the post-comments which include some examples:
 Example Usages

1) INSERT..EXECute:
Demonstrates capturing the SELECT output from an EXECUTE OVER_SET that
searches every database in the SQL Server Instance for routines with
the work "cursor" in them.
--

CREATE TABLE #temp (DB sysname, [Schema] sysname, Routine sysname);
INSERT INTO #temp
  EXECUTE OVER_SET '
    SELECT ROUTINE_CATALOG, ROUTINE_SCHEMA, ROUTINE_NAME
      FROM [{db}].INFORMATION_SCHEMA.ROUTINES
      WHERE ROUTINE_DEFINITION like "%cursor%"',
    @from = 'sys.sysdatabases WHERE dbid > 4',
    @subs1 = '{db}=name',
    @quote = '"'
;
SELECT * from #temp;
DROP table #temp;

--
The @from argument returns the list of non-system databases in the server,
and the @susbs1 argument "{db}=name" tells it to replace every instance
of "{db}" in the command strings with the value of the [name] column (from
sys.sysdatabases). Note also the @quote argument's value (") allows us to
use a single quotation mark in the quoted command text instead of having
to use double apostrophes (ie, ' "%cursor%" ', instead of ' ''%cursor%'' ').

--======

2) Nested Example:
Demonstrates, nesting OVER_SET execution to operate against the combination
of to different sets, the second dependent on the first. Specifically,
it searches every non-system database for every user that is a windows
user or group, and then attempts to map them back to a server Login of
the same name.
--

EXECUTE OVER_SET '
   EXECUTE OVER_SET "
        ALTER USER [{name}] WITH LOGIN = [{name}];
        PRINT `USER {name} has been mapped to its Login.`;",
     @from   = "sys.database_principals
            WHERE ( type_desc = ""WINDOWS_GROUP"" OR type_desc = ""WINDOWS_USER"" )
            AND name NOT like ""%dbo%"" AND name NOT LIKE ""%#%"" ",
     @use_db = "{db}",
     @subs1  = "{name}=name",
     @catch  = "continue",
     @print  = 1,
     @quote  = "`";
     ',
  @from  = 'sys.sysdatabases
       WHERE dbid > 4',
  @subs1 = '{db}=name',
  @catch = 'continue',
  @print = 0,
  @quote = '"';

--
The outer OVER_SET uses the @from argument to return the list of all databases
which the @subs1 argument "{db}=name", uses to modify the inner OVER_SET
commands @use_db argument, cuasing the inner execution to USE [{db}} to each
database in turn. The inner execution's @from argument returns the list
of database users that are WINDOWS_* user or group, and the @subs1 ({name}=name)
cause the "{name}" token to be replaced with the value of the [name] column
from the database_principals table.

Note that two different @quote characters are used ( ("), then (`) ), removing
the need for double or even quadruple apostrophes in the inner command text.
(also note, that the @from argument text does not benefit from this, and can
only use the outer command quote (") becuase it is part of the outer command
text argument.

A: You can't call a stored procedure as part of another query, so it would be impossible to do what you're asking as a set-based operation without rewriting the stored procedures.

A: Is it possible to use UDFs instad of SP?  In that case you can include the UDF with parameters from the SELECT statement in one go.  Obviously UDFs have limitations but I guess it depends on the complexity of your SP.


text:
Q: How to put green border for valid fields in ASP.NET MVC I cannot find any easy way of making borders green for fields that are valid in ASP.NET MVC. I am using DataAnnotations and Unobtrusive jquery validation. I have all the default validation styles and I can easily change border color of invalid controls and colour of the messages. However, there there is no style being added to valid fields. How can I do it. DO I need to hijack it with jquery?
Another question I have is how to trigger validation on fields on blur without writing much of the custom code? By default it validates only on form submit. Do I have to use Remote Validation for that? I was hoping there was an easy setting somewhere to enable it.
EDIT
   <% using (Ajax.BeginForm("SaveSupplier",
                             "Suppiers",
                             new AjaxOptions
                             {
                                 UpdateTargetId = "supplier-details-wrapper",
                                 InsertionMode = InsertionMode.Replace
                             },
                             new { id = "supplier-details-form", enctype = "multipart/form-data" }))
    { %>

                <%: Model.PageDescription %>

            <%: Html.AntiForgeryToken() %>

            -- MY FIELDS HERE --

    <% } %>

        <button id="save-button" type="button" class="submit-button">Save</button>
        <button id="cancel-button" type="button" class="submit-button">Cancel</button>

ANd javascript

I also have

And in web.config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />

My issue is that it only does validation on server side no matter what I do. How do I manually trigger it in javascript. I tried various things and it always does postback to the server. $("#my-element-id").valid() sort of works, it returns 1 or 0, but it doesnt highlight text box and doesnt show error. Validate doesnt seem to do anything. I have a suspicion it has something to do with my buttons being outside of Ajax form or because of AntiFormgeryToken.

A: As for validation on client side add this code in your web.config
<appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

And for border color, try to put this in your css:
input:valid { border-color:green; }

A: Style valid elements
My approach to this would be to set the default styling of the elements to be valid (green border).  Then use the validation style classes (e.g. input-validation-error) to override the default styles when an input item is invalid.
Validate on blur
To do this you need to change the validation settings.  This can be done like so.
var validator = form.data("validator");
    if (validator){
        validator.settings.onkeyup = false; // Disable keyup validation
        validator.settings.onfocusout = function (element){
            $(element).valid();
        };
    }

I answered the same question regarding this here

A: I found my issue. I was loading partial views inside partial views. So content was loading dynamically. Adding this fixed on blur validation:
$(function () {
        $.validator.unobtrusive.parse(document);
        $("input[data-val=true]").on("blur", function () {
            $(this).valid();
        });
});

Also
input.valid
{
    border: 1px solid rgb(19, 147, 7);
}

worked, but input:valid didn't as it was setting border to green to all fields, even invalid ones.


text:
Q: how to convert 2012-05-03T25:00:00 to 2012-05-04T01:00:00 in unix I am not sure how this will be done in unix can anybody help/suggest to convert
    2012-05-03T25:00:00 to 2012-05-04T01:00:00 in Unix command/script
In my file I have more than one occurrence with different times those needs to converted to next day
2012-05-03T25:00:00 to 2012-05-04T01:00:00
2012-05-03T26:50:00 to 2012-05-04T02:50:00
2012-05-03T31:59:59 to 2012-05-04T07:59:59

etc
I tried it but somehow sed is not working
Date.txt
2009-09-12T05:18:@00@+10:00,D,
2009-09-12T05:24:00+10:00,2009-09-12T05:24:@00@+10:00,D,
2009-09-12T05:25:00+10:00,2009-09-12T05:25:@00@+10:00,D,
2009-09-12T05:27:00+10:00,2009-09-12T05:27:@00@+10:00,D,
2009-09-12T30:29:00+10:00,2009-09-12T05:29:@00@+10:00,D,
2009-09-12T29:31:00+10:00,2009-09-12T05:31:@00@+10:00,D,
2009-09-12T28:33:00+10:00,,D,
2009-09-12T27:00:@00@+10:00,U,
2009-09-12T26:01:00+10:00,2009-09-12T05:01:@00@+10:00,U,
2009-09-12T24:04:00+10:00,2009-09-12T05:04:@00@+10:00,U,
2009-09-12T24:59:59+10:00,2009-09-12T05:06:@00@+10:00,U,
2009-09-12T30:08:00+10:00,2009-09-12T05:08:@00@+10:00,U,
2009-09-12T31:59:59+10:00,2009-09-12T05:10:@00@+10:00,U,
2009-09-12T05:17:00+10:00,,U,
2009-09-12T25:25:@00@+10:00,D,

script.sh
awk -F"T" -v OFS=',' '{print $1}' date.txt > tmpdate
uniq -d tmpdate > tmpuniq
rm tmpdate
date1=`cat tmpuniq`
date2=`date --set="$date1" +%F`
date3=$(date --date="$date2" -d "+1 day" +"%F")
T1=$date2+"T24"
T2=$date3+"T00"
echo $T1
echo $T2
dos2unix date.txt
#sed -i 's/$T1/$T2/g' date.txt > test.txt
#sed -i 's/"$T1"/"$T2"/g' date.txt > test.txt
sed -i 's/'$T1'/'$T2'/g' date.txt

Any help much appreciated

A: If you have Tcl on your system, the clock command makes it pretty easy:
set t 2012-05-03T31:59:59
lassign [split $t T] date time
lassign [split $time :] hour min sec
set base [clock scan $date -format %Y-%m-%d]
set new [clock add $base $hour hours $min minutes $sec seconds]
puts [clock format $new -format %Y-%m-%dT%T]   ;# -> 2012-05-04T07:59:59

Update for cygwin:
first, using the cygwin installer, install the version 8.5.x of the "tcl" package (located in the Interpreters category). Then, you can do this
normalize_time() {
    printf '
        lassign [split "%s" T] date time
        lassign [split $time :] hour min sec
        set base [clock scan $date -format %%Y-%%m-%%d]
        set new [clock add $base $hour hours $min minutes $sec seconds]
        puts [clock format $new -format %%Y-%%m-%%dT%%T]
    ' "$1" | tclsh
}
normalize_time 2012-05-03T31:59:59

A: You will basically need to parse the erroneous time specification, convert everything to seconds, add it back together, and convert it back to a proper date.
date -d "date" +%s produces seconds since January 1, 1970.  date -d @1234567890 converts a date in this format back to a regular human-readable date.
#!/bin/sh

IFS=T:

while read date hh mm ss; do
    basedate=$(date -d "$date" +%s)
    date -d @$(echo "$basedate+($hh*60*60)+($mm*60)+$ss" | bc) +%FT%T
done <<EOF
    2012-05-03T25:00:00
    2012-05-03T26:50:00
    2012-05-03T31:59:59
EOF

I didn't have bc on this computer so I replaced my original attempt with a small awk script, but it's not very readable.
awk 'END { print '"$basedate"'+('"$hh"'*60*60)+('"$mm"'*60)+'"$ss"'}' </dev/null

If you don't have a recent enough version of GNU date, you can find some alternative ways at http://www.antonolsen.com/2006/04/06/bash-convert-unix-timestamp-to-a-date/

A: finally I got a solution with a bug (if date is last day of the month then this will not work but I can live with that)
and did a clumsy job
date1=`cat date.txt | awk -F. '{print substr($1,1,10)}'|uniq |head -1`
echo $date1
date2=$date1"T24"
date21=$date1"T25"
date22=$date1"T26"
date23=$date1"T27"
date24=$date1"T28"
date25=$date1"T29"
date26=$date1"T30"
date27=$date1"T31"
date3=$(date --date="$date1" -d "+1 day" +"%F")
echo $date2
cat date.txt | grep "$date2"
tmpdate=`echo $date1 | sed -e 's/-//g'`
echo $tmpdate
date4=`echo $(date -d $(echo \`expr $tmpdate + 1\`F) +"%F")`
echo $date4
date41=$date4"T00"
date42=$date4"T01"
date43=$date4"T02"
date44=$date4"T03"
date45=$date4"T04"
date46=$date4"T05"
date47=$date4"T06"
date48=$date4"T07"

sed -i 's/'$date2'/'$date41'/g' date.txt
sed -i 's/'$date21'/'$date42'/g' date.txt
sed -i 's/'$date22'/'$date43'/g' date.txt
sed -i 's/'$date23'/'$date44'/g' date.txt
sed -i 's/'$date24'/'$date45'/g' date.txt
sed -i 's/'$date25'/'$date46'/g' date.txt
sed -i 's/'$date26'/'$date47'/g' date.txt
sed -i 's/'$date27'/'$date48'/g' date.txt

If anyone wants to improve this script please go ahead.
Once again thanks to all.

A: First, use cat 'yourfile' to open it. Then do a loop on each line. Then use grep and cut. That's really simple to do and the most efficient way for you to learn is to go through the man pages of cat, grep, and cut.
Hope it'll help.


text:
Q: How to remove hieroglyphs from message, recieved on Windows 10 machine? I have an app, which sends e-mail messages with some pictures attached, using SmtpClient class. I've noticed strange thing. After recieving the message on some e-mail client(not in browser) on Windows 10 computer - there are a lot of hieroglyph symbols at the end of the message body. Imagine situation: you are trying to send message using hands(not from code). You can simply attach some picture to the message by their paths so, that they are really simple attachments. But you can also crop some image from the Paint and insert it into the body - in that case the cropped image will be seen in the body and it will be attached to the message, too. So I think, that SmtpClient class works like the second variant. And the hieroglyphs are the encoded image, which was cropped and inserted into the body. The question is, why does that happen only on Windows 10 and only using e-mail client programs?
I've tried to attach pictures at first, and only after that the body has been filled. The second idea was to fill the body and remember it, assigning it to temporary variable, then attaching files, and after that clearing current body value and assigning temporary variable to it. Such ways didn't help.
Making message:
    public MailMessage MakeMessage()
    {
        MailAddress from = new MailAddress("from@address.com", Name);
        MailAddress to = new MailAddress("to@address.com");

        MailMessage message = new MailMessage(from, to);

        message.Body = MessageText; // typed text
        string temp = message.Body;

        message.BodyEncoding = Encoding.Unicode;
        message.ReplyTo = new MailAddress(Mail);

        CreateAttachments(message);

        message.Body = null;
        message.Body = temp;

        return message;
    }

During using the app - some screenshots can be created, storing dynamicly.
So this method creates physical files for that screenshots and then attaches them to the message:
    public void CreateAttachments(MailMessage message)
    {
        foreach (var pict in FeedBackHelper.ScreenshotsCollection)
        {
            if (pict.IsChecked)
            {
                BitmapEncoder encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(pict.Image));

                var pathToPicture = Path.Combine(FeedBackHelper.feedBackTempPath, $"{pict.Name}.jpg");

                using (var fileStream = new FileStream(pathToPicture, FileMode.Create))
                {
                    encoder.Save(fileStream);
                }
                message.Attachments.Add(new Attachment(pathToPicture));
            }
        }

    }

I've checked this, sending messages on 3 Windows 7 and 3 windows 10 computers. As result messages with image attachments look like they must on Windows 7 in each e-mail client or browser, but on Windows 10 messages consist of simple attachment and body with a lot of hieroglyphs at the end. Any ideas?

A: Yes, the problem was in encoding. Changed Unicode on UTF-8, although UTF-7 works, too.
But that behavior has really confused me.


text:
Q: ¿Como hacer que se añada contenido a un grid cuando rellene una forma y clicke en el boton "Submit"? [JavaScript y CSS] ¿Como puedo hacer que se añada contenido a un grid cuando rellene una forma y clicke en el boton "Submit"? [JavaScript y CSS]
Alguien me puede ayudar? Gracias, soy nuevo en Javascript.


text:
Q: Tdd workflow when you find Single Responsibility Principle violation I trying to follow TDD. So here is my problem
I have interface Risk with method
boolean check(...)

Risk1, and Risk2 are implentations deveped test first, so now they are fully covered.
I decided that unit that check all risks (CompositeRisk) also could implement Risk.
CompositeRisk applies OR on each Risk1 and Risk2 rezult (If one risk is true then whole this is risky). Still everything is test first.
Now I am looking to one of the risk and thinking - this one has word "AND" and checks different fields. It seems that I can split it to two object and create one more CompositeAndRisk which would apply And on both splitted risks. This way I could construct DSL for risks decision tree (seems nice because risks rules could changes a lot).
So what I should do with risk's I split tests? Should I rename i to CompositeAndRiskTest? should I delete it?, should I write test for splitClasses?

A: First of all, I suggest that you turn the CompositeRisk class into an interface, and have two separate subclasses of it: CompositeOrRisk and CompositeAndRisk. This is just about the design though.
Regarding your question, I believe there's no single right answer, so let me share how I see it.
As you know, in TDD there are concrete steps you follow (that comprise the TDD cycle), and there's a specific state the tests should be at in between each of them. Here's what I mean:
[State = No tests]
1. Write a test that fails
[State = Test fails]
2. Write as little code as possible in order for the test to pass
[State = Test passes]
3. Refactor
[State = Test still passes]

Given that this is what we aim for in TDD, I would do the changes you're talking about in the refactoring phase, including refactoring the tests accordingly.
This means that if I'm splitting a class, I'll be splitting the relevant test as well. At no point should the tests fail, as I'm only changing the structure of the code, not what it does (this is the meaning of refactoring after all).
If you have a larger change to do though, I would go about creating a new class from scratch (TDD of course), and later on, remove the no longer needed functionality from the old class, as well as the now redundant test cases.

A: The approach I'd take in this case is "play it innocent" -- when you discover a new requirement, just write a test and the implementation for it, pretending to ignore the relationship with previous requirements at first.
The "And" case here is clearly new functionality. No need to modify the contents of the existing test at that point, just create another test with a name that reflects the new requirement, such as CompositeAndRiskTest and create the corresponding implementation.
Then, during the Refactor step, "realize" that the two previous objects are 2 sides of the same coin and refactor them accordingly. That could just mean renaming CompositeRisk to CompositeOrRisk, or more complex things.
Once the 2 sorts of Risks are identified, tested and implemented, you could go on and create new tests for combinations of them.


text:
Q: C# Selenium, getting text of Invisible elements is slow I am trying to get invisible text that is on a given page using C# Selenium EdgeDriver. I am able to do it, i.e. I get the elements (such as within span, p or b tags, then I am filtering out the elements into a list based on Displayed property, and finally I am calling GetAttribute("textContent") to get the text. The problem I am having is that is slow, about 10 seconds for the page I am doing that on, do you think there is any better way, or making this faster?
Thanks,
       public static string GetInvisibleText()
        {
            Stopwatch s500 = new Stopwatch();
            s500.Start();

            string returnable = "\r\n";
            var elements = driver.FindElements(By.XPath("//b | //span | //p | //a | //h1 | //h2 | //h3 | //h4 | //h5 | //h6 | //div"));
            List<string> list = new List<string>();
            var displayed_elements = elements.Where(e => !e.Displayed);

            foreach(var el in displayed_elements)
            {
                try
                {
                    string val = el.GetAttribute("textContent");
                    val = val.Trim();
                    val = Regex.Replace(val, @"\s+", " ");
                    list.Add(val);
                }
                catch (Exception ex)
                {

                }
            }

            list = list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();

            foreach (string line in list)
            {
                returnable = returnable + line + "\r\n";
            }

            s500.Stop();
            return returnable;
        }


text:
Q: How to validate and show errors in a PHP input without pressing SUBMIT button? I have a user registration form in php and mysql as follows.
I need to validate each input field before the user moves to the next field AND without submitting a button. The user must submit the form once all the fields are filled properly or it should prompt the error at the filling field?
How can i do that.
For an example:- i need to validate the NIC Number once it is filled and should show if there is any error in the formatting once moved to the Name field and before submitting the form.
<form action='register.php' method='post'>
NIC Number : <select class='drdwn1' name='idtype'>
<option value="old">Old</option>
<option value="new">New</option>
</select>
<input type='text' name='nic'/>

Name with Initials : <select class='drdwn1' name='saluation'>
<option value="Mr.">Mr.</option>
<option value="Ms.">Ms.</option>
</select>

<input type='text' name='name' />
Address : <input type='text' name='address' />
Occupation : <input type='text' name='occupation' />
Contact Number : <input type='text' name='contactno'/>
Email Address : <input type='text' name='email' placeholder=''/>
Password : <input type='password' name='password' >

Confirm Password : <input type='password' name='password1' />
<input type='submit' name='submit' value='Submit' >
</form>

<?

php

if (isset($_POST['submit'])){

$Idtype=$_POST['idtype'];
$Nic=$_POST['nic'];
$Saluation=$_POST['saluation'];
$Name=$_POST['name'];
$Address=$_POST['address'];
$Occupation=$_POST['occupation'];
$Contactno=$_POST['contactno'];
$Email=$_POST['email'];
$Username=$_POST['nic'];
$Password=$_POST['password'];
$Password1=$_POST['password1'];
$email = filter_var($Email, FILTER_SANITIZE_EMAIL);

$check=mysqli_query($conn,"select * from user.admin WHERE username='$Username'");
$checkrows=mysqli_num_rows($check);

    // Check if User exist
    if($checkrows>0) {
    echo "
Your username already exist!
";
    }
    // Check if User exist

    // Check Manditory fields
    else if(empty($_POST['nic'] AND $_POST['email'] AND $_POST['password'])){
    echo "
Please fill the mandetory fields!
";
    }
    // Check Manditory fields

    // Validate Email
    else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo("
$email is not a valid email address!
");
    }
    // Validate Email

    //if old ID and and not filled V
    else if (strlen($Nic) == '10' AND !preg_match("/^[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[0-9]+[V,X]$/i", $Nic)){
    echo "
Should have the letter V or X at the end!
";
    }
    //Validate ID Number

    // Validate Password
    else if(($_POST['password'] !== $_POST['password1'])){
    echo "
Password must mach!
";
    }
    // Validate Password

else{

$sql = "INSERT INTO user.admin (nic, saluation, name, address, city, bday, occupation, contactno, email, username, password) VALUES ('$Nic','$Saluation','$Name','$Address','$Occupation','$Contactno','$Email','$Username','$Password')";
if ($conn->query($sql) === TRUE) {

Echo "Success!";
}
}
}

?>

A: Use Javascript! Is powerful and works fine with this problems.
Suppose you have a function
function validateNIC(param){...}
You could use this as follows:
<input type='text' name='nic' onblur="validateNIC(this.value)"/>

where I used "onblur" event, but you can customize it on your needs.
Naturally, this is only a syntactic control. If you wanted to perform actions such as database queries or in general a server-side control, this is not the thing to do: you should use, for example, Ajax technology, for an asynchronous communication with the server without submit the form data.

A: You could do this with Javascript with a keyup event.
$('input').keyup(function() {
//code...
});

you could put all of the requirements you want to set said input in there.

A: First, form validation is a topic covered in many tutorials and documentations on the Internet and there is no point in me just reinventing the wheel. Interestingly enough, I could not find an exact duplicate question on Stack Overflow, so I'll give you a rough outline, based (or backed up) by this fantastic article on form validation from the MDN - go read it, it will teach you everything.
Now, there are three possible ways of validating a form:

*

*Browser's built-in validation (client-side)

*Custom JavaScript (client-side)

*PHP (or another server-side language)

It is important to understand that all client-side validations can easily be disabled or circumvented by the user, which means that you absolutely have to do server-side validation. Client-side validation is only additional convenience.
If you want to perform client-side validation, the easiest way would be to make use of modern browser's built-in functionality. This can be achieved through attributes like required, maxlength or even pattern, which can be given to form input elements.
JavaScript (or jQuery) solutions can be used in addition if the built-in solutions do not suffice for your specific use case. There are plenty of options out there.

A: use onfocusout for client side validation example

A: We can use available client side validation plug ins like:
https://jqueryvalidation.org/files/demo/
Similarly we can use php server side validation like:
https://www.w3schools.com/php/php_form_validation.asp


text:
Q: Tomcat 7 Session replication issue on fail-over We recently clustered our application with 2 tomcat nodes(7.0.53) and the cluster was setup as per the Tomcat documentation https://tomcat.apache.org/tomcat-7.0-doc/cluster-howto.html
Everything works as expected except the session replication doesnt work on fail over, I had to setup hazelcast on both tomcat instances to make the session replication work. I refered to hazelcast documentation to setup http://docs.hazelcast.org/docs/3.5/manual/html/websessionreplication.html and session replication works perfectly on tomcat failure. I am just wondering is this a bug with Tomcat session replication? Or is it mandatory to use 3rd party libraries like hazelcast to achieve session replication on tomcat failure?


text:
Q: 'The string argument 'migrationId' cannot be empty.' Blocked on a weird error. I am working in an asp.net core web application, and using EF core 1.1.0 in it.
EF database migration is throwing error 'The string argument 'migrationId' cannot be empty.' when trying to execute below command
dbcontext.Database.Migrate();

Performed accepted answer from the the link but it did not solved my issue.
Uninstall donet 2.0.0, installed 1.1.0 and restarted PC. Still i am getting the same error.

Can anyone please help me on this.

A: When you have MigrationID column with in __EFMigrationsHistory table is empty you will have above issue. Make sure you delete this record manually and rerun the command. Please find screen shot for the same.

A: I had solved my issue.
Just deleted development database and executed migration on start.
It working now perfectly.


text:
Q: how to enable TLS and https requests for a website using node.js and express.js? I'm doing one of my first projects of web programming using node.js (using express.js) as back and react as front. Some requests to my node server need to be secure like post requests for sending login and register data.
what should i do?
is there any library for node or react to help me?
and which parts of my project should i change?

A: I see two ways:

*

*Enable https at node express level. Use some tutorial like this
https://medium.com/@nileshsingh/everything-about-creating-an-https-server-using-node-js-2fc5c48a8d4e

*Or put node server behind nginx reverse proxy. This way actually is easier for beginner. Simple nginx configuration + certbot and it is done. Certbot is a tool that will provide you free certificates and integrate them into your nginx configuration - https://certbot.eff.org/