text:
Q: Duplicate Pandas dataframe rows by swapping two columns Given a pandas dataframe, each row in the dataframe should be duplicated, but the duplicate row differs from the original row in terms of the score1 and score2 columns whereby their values are swapped. Furthermore, the incremental nature of unique ID must be kept.
Original dataframe:
nme = ["Tom", "John", "Philip", "Ross"]
deg = ["MBA", "BCA", "M.Tech", "MBA"]
scr1 = [90, 40, 80, 98]
scr2 = [10, 20, 30, 50]

# dictionary of lists
dct = {'name': nme, 'degree': deg, 'score1': scr1, 'score2': scr2}
my_dataframe = pd.DataFrame(dct)
print(my_dataframe)

     name  degree  score1  score2
0     Tom     MBA      90      10
1    John     BCA      40      20
2  Philip  M.Tech      80      30
3    Ross     MBA      98      50

Expected dataframe:
nme = ["Tom","Tom", "John", "John", "Philip","Philip", "Ross", "Ross"]
deg = ["MBA", "MBA", "BCA", "BCA", "M.Tech", "M.Tech", "MBA", "MBA"]
scr1 = [90, 10, 40, 20, 80, 30, 98, 50]
scr2 = [10, 90, 20, 40, 30, 80, 50, 98]

# dictionary of lists
dct = {'name': nme, 'degree': deg, 'score1': scr1, 'score2': scr2}
my_new_dataframe = pd.DataFrame(dct)
print(my_new_dataframe)

     name  degree  score1  score2
0     Tom     MBA      90      10
1     Tom     MBA      10      90
2    John     BCA      40      20
3    John     BCA      20      40
4  Philip  M.Tech      80      30
5  Philip  M.Tech      30      80
6    Ross     MBA      98      50
7    Ross     MBA      50      98

Thank you very much in advance.

A: This one works for me:
new_df = pd.DataFrame(columns=['name', 'degree', 'score1', 'score2'])
j=0
for index, row in df.iterrows():
    new_df.loc[j] = [row[0], row[1], row[2], row[3]]
    new_df.loc[j+1] = [row[0], row[1], row[3], row[2]]
    j+=2
new_df

The Output:
name     degree score1  score2
0   Tom     MBA     90  10
1   Tom     MBA     10  90
2   John    BCA     40  20
3   John    BCA     20  40
4   Philip  M.Tech  80  30
5   Philip  M.Tech  30  80
6   Ross    MBA     98  50
7   Ross    MBA     50  98

A: You can use itertools.permutations and df.explode to get your desired output.
from itertools import permutations

my_dataframe['combine'] = [list(permutations((i,j),2)) for i,j in zip(my_dataframe.score1,my_dataframe.score2)]

     name  degree  score1  score2               combine
0     Tom     MBA      90      10  [(90, 10), (10, 90)]
1    John     BCA      40      20  [(40, 20), (20, 40)]
2  Philip  M.Tech      80      30  [(80, 30), (30, 80)]
3    Ross     MBA      98      50  [(98, 50), (50, 98)]

my_new_dataframe = my_dataframe.explode('combine')

     name  degree  score1  score2   combine
0     Tom     MBA      90      10  (90, 10)
0     Tom     MBA      90      10  (10, 90)
1    John     BCA      40      20  (40, 20)
1    John     BCA      40      20  (20, 40)
2  Philip  M.Tech      80      30  (80, 30)
2  Philip  M.Tech      80      30  (30, 80)
3    Ross     MBA      98      50  (98, 50)
3    Ross     MBA      98      50  (50, 98)

my_new_dataframe[['score1','score2']] = pd.DataFrame(my_new_dataframe['combine'].tolist(), index= my_new_dataframe.index)

     name  degree  score1  score2   combine
0     Tom     MBA      90      10  (90, 10)
0     Tom     MBA      10      90  (10, 90)
1    John     BCA      40      20  (40, 20)
1    John     BCA      20      40  (20, 40)
2  Philip  M.Tech      80      30  (80, 30)
2  Philip  M.Tech      30      80  (30, 80)
3    Ross     MBA      98      50  (98, 50)
3    Ross     MBA      50      98  (50, 98)

Update
To obtain unique index for every row, you can use df.reset_index
my_new_dataframe.reset_index(drop=True, inplace=True)

     name  degree  score1  score2   combine
0     Tom     MBA      90      10  (90, 10)
1     Tom     MBA      90      10  (10, 90)
2    John     BCA      10      90  (40, 20)
3    John     BCA      10      90  (20, 40)
4  Philip  M.Tech      40      20  (80, 30)
5  Philip  M.Tech      40      20  (30, 80)
6    Ross     MBA      20      40  (98, 50)
7    Ross     MBA      20      40  (50, 98)

A: Just realised it's been 4 days, but I've thought of a simple solution to swap the 2 scores columns first, before concat with the original dataframe, for example:
print(my_dataframe)
     name  degree  score1  score2
0     Tom     MBA      90      10
1    John     BCA      40      20
2  Philip  M.Tech      80      30
3    Ross     MBA      98      50

my_dataframe2 = my_dataframe.copy()
my_dataframe2.columns = ['name', 'degree', 'score2', 'score1']

print(my_dataframe2)
     name  degree  score2  score1    #note 2 column names are swapped
0     Tom     MBA      90      10
1    John     BCA      40      20
2  Philip  M.Tech      80      30
3    Ross     MBA      98      50

Next use pd.concat(), which will stack vertically based on column names:
df = pd.concat([my_dataframe, my_dataframe2]).sort_index().reset_index(drop=True)
print(df)

   degree    name  score1  score2
0     MBA     Tom      90      10
1     MBA     Tom      10      90
2     BCA    John      40      20
3     BCA    John      20      40
4  M.Tech  Philip      80      30
5  M.Tech  Philip      30      80
6     MBA    Ross      98      50
7     MBA    Ross      50      98


text:
Q: Text filter and Dropdown filter on the same field in Angular table I am pretty new to Angular and struggling at the moment to do a simple thing. Not sure how to go about it.
I have a table which I have created using ng-repeat.
Now on each of the columns I have filters which are controlled by my ng-model.
For example, let's say I have an Employees table with these columns:
EmpId, EmpName, Unit, Active (Y/N)

Each of these have filters in the <th> tags where I can easily filter by
Id, Name, Active:Y/N
Now the problem is I need to show a drop down outside of this table which says Active/InActive and by default it should always show Active Employees
So I am not sure how can I specify two filters on the same column to achieve this.
Please help me out.

A: Refer this link
//FILTER
  .filter('findobj', function () {
 return function (dataobj, multipleVlaue) {
     if (!multipleVlaue) return dataobj;
     return dataobj.filter(function (news) {
         var tofilter = [];

         angular.forEach(multipleVlaue,function(v,i){
          tofilter.push(v);
         });

         return news.CategoryList.some(function (category) {
        return tofilter.indexOf(category.DisplayName)>-1;
     });

     });
 };
 })

I hope this will help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error while attempting to install Python 3.8.2 on Windows 7 I am using Windows 7 64 bit and when I attempt to run the executable installer for Python 3.8.2 I get an error stating that I need to install windows service pack 1 to continue. I already have windows service pack 1 installed on this drive, I've double checked and reinstalled it but this has not fixed the issue.
This is what's in the error log:

[1B0C:1AAC][2020-04-10T05:16:05]i001: Burn v3.11.1.2318, Windows v6.1
  (Build 7601: Service Pack 1), path:
  C:\Users\Admin\AppData\Local\Temp{4C6C4ED2-212B-4FA8-BD34-C5891FEA4006}.cr\python-3.8.2-amd64.exe
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'ActionLikeInstalling' to value 'Installing'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'ActionLikeInstallation' to value 'Setup'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'ShortVersion' to value '3.8'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'ShortVersionNoDot' to value '38'
  [1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'WinVer' to value '3.8'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'WinVerNoDot' to value '38'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'InstallAllUsers' to value '0'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'InstallLauncherAllUsers' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'TargetDir' to value ''
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'DefaultAllUsersTargetDir' to value
  '[ProgramFiles64Folder]Python[WinVerNoDot]'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'TargetPlatform' to value 'x64'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'DefaultJustForMeTargetDir' to  value
  '[LocalAppDataFolder]Programs\Python\Python[WinVerNoDot]'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'OptionalFeaturesRegistryKey' to value
  'Software\Python\PythonCore[WinVer]\InstalledFeatures'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'TargetDirRegistryKey' to value
  'Software\Python\PythonCore[WinVer]\InstallPath'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'DefaultCustomTargetDir' to value ''
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'InstallAllUsersState' to value 'enabled'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'InstallLauncherAllUsersState' to value 'enabled'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'CustomInstallLauncherAllUsersState' to value
  '[InstallLauncherAllUsersState]'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'TargetDirState' to value 'enabled'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'CustomBrowseButtonState' to value 'enabled'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_core' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_exe' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_dev' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_lib' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_test' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_doc' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_tools' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_tcltk' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_pip' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_launcher' to value '-1 '
  [1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'Include_launcherState' to value 'enabled'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_symbols' to value '0'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Include_debug' to value '0'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'LauncherOnly' to value '0'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'DetectedLauncher' to value '0'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'DetectedOldLauncher' to value '0'
  [1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'AssociateFiles' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'Shortcuts' to value '1'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'PrependPath' to value '0'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'CompileAll' to value '0'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing numeric variable
  'SimpleInstall' to value '0'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Initializing string variable
  'SimpleInstallDescription' to value ''
  [1B0C:1AAC][2020-04-10T05:16:05]i009: Command Line:
  '-burn.clean.room=C:\Users\Admin\Downloads\python-3.8.2-amd64.exe
  -burn.filehandle.attached=180 -burn.filehandle.self=188'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Setting string variable
  'WixBundleOriginalSource' to value
  'C:\Users\Admin\Downloads\python-3.8.2-amd64.exe'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Setting string variable
  'WixBundleOriginalSourceFolder' to value 'C:\Users\Admin\Downloads\'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Setting string variable
  'WixBundleLog' to value 'C:\Users\Admin\AppData\Local\Temp\Python
  3.8.2 (64-bit)_20200410051605.log'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Setting string variable
  'WixBundleName' to value 'Python 3.8.2 (64-bit)'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Setting string variable
  'WixBundleManufacturer' to value 'Python Software Foundation'
[1B0C:1AAC][2020-04-10T05:16:05]i000: Setting numeric variable
  'CRTInstalled' to value 1
[1B0C:1D88][2020-04-10T05:16:05]i000: Did not find
  C:\Users\Admin\Downloads\unattend.xml
[1B0C:1D88][2020-04-10T05:16:05]i000: Setting string variable
  'ActionLikeInstalling' to value  'Installing'
[1B0C:1D88][2020-04-10T05:16:05]i000: Setting string variable
  'ActionLikeInstallation' to value 'Setup'
[1B0C:1D88][2020-04-10T05:16:05]i000: Setting version variable
  'WixBundleFileVersion' to value '3.8.2150.0'
[1B0C:1D88][2020-04-10T05:16:05]e000: Detected Windows 7 SP1 without
  KB2533623
[1B0C:1D88][2020-04-10T05:16:05]e000: KB2533623 update is required to
  continue.

A: I have observed that versions above 3.7.2 require more that just the SP1 update. Looking at your log files, you will find that it requires you to install the update KB2533623. Unless you fulfill the all the prerequisites for the installation, you wouldn't be able to continue with it. Install the appropriate updates as referred to by the setup/log-file and try again.
It is probable that the Service Pack 1 update might have not installed properly into the system. You would need to retry installing the updates. I am afraid to tell you that official free support and updates to Windows 7 have been discontinued since the onset of 2020, so you might have a hard time finding the correct update.
Sometimes, the update unexpectedly fails to install properly. If nothings else works, the service pack version may be fixed through the registry, but at one's own risk as it might lead to consequences.
Handling the registry is dangerous, so proceed at your own risk.

*

*Open the registry editor.

*Navigate to HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Control/Windows.

*Modify the hexadecimal value of CSDVersion to 100 for SP1, 200 for SP2, and 300 to SP3.

*Restart the PC.


text:
Q: How do I get around the happybase "TApplicationException: Internal error processing mutateRows" error? I'm using happybase to connect to my Hbase database. I made a sample table called 'irisSample'. Here's the part of the code that I'm having trouble with-
import happybase
from happybase import *
import json

connection = happybase.Connection('<ip-address>', '9090')

table = connection.table('irisSample')

n = 0
x = 1
for u in y:
    data = {'petalWidth':points['petalWidth'][n], 'sepalLength':points['sepalLength'][n],
          'petalLength':points['petalLength'][n], 'label': u}
    row = 'row' + str(x)
    table.put(row, {'flowers': str(data)})
    n += 1
    x += 1

And I get the following.
TApplicationException                     Traceback (most recent call last)
<ipython-input-15-94741a8b04dc> in <module>()
      9           'petalLength':points['petalLength'][n], 'label': u}
     10     row = 'row' + str(x)
---> 11     table.put(row, {'flowers': str(data)})
     12     n += 1
     13     x += 1

/root/anaconda/lib/python2.7/site-packages/happybase/table.pyc in put(self, row, data, timestamp, wal)
    437         """
    438         with self.batch(timestamp=timestamp, wal=wal) as batch:
--> 439             batch.put(row, data)
    440
    441     def delete(self, row, columns=None, timestamp=None, wal=True):

/root/anaconda/lib/python2.7/site-packages/happybase/batch.pyc in __exit__(self, exc_type, exc_value, traceback)
    130             return
    131
--> 132         self.send()

/root/anaconda/lib/python2.7/site-packages/happybase/batch.pyc in send(self)
     53                      self._table.name, self._mutation_count, len(bms))
     54         if self._timestamp is None:
---> 55             self._table.connection.client.mutateRows(self._table.name, bms, {})
     56         else:
     57             self._table.connection.client.mutateRowsTs(

/root/anaconda/lib/python2.7/site-packages/happybase/hbase/Hbase.pyc in mutateRows(self, tableName, rowBatches, attributes)
   1574     """
   1575     self.send_mutateRows(tableName, rowBatches, attributes)
-> 1576     self.recv_mutateRows()
   1577
   1578   def send_mutateRows(self, tableName, rowBatches, attributes):

/root/anaconda/lib/python2.7/site-packages/happybase/hbase/Hbase.pyc in recv_mutateRows(self)
   1592       x.read(self._iprot)
   1593       self._iprot.readMessageEnd()
-> 1594       raise x
   1595     result = mutateRows_result()
   1596     result.read(self._iprot)

TApplicationException: Internal error processing mutateRows

I've also tried json.dumps(data) instead of str(data) which threw the same exception.
From what I'm gathering it seems more like a Thrift problem but I could be wrong. I may have to look at starbase instead. I don't know, that's why I'm asking you guys.

A: It looks like in your "data" object you are not giving column family along with the column name.
data = {'petalWidth':points['petalWidth'[n], 'sepalLength':points['sepalLength'][n], 'petalLength':points['petalLength'][n], 'label': u}

You need to have column family before each of the column values. E.g., say your column family is "cf" then instead of 'petalWidth' you want 'cf:petalWidth'.
data = {'cf:petalWidth':points['petalWidth'[n], 'cf:sepalLength':points['sepalLength'][n], 'cf:petalLength':points['petalLength'][n], 'cf:label': u}

Doing this fixed the mutateRows error for me.

A: I found the answer here. It required a REST framework to be running on an unused port. I then connected to that port and was able to see the list of all the tables in Hbase and insert data into the database. The command is ./hbase-daemon.sh start rest -p <unused port number>. I couldn't find the answer anywhere and no one even commented for a few days so I hope this helps you! Here's the code. I ended up using starbase.
import starbase
from starbase import Connection

c = Connection(host='<ip-address>', port=8000)

8000 is the default port by the way.
t = c.table('irisSample')

for flower in range(len(labels)):
    data = {'petalWidth':X[flower][3], 'petalLength':X[flower][2],
              'sepalLength':X[flower][0], 'sepalWidth':X[flower][1], 'cluster': labels[flower]}
    n += 1
    row = 'row' + str(n)
    t.insert(row, {'flowers': data})


text:
Q: unable to access mysql db using python (both running on different containers) I am trying to connect to mysql db using a python program. When run locally it works.
But while dockerizing the application I created, one container is for the python code and the other for the mysql db, when ran i this manner it fails to connect.
Python_code:
db.bind(provider='mysql', user='docker_root', password='password', host='db', database=database, port = 3306)

docker-compose:
version: "3"
  services:
    app:
      image: app:latest
      links:
        - db
      ports:
        - "8001:8081"
      environment:
        - DB_HOST= db

    db:
      image: mysql:5.7.26
      restart: always
      environment:
        MYSQL_DATABASE: 'my_db'
        MYSQL_USER: 'docker_root'
        MYSQL_PASSWORD: 'password'
        MYSQL_ROOT_PASSWORD: 'password'
      ports:
        - "3306:3306"
      volumes:
        - ./DB_config/:/etc/mysql/mysql.conf.d

And the docker-compose up fails with the eroor:

pony.orm.dbapiprovider.OperationalError: (2003, "Can't connect to
  MySQL server on 'db' ([Errno 111] Connection refused)")

Where am I going wrong? Please advise!

A: Try using container port 3306 -
db.bind(provider='mysql', user='docker_root', password='password', host='db', database=database, port = 3306)

Also, add depends_on attribute, you can remove the links attribute -
 depends_on:
    - db

A: YOu can use depends_on flag as mentioned in accepted answer. If it does not solve your problem them use this approach.
After starting the container, your server will try to connect to the database server. sometimes database server may take some time to boot up and in this window, if the server tries to connect to database server it will face problems.
Try adding logic to reconnect database server after few seconds if the connection fails.
try{
   connectToDatabase();
   }catch(error){
   waitForHalfMinute();
   connectToDatabase();
}

A: I would recommend you to exit your application in case it cannot connect to MySQL and set the restart policy to always, because depends_on does not guarantee that MySQL will be totally up when app starts but it is good to have it there.
version: "3"
  services:
    app:
      image: app:latest
      restart: always
      links:
        - db
      ports:
        - "8001:8081"
      environment:
        - DB_HOST= db
      depends_on:
        - db

    db:
      image: mysql:5.7.26
      restart: always
      environment:
        MYSQL_DATABASE: 'my_db'
        MYSQL_USER: 'docker_root'
        MYSQL_PASSWORD: 'password'
        MYSQL_ROOT_PASSWORD: 'password'
      ports:
        - "3306:3306"
      volumes:
        - ./DB_config/:/etc/mysql/mysql.conf.d

And your application code should be something like:
try:
    db.bind(provider='mysql', user='docker_root', password='password', host='db', database=database, port = 3306)
except:
    # write some logs
    exit(1)


text:
Q: Execute php when a button is clicked I have a contact form which is linked to contact.php. I've added a small captcha widget to the form. I know spam bots can still get this but it's just for learning purposes.
Anyways, I created 2 random numbers and user must type the corresponding answer in the textarea near it. The problem is that I cannot get PHP to run when submit is clicked to check if captcha is correct or not.
Sorry if the code is a little messed up but its only a simple form containing name, email and the message + a button.
P.S: $total is used only as it stopped chrome from displaying the confirm form resubmission message from being displayed when attempting to refresh.
Update:
First of all thanks for all the corrections, I am new to here.
Secondly it is only half-solved. This is because the captcha verification alert message is only being shown when I remove contact.php from <form action="contact.php" method="post" name="contact_form">. Apart from all this, since I am fairly new to web programming, is there any other programming language (best to use in this context) I can use so that I can create the captcha, check it and place a note like Your captcha is incorrect on top of the textbox(if captcha is incorrect) and prevent users from submitting form until the value is correct?
<?php
// init session to store captcha numbers
session_start()
?>

<form action="contact.php" method="post" name="contact_form">

Contact Us For a Quote

                        <input name="name"     type="text" class="text" value="Name" onfocus="this.value = '';" onblur="if     (this.value == '') {this.value = 'Name';}">

                        <input name="email" type="text" class="text" value="Email" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}">

                        <textarea name="message" value="Your Message/request" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Your Message/request';}">Your Message/request</textarea>

                <?php
                $min = 1;
                $max = 7;
                $num1 = rand ($min, $max);
                do{
                    $num2 = rand ($min, $max);
                }while($num1 == $num2);
                // store captcha numbers to check them on submit
                $_SESSION['num1'] = $num1;
                $_SESSION['num2'] = $num2;
                echo $num1 . " + " . $num2 . " =";
                $total = $num1 + $num2;
                ?>
                <input name="ver" type="text" value="" onfocus="this.value = '';" size="2" maxlength="2">

        <input type="submit" name="submit" onclick="myFunction()" value="Submit Request">
        <?php
        // your form pass data through post, not get
        if(isset($_POST['submit'])){
            //submit clicked
            $verification = $_POST['ver'];
            // check numbers on submit
            if($_SESSION['num1'] + $_SESSION['num2'] != $verification)
            {
                echo'';
            }
        }
        ?>

Printscreen: http://i.stack.imgur.com/u0Ca9.png
contact.php contents
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = "name@example.com";
$subject = "New Form Submission";
$finmsg = "A visitor has submitted a new request.\n\nName: $name\nEmail: $email\nMessage: $message";
mail ($to, $subject, $finmsg);
?>

A: The problem is that $num1 and $num2 variables are not defined then your check captcha, because variable states are not saved between different requests.
You should use smth like sessions to preserve variable values. See comments in snippet below:
<?php
  // init session to store captcha numbers
  session_start()
?>

<form action="contact.php" method="post" name="contact_form">

Contact Us For a Quote

                            <input name="name" type="text" class="text" value="Name" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}">

                            <input name="email" type="text" class="text" value="Email" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}">

                            <textarea name="message" value="Your Message/request" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Your Message/request';}">Your Message/request</textarea>

                    <?php
                    $min = 1;
                    $max = 7;
                    $num1 = rand ($min, $max);
                    do{
                        $num2 = rand ($min, $max);
                    }while($num1 == $num2);
                    // store captcha numbers to check them on submit
                    $_SESSION['num1'] = $num1;
                    $_SESSION['num2'] = $num2;
                    echo $num1 . " + " . $num2 . " =";
                    $total = $num1 + $num2;
                    ?>
                    <input name="ver" type="text" value="" onfocus="this.value = '';" size="2" maxlength="2">

            <input type="submit" name="submit" onclick="myFunction()" value="Submit Request">
            <?php
            // your form pass data through post, not get
            if(isset($_POST['submit'])){
                //submit clicked
                $verification = $_POST['ver'];
                // check numbers on submit
                if($_SESSION['num1'] + $_SESSION['num2'] != $verification)
                {
                    echo'';
                }
            }
            ?>

A: try this
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">


text:
Q: How can convert svg(data:image/svg+xml) to .png or .jpg When onclick Save as Image button,
I want to save or download Chart to .png or .jpg

$scope.saveAsBinary = function () {
     var svg = document.getElementById('highchartContainer').children[0].innerHTML;
     var base_image = new Image();
     svg = "data:image/svg+xml," + svg;
     base_image.src = svg;
     $('#binaryImage').attr('src', svg);
}

Please check this fiddle


text:
Q: ImageButton click events get queued up until ListView is scrolled I have a custom ListView item that has an ImageButton in it, and when I click it, the click events don't come through until the list item as a whole is interacted with, such as scrolling the list or tapping somewhere else on the list item. So for instance, if I click the ImageButton 5 times, nothing will happen, but then when I scroll the list, all 5 click events will come through simultaneously.
After a lot of research, I've come to find this is a common question, but none of the solutions I've found have worked for me so far. This question was quite helpful in learning some of the quirks of view interaction, and most other solutions I found used a similar approach to the accepted answer on that question, but unfortunately none of them worked for my particular situation.
So what I need to happen is to handle the click events for the ImageButton on the list item, as well as the click event for the list item itself. I've tried setting android:focusable="false" and android:focusableInTouchMode="false" on pretty much every view element involved in the display of this list. I've also tried setting these attributes programmatically. I also tried setting android:descendantFocusability="blocksDescendants" on several view elements including the ListView, the LinearLayout of the row item, and the CardView that contains all of this stuff.
The confusing part about all of this, is that I have this working just fine in another Activity of the same app. I have an ImageButton in a custom row layout of a ListView, and the onClick events work just fine for that. So it has to be something with my setup on this Activity. Here's some code:
The getView() of my custom BaseAdapter:
public View getView(int position, View convertView, ViewGroup parent) {
    FavoritesItemViewHolder favoriteItem = favoritesList.get(position);
    if(convertView == null) {
        convertView = favoriteItem.getNewConvertView(parent);
    } else {
        if(favoriteItem.getConvertView() == null) {
            convertView = favoriteItem.getNewConvertView(parent);
        } else {
            convertView = favoriteItem.getConvertView();
        }
    }

    return convertView;
}

The view inflation of my individual view holders:
public View getNewConvertView(ViewGroup parent) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    convertView = inflater.inflate(R.layout.favorites_list_item, parent, false);

    TextView favoriteText = (TextView) convertView.findViewById(R.id.favoritesItemText);
    favoriteText.setText(itemTitle);

    //Here is where I'm setting the OnClickListeners for each row...
    ImageButton clearButton = (ImageButton) convertView.findViewById(R.id.favoritesClearButton);
    clearButton.setVisibility(View.VISIBLE);
    if(itemTitle.equals(context.getResources().getString(R.string.no_favorites))) {
        clearButton.setVisibility(View.INVISIBLE);
    } else {
        clearButton.setVisibility(View.VISIBLE);
        clearButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("CLEAR FAVORITE", "The clear button was just clicked on a favorites item...");
            }
        });
    }

    return convertView;
}

And here is the XML for my custom row layouts...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/favoritesListItemContainer"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/favoritesItemText"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:layout_gravity="center_vertical"
        android:textSize="16sp"
        android:textColor="@android:color/black"
        android:layout_weight="0.9"/>

    <ImageButton
        android:id="@+id/favoritesClearButton"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_clear_x"
        android:layout_gravity="center_vertical"
        android:scaleType="centerInside"
        android:adjustViewBounds="true"
        android:background="@android:color/white"
        style="?android:attr/borderlessButtonStyle"
        android:layout_weight="0.1" />
</LinearLayout>

Any help would be appreciated. I'm just completely stumped here.
UPDATES

In this Activity, I'm using getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE, WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE); in order to disable a SearchView and some other UI, and when the SearchView receives focus, suddenly my ListView items work as intended. So I'm guessing this has an issue with the ListView or the Window it's in having no focus, and so the click events don't come through until something on the screen receives focus.
What's strange is, when the keyboard is showing on the screen, I can click the list items and their ImageButtons and all the click events are handled correctly. But when I dismiss the keyboard, it breaks again.

A: There are known problems with ListView interfering with the touch events of views inside each item.  You should switch to RecyclerView instead.  ListView is seen as essentially deprecated for new apps with RecyclerView becoming its replacement.


text:
Q: Accessing google maps in vue js Here is the link i used to display google maps :
https://jsfiddle.net/oscar11/1krtvcfj/2/
While trying to access maps by trying this code, it shows the following error:

Error in mounted hook: "ReferenceError: google is not defined"

As somebody suggested in another link I even initialised the 4 parameters like
geocoder: null,
map: null,
marker: null,
infowindow: null

I need to access google maps using this code. please somebody help out.

A: You have many things wrong here:

*

*Reference to variables should be maintained in the data component.

*Function callbacks need to use the fat arrow function, or .bind(this) (among other options) in order to maintain scope. This would change function () { to () => {. Otherwise, the scope of this within these anonymous callbacks would not be the Vue instance.

*The map its self needs to be part of the Vue template.

*The address input should use the v-model binding that Vue provides in order to keep it's data in sync with the component

*The geocoder service will not work without an API key.

*The base div in your component also needs a fixed height, or at least a height of 100% for the map to appear correctly.

*While you can use document.getElementById(), I would suggest using a ref to maintain reference to the element, by adding ref="map_canvas" to the element and then using this.$refs.map_canvas instead.

It seems as if you've just copied and pasted some code into the Vue component and hoped it worked. It won't. I've cleaned this up for you, but I would recommend paying close attention to the differences so you can get an understanding as to how these integrate together.
Here's your updated jsFiddle


text:
Q: Ubuntu Server 20 does not boot when exfat external drive is connected Bought an 8TB WD My Book external drive to replace an existing hard drive. The drive is formatted as exfat as per the output of "sudo blkid | grep UUID=".
I am able to mount/unmount the drive without any issues and am able to access the contents of the drive.
My issue is that when I reboot the server, it does boot up with the drive connected (via usb). If I remove the drive and reboot, the server boots up. Connecting the external drive after boot up does not cause any issues.
Do I need to configure anything in order get my server boot up with the external drive connected?
Thanks.

A: You need to change the boot order of your drives in your BIOS/UEFI. Since the WD does not have a an OS your server won't start if it "thinks" it is the system drive.


text:
Q: Tracking time spent at a location in Android using Google apis I need to track the time spent by the app user at a particular location. Please suggest me an optimized approach. I looked into this link.
I can use the above for getting the location, but what should my approach to achieve what I want ?

A: The main idea is to fetch current user location at defined interval and if location goes beyond your region, we can calculate time difference
Follow this steps
 long time1 = new Date().getTime();
 long time2;

 double firstLat, firstLog;
 // fetch current user location using this link
 // https://developer.android.com/training/location/retrieve-current.html

 //Declare the timer
 Timer timer = new Timer();
 //Set the schedule function and rate
 timer.scheduleAtFixedRate(new TimerTask() {

      @Override
      public void run() {
         // Called each time when 1000 milliseconds (1 second) (the period parameter)

         double curLat, curLog;

         // fetch current user location using this link
         // https://developer.android.com/training/location/retrieve-current.html

         if(!isUserInRegion(firstLat,firstLog,curLat,curLog){
             time2 = new Date().getTime();
             timer.cancel();
             timer.purge();
      }

 },
 //Set how long before to start calling the TimerTask (in milliseconds)
 0,
 //Set the amount of time between each execution (in milliseconds)
 1000);
 long timeDiff = time2 - time1;

 private boolean isUserInRegion(double firstLat, double firstLog, double curLat, double curLog){
      int r = 0.005; // Any radious
      double dx = curLat - firstLat;
      double dy = curLog - firstLog;
      return dx * dx + dy * dy <= r * r;
 }

Hope so this trick works for you :)


text:
Q: Load CSV dataset into R directly from Kaggle I need to load a CSV dataset directly to R from Kaggle without pre-downloading the CSV file. I found the solution how to unzip a csv file using GET() function from httr package, but for that I need the URL of the download. On Kaggle I can see only the Download button link '.../download', without the exact address to the zipped csv file. Is there any way to get the link to the zipped csv file on Kaggle?
I also found the kaggler package, but it seems working only for my own datasets that are under my account. While I would like to load into R datasets uploaded by other Kaggle users. Is there any way to do it in R?
Here is an example of Kaggle dataset. I would need to load the Placement_Data_Full_Class.csv directly into R.


text:
Q: How can I get more keyboard software instruments for GarageBand? I've been using GarageBand to play my MIDI keyboard for a few years, just because of its built-in software instruments for keyboards. Now I'm thinking about purchasing some jam packs only for the extra keyboard software instruments.
Which ones should I buy? Are there any more places or third-party software where I can get more keyboard instruments? I really want to have a huge selection of keyboard sounds, but don't know where or how to get them.

A: There are many third-party virtual keyboard instruments. Do a search at the kvraudio.com virtual instrument news site. Anything that is in Audio Unit (AU) format will work with GarageBand. Here is a search result I have prepared for you.
Popular products you might consider:
Anything by Native Instruments
Pianoteq
Buying Apple Logic Express or Logic Studio will give you all the Apple Jam Pack sounds in one purchase, with many other features besides. Apple Logic Express and Logic Studio.
Finally, read Keyboard Magazine. They provide a lot of coverage and reviews of products in this category.

A: Best buy is simply Apple MainStage3, for 30 USD you get 60GB of content that works in GarageBand.
https://www.youtube.com/watch?v=IEJvJBLtMeY
Apply symlink trick to get them all:
https://apple.stackexchange.com/a/280434/203343


text:
Q: Memory issue using DAX query in python script I am having memory issue when I execute DAX query inside the code in ref picture. If its like 10000 row it works however more than that it create memory issue. My query may return up to 50 Millions of data.
Question 1: What should be the efficient way to execute the query.
Question 2: What settings or properties might change to adjust huge amount of data.
Question 3: Is that possible to use partition and split data to fill into data table?
I am new in python coding. Please suggest me if code needs to change or any other efficient way to pull the data and send to data frame? my end goal is to send all data to CSV format into data lake. Its currently working however, for smaller amount of rows. I have tested till 10k is working in few min. its super inefficient seems to me.
Thanks in Advance!

A: I'm not sure how I would automate it, but the Export Data function from DAX Studio works really fast. I just did 500k rows in under a minute. It works against tables in the model, so if you are working with a DAX Expression, you would have to create it as a DAX Table in the model first.


text:
Q: "not stripped" but "no debug symbols" Can you explain the different results:
$ file libc-2.8.so
libc-2.8.so: ELF 32-bit MSB shared object, PowerPC or cisco 4500, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.6.10, with unknown capability 0x41000000 = 0x13676e75, with unknown capability 0x10000 = 0xb0401, not stripped

Notice the "not stripped" at the end.
and
(gdb) file libc-2.8.so
Reading symbols from /opt/Cross_Tools/powerpc-linux-gnu/powerpc-linux-gnu/libc/lib/libc-2.8.so...(no debugging symbols found)...done.

Notice the "(no debugging symbols found)"

A: You typically have to compile in debug mode (-g is the GCC command-line option) to include the debug symbols, it's not as if they're always there until stripped out. The default is to build in non-debug mode, without the symbols.


text:
Q: img tags in javascript for autocomplete search I am designing an autocomplete search which will have text and images in the results (working fine). However my images are blurred due to the standard image cache. So I was wondering if it is possible to resize images in the javascript to make them look neat and small?
Below is my javascript where I am using the img tags.
Could anyone please assist me with this? Thanks.
.data('autocomplete')._renderItem = function(ul, item) {
   return $('
')
   .data('item.autocomplete', item)
   .append(""+"" + item.label+"")
   .appendTo(ul);

A: Just add a CSS properties for your image tag or change it through script like
image.style.width='50%';
image.style.height='auto';

by doing this you can maintain the resolution of image. so it can not lose its quality.

A: I hope this code will help you, here i used jquery UI with inline style
$.ui.autocomplete.prototype._renderItem = function(ul, item) {
return $("

")
.data("item.autocomplete", item)
.append(""+item.label+ "").appendTo( ul );
};}


text:
Q: Prove that ⊨ is not symmetric Another question from a beginner:
We want to prove that ⊨ is not symmetric by finidng concrete formulas φ and ψ for which we can show that φ ⊨ ψ and ψ ⊭ φ.
Thank you for your help!

A: We have that :

$p \land q \vDash p$

but :

$p \nvDash p \land q$.

Use truth-table to verify it.

A: If $\models$ means classical consequence counterexamples are easy to find. Let $R, S$ be one place relation symbols. We have $\exists x (Rx \wedge Sx) \models \exists x Rx \wedge \exists x Sx$, but not vice versa.
For the first claim let $\mathfrak{A} = \langle D, I\rangle$ be a first-order model and $\beta$ an assignment in $\mathfrak{A}$. $\mathfrak{A}, \beta \models \exists x (Rx \wedge Sx) \Rightarrow~ \text{There is some}~a \in D~\text{with}~ \mathfrak{A}, \beta \frac{a}{x} \models Rx ~\text{and}~\mathfrak{A}, \beta \frac{a}{x} \models Sx \Rightarrow~\text{There is some}~a \in D~\text{with}~\mathfrak{A}, \beta \frac{a}{x} \models Rx ~\text{and}~\text{there is some}~a \in D~\text{with}~\mathfrak{A}, \beta \frac{a}{x} \models Sx \Rightarrow \mathfrak{A}, \beta \models\exists x Rx \wedge \exists x Sx$. (Notation: $\beta \frac{a}{x}$ is that assignment that differs form $\beta$ at most in that it assigns $a$ to $x$)
The following model shows that $\exists x Rx \wedge \exists x Sx \not \models \exists x (Rx \wedge Sx)$: $\mathfrak{A} = \langle \mathbb{N}, I \rangle$, such that $I(R) = \lbrace n \in \mathbb{N}: n = m \cdot 2~ \text{for some}~ m \in \mathbb{N} \rbrace, I(S) = \mathbb{N} \setminus I(R)$. Since obviously $I(R), I(S)$ are non-empty we have (for some assignment $\beta$) $\mathfrak{A}, \beta \models \exists x Rx \wedge \exists x Sx$. But because $I(R) \cap I(S) = \emptyset$ we also have that $\mathfrak{A}, \beta \not \models \exists x (Rx \wedge Sx)$.


text:
Q: Curl with POST method gives "HTTP Status 405" while the submit form is a POST. Input doesn't get prefilled from paired URL parameter I searched around google for a similar problem but couldn't find any, or couldn't formulate my question precisely enough, so I come to you.

I'm trying to login to forclosure.com from my localhost using Curl.
If you go to forclosure.com/login, you'll find that the login form uses a POST method, whereas when I try to login with Curl, it gives me an HTTP Status 405 error.
I tried to use Curl with a GET request instead and it passes (while the form is a POST..).
But now comes another problem, the password input isn't recognized in the URL and the login doesn't pass.
For exemple, if you try those parameters :
https://www.foreclosure.com/login?key=testkey&password=testpass
You will see that the username "key" gets filled, but not the password "password".
Same thing seems to happen with the search bar above with the name "q"

Thank you in advance. If the solution seems obvious to you, bear in mind that I'm still learning and would like to be pointed towards the right path.

A: Thanks to CBroe, I decided to try and use CURLOPT_URL with /login.html instead of just /login.. and not surprisingly, it works.
But I had to use GET parameters with CURLOPT_POST on true.
Here's the code for the interested:
//-----------------------------------Login Part
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://www.foreclosure.com/login.html?key='.$loginInfo['key'].'&password='.$loginInfo['password'];
curl_setopt($ch, CURLOPT_POST, 1); //Wouldn't work without it
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_COOKIEFILE, NULL);                     //NULL to use cookies in memory, use $cookiefile to store them in disk
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_NOBODY, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_BINARYTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_exec($ch);
curl_close($ch);


text:
Q: Are there "Dynamic Playlists" of unit tests in Visual Studio? When working with unit tests in Visual Studio, it's possible to compile playlists that group the tests. This is useful, for instance, when developing a new feature for which we want to run only the related tests and not all the existing ones.
However, it seems to me the playlists can only be maintained "manually", by explicitly adding/removing unit tests.
It's better than nothing, but it would be great if I could some how "tag" my unit tests depending on some criterion (e.g. feature, test duration, etc.) and generate the playlists dynamically.
Is there any way to do something similar in Visual Studio with the default testing framework?

A: You can run certain tests contextually in relation to the current cursor position by right clicking and then "Run Tests", or hitting CTRL+R then T.

*

*If the cursor is within the body of a test, only that test will be run.

*If the cursor is within the body of a test class, only the tests in that class will be run.

*If the cursor is within a namespace, all tests in that namespace will be run.

See MSDN documentation on the subject.
Alternatively you can filter the test explorer in various ways. I often use the Project flag to exclude certain projects for instance.

A: The ability to create a playlist which is defined dynamically was added with update 16.7.0 to Visual Studio 2019.
According to those notes, the playlist User Interface now contains checkboxes for the various selection criteria. The underlying XML seems to be a cascade of <Rule> elements.
To access the new user interface, it may be necessary to click the new pencil icon (tooltip: edit) in the Test Explorer toolbar, and confirm that the playlist may be updated to the new format.
From the source:

You can also use traits to define a dynamic group by editing the playlist xml file directly.

As of 2020-12-07, I finally got this to work. For the goal to run any test that includes the MSTest Attribute [TestCategory("SchemaUpdateBasic")], possibly with other instances of [TestCategory("...")]
<Playlist Version="2.0">
  <Rule Name="Includes" Match="Any">
    <Property Name="Trait" Value="SchemaUpdateBasic" />
  </Rule>
</Playlist>

As of Visual Studio version 16.8.2, this worked as desired. Prior versions resulted, for me, in the correct set of tests appearing in the Test Explorer window, but clicking "Run All" yielding this in Test Output
---------- Starting test discovery for requested test run ---------- Test run will use DLL(s) built for framework
...
========== Test discovery finished: 0 Tests found in 2.6 sec ========== No tests found to run.

Source:
https://learn.microsoft.com/en-us/visualstudio/releases/2019/release-notes#--visual-studio-2019-version-1670
Also https://github.com/MicrosoftDocs/visualstudio-docs/issues/6012 exists as a request for documentation enhancement.

A: In VS2017, you can group tests by Namespace, Class, Duration, Outcome, Traits or Project. Probably was there before, but I can't check first hand right now.
To do so, in the Test Explorer window, click on the second icon then whichever choice you want. By default, they're grouped by Outcome.
If you want to use Traits, add the Trait name/value attribute to your individual test cases:
[Trait("Foo", "Value1")]
[Trait("Foo", "Value2")]
[Trait("Bar", "Value")]
public void MyClass_MyMethod_WhenThing_Outcome()
{
    // ...
}


text:
Q: How can I get all the records that are in a intermediate table only once? This maybe is a complex question, but I'll try to explain at best.
I have the following models:
class Event(models.Model):
    name = models.CharField(max_length=128)

class Order(models.Model):
    requester = models.CharField(max_length=128)
    taker = models.CharField(max_length=128)
    email = models. EmailField()
    phone = models.CharField(max_length=13)

class Picture(models.Model):
    event = models.ForeignKey(Event)
    image = models.ImageField(upload_to='media')
    show_name = models.CharField(max_length=128, blank=True, null=True)
    file_name = models.CharField(max_length=128, blank=True, null=True)

class OrderItem(models.Model):
    order = models.ForeignKey(Order)
    picture = models.ForeignKey(Picture)
    amount = models.PositiveSmallIntegerField()

I need to get all the Orders that belong to an Event, but only once. This can be achieved by the Pictures. If a Picture is in an Order, I need the Event.
Example:
Event 1:
Pic 1, Pic 2

Event 2:
Pic 3, Pic 4

Order 1:
Pic 1, Pic 2, Pic 3, Pic 4

Order 2:
Pic 2

Order 3:
Pic 1

What I need:
Event 1 has 3 Orders (Order 1, Order 2 and Order 3)
Event 2 has 1 Order (Order 1)

Even if the Order contains several pictures from the Event, I just need it to count one time.
Any help would be appreciated. Thanks.

A: It has no difference than any other queries, just use double underscore to change the relation:
event = Event.objects.get(id=1)
orders = Order.objects.filter(orderitem__picture__event=event)

Edit:
To count the orders you do:
order_count = orders.distinct().count()


text:
Q: Web components in lit-element + SASS I'am developing some web components (I'm newbie) for an app with [lit-element] 1 (Rather than [open-wc] 2) and I want to create a "global default style" for my web components.
Could someone explain me concretely how to use SASS in a web component from scratch? I have read a lot of documentation, post and others, and nobody explains in a concise way how to do it (and everything I have tried doesn't work).
Thanks in advance.

A: SASS (a file on your harddisk) has little to do with Custom Elements/Web Components (run in the Browser).
SASS needs/is a pre processor, to convert (compact) SASS syntax into CSS;
because the Browser only understands CSS and does not understand SASS.
It is then up to you how you want to deliver that CSS to the Client
For now you:

*

*Inject a text string <style>[your CSS]</style> in the Component HTML.

*Include the styles in a template, you cloneNode(true) into your Component:

      <template id="component">
          <style>[your CSS]</style>
      </template>

*

*(Nov-2020) In Chrome you can already use Constructible/Constructable/Constructed StyleSheets
https://developers.google.com/web/updates/2019/02/constructable-stylesheets
More:

*

*https://css-tricks.com/styling-a-web-component/

*https://meowni.ca/posts/part-theme-explainer/


text:
Q: Gradle: how to move outputs of a task? I have set buildDir in build.gradle and all but one plugins honor that setting. For the one that insists on creating build/reports/license/ and placing its outputs there, I'd like to move these files to my ${buildDir}.
I tried adding a doLast block to the task
downloadLicenses {
    // ...
    doLast {
        file("build/reports/license").renameTo("${buildDir}/reports");
    }
}

but Gradle complains

Could not find method doLast() for arguments [build_3s5ts0z1u2ed2z2xpd2pa56i$_run_closure50$_closure144@4d98efa4] on root project 'myProject'.

What am I missing here and how can I move the files after the task is done?
Edit: The plugin in question is License Gradle Plugin, and I did report this as a bug. I am hoping for a workaround until this is officially fixed.

A: Which plugin is this?
Try the following
println downloadLicenses.class.name

Is that printing the name of a task? I'm guessing there's an extension object named downloadLicenses rather than a task
Assuming there's a downloadLicenses task which is "hidden" by downloadLicenses extension object, this should work
tasks.getByName('downloadLicenses').doLast { ... }

If the "build" directory is hard-coded you should raise an issue with the plugin's author

A: I am not sure I have understood your question, but, if you would like to move your file to ${buildDir}/reports I think this should be your doLast block:
doLast {
    file("build/reports/license").renameTo(file("${buildDir}/reports"));
}

I hope I am helping you!


text:
Q: set user agent in a node request I try to set user agent to a npm request. Here is the documentation, but it gives the following error:

Error: Invalid URI "/"

const request = require('async-request')

const run = async (url) => {
  const {statusCode} = await request(url)
  console.log(statusCode) // 200, works
  const options = {
    url,
    headers: {
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
    }
  }
  await request(options) // Error: Error: Invalid URI "/"
}

run('https://github.com/')

sandbox
I also tried request.get, as it mentioned in here, but it gives "request.get is not a function" error.

A: The problem is you are looking at the documentation of request, but using the async-request, which dont support calling with the object argument like you do.
const request = require('async-request')

const run = async (url) => {
  const {statusCode} = await request(url)
  console.log(statusCode) // 200, works
  const options = {
    headers: {
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.122 Safari/537.36'
    }
  }

  const res = await request(url, options);
  console.log(res.statusCode) // 200, works
}

run('https://github.com/')


text:
Q: Facebook graph API /me/friends not returns all friends who authorized app? After a long surf i have realized Graph API /me/friends only returns the person's friends who also use the app.anyway i need answer from an experienced one
Any possibility to fetch all friends of a user ?
Now my second query I have used the following code for fetching friends of a user after verifying and approved user_friends permission by team facebook and also I'm logging in with the user_friends permission.
 /* make the API call */
        new GraphRequest(
                AccessToken.getCurrentAccessToken(),
                "/me/friends",
                null,
                HttpMethod.GET,
                new GraphRequest.Callback() {
                    public void onCompleted(GraphResponse response) {
                     /* handle the result *
                    }
                }
        ).executeAsync();

Response
{Response:  responseCode: 200, graphObject: {"summary":{"total_count":572},"data":[]}, error: null}.

I have friends in my list whose also uses the same app but ain't get their information also you can see in the above response only total_count were returning.
What's going wrong, Can anyone help me out ?
Update
After some debugging now I'm getting only details of single friend in response while i have friends more than that whose using the app.why it won't return the other friends details ? any idea ?
Also when i debugged with Access Token Debugger, it tells that the user have user_friends scope.still ain't get the expected response.

A: If you are updating permissions in an existing application then exiting users will have to logout and login again with new set of permissions with new code.


text:
Q: data_mapper: Can't save Time object I am attempting to persist an object that has a Time-type field. On create, I attempt to set the sleep_value to a valid Time object but the save seems to fail silently (even though raise_on_save_failure is set to true).
If I try to search for the object via Sleep.all or Sleep.get(1), i am getting an error argument out of range.
The only value I can pass it to make it persist is Time.now(). If I do a Sleep.all, that object with sleep_time => Time.now is returned.
gems:
data_mapper (1.2.0)
sqlite3 (1.3.10)

require 'sqlite3'
require 'data_mapper'

DataMapper::setup(:default, "sqlite3://#{Dir.pwd}/test.db")

DataMapper::Model.raise_on_save_failure = true

class Sleep

    include DataMapper::Resource
    property :id,           Serial
    property :sleep_time,   Time

end

DataMapper.finalize.auto_migrate!

Sleep.create(:sleep_time => Time.new(2015, 10, 1))

Sleep.all

UPDATE: I have done a bit more trial and error and have found the following values are compatible with the time field (changed the name from sleep_time to st)
Sleep.create(:st => (Time.now - 1))
Sleep.create(:st => Time.at((Time.now - Time.at(1000))))

And the following values do not save (no error is thrown but records are nt persisted)
Sleep.create(:st => Time.new(2015, 10, 1, 2, 2, 2, "+02:00"))
Sleep.create(:st => Time.new(2002))
Sleep.create(:st => Time.new((Time.now - Time.new(2002)))) #out of range
Sleep.create(:st => Time.at(2)) #out of range

A: I used the fact that I could use with Time.now() and made this helper method. I call it to save my Time properties.
def self.convert_to_dm_friendly_time(target_time)
today = Time.now
return today + target_time.to_i - today.to_i #basically starting the object from today and then taking today out.

end

Damn, this was an ugly solution. Surely there is an easier way?


text:
Q: themeConfig.docs.sidebar options throws 'ValidationError: "docs.sidebar" is not allowed' on build I'm using Docusaurus 2.0.0-rc.1 and trying to add hideable: true and autoCollapseCategories: true options in docusaurus.config.js according to https://docusaurus.io/docs/sidebar#hideable-sidebar, but I've received an error during build:
> docusaurus build

[INFO] [en] Creating an optimized production build...
[ERROR] Unable to build website for locale en.
[ERROR] ValidationError: "docs.sidebar" is not allowed

My sidebars.js (autogenerated sidebar):
/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */
const sidebars = {
  DocSidebar: [{type: 'autogenerated', dirName: '.'}],
};

module.exports = sidebars;

My docusaurus.config.js:
// @ts-check
// Note: type annotations allow type checking and IDEs autocompletion

const lightCodeTheme = require('prism-react-renderer/themes/github');
const darkCodeTheme = require('prism-react-renderer/themes/dracula');

/** @type {import('@docusaurus/types').Config} */
const config = {
  title: 'Test portal',
  tagline: 'Test company',
  url: 'https://test.com',
  baseUrl: '/',
  onBrokenLinks: 'ignore',
  onBrokenMarkdownLinks: 'warn',
  favicon: 'img/favicon.ico',
  organizationName: 'Test.com', // Usually your GitHub org/user name.
  projectName: 'test-repo', // Usually your repo name.

  presets: [
    [
      'classic',
      /** @type {import('@docusaurus/preset-classic').Options} */
      ({
        docs: {
          lastVersion: 'current',
          versions: {
            current: {
              label: '1.1.0',
              path: '1.1.0',
              badge: true,
            },
          },
          sidebarPath: require.resolve('./sidebars.js'),
        },
        blog: false,
        theme: {
          customCss: require.resolve('./src/css/custom.css'),
        },
      }),
    ],
  ],

  themeConfig:
   /** @type {import('@docusaurus/preset-classic').ThemeConfig} */
    ({
       docs: {
        sidebar: {
          hideable: true,
          autoCollapseCategories: true,
        },
      },
      navbar: {
        title: 'Docs portal',
        logo: {
          alt: 'Company Logo',
          src: 'img/logo.png',
        },
        items: [
          {
            type: 'doc',
            docId: 'intro',
            position: 'left',
            label: 'Product docs',
          },
          {
            type: 'docsVersionDropdown',
            position: 'right',
            dropdownItemsAfter: [{to: '/versions', label: 'All versions'}],
            dropdownActiveClassDisabled: true,
          },
          {
          href: 'https://test.com',
          label: 'Test Company',
          position: 'right',
          },
        ],
      },
      footer: {
        style: 'dark',
         copyright: `Copyright © ${new Date().getFullYear()} Test Company Built with Docusaurus.`,
      },
      prism: {
        theme: lightCodeTheme,
        darkTheme: darkCodeTheme,
      },
    }),
};

module.exports = config;


text:
Q: mysql5.6 /bin/mysql can't work #why my  mysql5.6's /bin/mysql can't  use?

aiapple@aiapple:/usr/local/mysql55/bin$ echo $PATH
/usr/local/mysql55/bin:/usr/local/mysql56/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

#mv the mysql5.5's mysql
aiapple@aiapple:/usr/local/mysql55/bin$ mv mysql Mysql

#cp the mysql5.6's mysql
aiapple@aiapple:/usr/local/mysql55/bin$ cp -ar /usr/local/mysql56/bin/mysql .
aiapple@aiapple:/usr/local/mysql55/bin$ mysql -V
bash: /usr/local/mysql55/bin/mysql: No such file or directory
aiapple@aiapple:/usr/local/mysql55/bin$ ls -al mysql
-rwxr-xr-x 1 aiapple aiapple 7840392  5月 17 07:40 mysql
#it do not work

#But  the mysql5.5's mysql can work
aiapple@aiapple:/usr/local/mysql55/bin$ rm -rf mysql

aiapple@aiapple:/usr/local/mysql55/bin$ mv Mysql mysql
aiapple@aiapple:/usr/local/mysql55/bin$ mysql -V
mysql  Ver 14.14 Distrib 5.5.50, for linux2.6 (x86_64) using readline 5.1
#it works


text:
Q: Is there a simpler and faster way to get an indexes dict in which contains the indexes of the same elements in a list or a numpy array Description:
I have a large array with simple integers(positive and not large) like 1, 2, ..., etc. For example: [1, 1, 2, 2, 1, 2]. I want to get a dict in which use a single value from the list as the dict's key, and use the indexes list of this value as the dict's value.
Question:
Is there a simpler and faster way to get the expected results in python? (array can be a list or a numpy array)
Code:
a = [1, 1, 2, 2, 1, 2]
results = indexes_of_same_elements(a)
print(results)

Expected results:
{1:[0, 1, 4], 2:[2, 3, 5]}

A: You can avoid iteration here using vectorized methods, in particular np.unique + np.argsort:
idx = np.argsort(a)
el, c = np.unique(a, return_counts=True)

out = dict(zip(el, np.split(idx, c.cumsum()[:-1])))

{1: array([0, 1, 4], dtype=int64), 2: array([2, 3, 5], dtype=int64)}

Performance
a = np.random.randint(1, 100, 10000)

In [183]: %%timeit
     ...: idx = np.argsort(a)
     ...: el, c = np.unique(a, return_counts=True)
     ...: dict(zip(el, np.split(idx, c.cumsum()[:-1])))
     ...:
897 µs ± 41.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

In [184]: %%timeit
     ...: results = {}
     ...: for i, k in enumerate(a):
     ...:     results.setdefault(k, []).append(i)
     ...:
2.61 ms ± 18.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

A: It is pretty trivial to construct the dict:
In []:
results = {}
for i, k in enumerate(a):
    results.setdefault(k, []).append(i)   # str(k) if you really need the key to be a str
print(results)

Out[]:
{1: [0, 1, 4], 2: [2, 3, 5]}

You could also use results = collections.defaultdict(list) and then results[k].append(i) instead of results.setdefault(k, []).append(i)

A: We can exploit the fact that the  elements are "simple" (i.e. nonnegative and not too large?) integers.
The trick is to construct a sparse matrix with just one element per row and then to transform it to a column wise representation. This is typically faster than argsort because this transform is O(M + N + nnz), if the sparse matrix is MxN with nnz nonzeros.
from scipy import sparse

def use_sprsm():
    x = sparse.csr_matrix((a, a, np.arange(a.size+1))).tocsc()
    idx, = np.where(x.indptr[:-1] != x.indptr[1:])
    return {i: a for i, a in zip(idx, np.split(x.indices, x.indptr[idx[1:]]))}

# for comparison

def use_asort():
    idx = np.argsort(a)
    el, c = np.unique(a, return_counts=True)
    return dict(zip(el, np.split(idx, c.cumsum()[:-1])))

Sample run:
>>> a = np.random.randint(0, 100, (10_000,))
>>>
# sanity check, note that `use_sprsm` returns sorted indices
>>> for k, v in use_asort().items():
...     assert np.array_equal(np.sort(v), use_sprsm()[k])
...
>>> timeit(use_asort, number=1000)
0.8930604780325666
>>> timeit(use_sprsm, number=1000)
0.38419671391602606


text:
Q: How to validate in javascript the below select element if empty on submit I need some advise on how to validate if the below select element is empty or not on form submit. I use a validate function that works for regular select or text elements when the id and name are in this format id=tag and name=tag but I cannot find the proper way to make it work for id=tag[] and name=tag[]:
<select name="tag[]" id="tag[]">
    <option value="">Please Select</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

This is the function I use:
function validate(){
      with (document.form){
      if(tag.value==""){
           alert("Enter tags");
           tag.focus();
           return false;
      }
return true;
}

So what should be the tag.value=="" in this case?
I tired tag[].value=="" and tag[0].value=="" without success.

A: Try this it works

function validate() {
  var selectValue = window.document.myForm["tag[]"].value;
  if (selectValue == "") {
    alert("Invalid : Enter tags");
    window.document.myForm["tag[]"].focus();
    return;
  }
  alert("Valid");
}
<form name="myForm">
  <select name="tag[]" id="tag[]">
    <option value="">Please Select</option>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
  </select>

</form>

<button onclick="validate()">Validate</button>

A: Try this (for validateJS)
constraints[treatment_type] = {"format": {"pattern":"4","message": "You need
To select Hospitalization"},"presence": {"message": "Value is required"}}

The object created is :
constraints = {
treatment_type:

format: {pattern: "4", message: "You need To select Hospitalization"}
presence: {message: "Value is required"}
}


text:
Q: How to find all possible paths with as many edges between two same vertices? Suppose I have an undirected graph G = Graph[{1 <-> 2, 2 <-> 3, 2 <-> 3, 3 <-> 4}]

I used FindPath[G,1,4,Infinity,All] and obtained the result

{{1, 2, 3, 4}}

But the expected result is

{{1, 2, 3, 4}, {1, 2, 3, 4}}

Is there any way to get all possible paths even though any number of edges are present in between two same vertices?

Link to Wolfram Community cross post.

A: First, to get this out of the way: I would not consider this a bug. FindPath returns a sequence of vertices, not a sequence of edges, which indicates the definition of path that is meant here.  {{1,2,3,4},{1,2,3,4}} are of course the very same sequence of vertices, regardless of any edges inbetween, thus there is no reason for FindPath to return them multiple times.

If needed, you can take the multiplicities of edges into account like this.
First convert to a list of edges:
FindPath[graph, 1, 4, Infinity, All]
path = First[%]
(* {1, 2, 3, 4} *)

edgeSequence = Sort /@ UndirectedEdge @@@ Partition[path, 2, 1]
(* {1 <-> 2, 2 <-> 3, 3 <-> 4} *)

edgeMultiplicities = Counts[Sort /@ EdgeList[graph]]
(* <|1 <-> 2 -> 1, 2 <-> 3 -> 2, 3 <-> 4 -> 1|> *)

edgeMultiplicities /@ edgeSequence
(* {1, 2, 1} *)

Times @@ %
(* 2 *)

The result is that this path should be taken into account twice.
The Sort was necessary to canonicalize directed edges, and make sure that 1<->2 and 2<->1 are treated as the same.

A: If the aim to count the paths of certain length [including traversing same vertices/edges multiple times: see comment Szabolcs]  (and it may not be) you could use AdjacencyMatrix, e.g.
g = Graph[{1 <-> 2, 2 <-> 3, 2 <-> 3, 3 <-> 4}]

then
np[g_, i_, j_, n_] := MatrixPower[AdjacencyMatrix[g], n][[i, j]]

so np[g,1,4,3] yields 2, np[g,2,2,3] yields 0 (as would any odd number of steps)  but np[g,2,2,4] yields 29.


text:
Q: Riemannian manifold with almost nonnegative sectional curvature A Riemannian manifold has almost nonnegative sectional curvature if it admits a sequence of  Riemannian metric $g_{i}$ such that $sec(g_{i})\geq (-1/i)$ and $D(g_{i})\leq 1$ where $sec(g_{i})$ is the sectional curvature of $g_{i}$ and $D(g_{i})$ is the diameter of $g_{i}$. ( see, https://www.sciencedirect.com/science/article/abs/pii/S0001870820302759)
My questions are those:
1-Could this definition be true for manifold with boundary?
2- What is the definition of the Riemannian curvature of manifold with boundary?
I have not found any things in the literature review about that when the boundary exists.


text:
Q: How do I implement efficient file upload to device over RS-232 I need to upload a file to a target platform over RS-232 protocol.
The input is a file (which has the memory address, the no. of bytes and the data to be written to the device memory). Since I am doing a block write through RS-232 I have followed this approach. But are there efficient ways to implement the below scheme as I am starting to code in C# and also in case I wish to show the download progress bar (based on the number of bytes written vs the total bytes). Do I implement this in a separate thread and update in the GUI. Are there any performance issues seen if the file size goes large with this scheme?
Below is the code:
private void DownloadToDevice(String file_path)
{
     FileData = System.IO.File.ReadAllBytes(file_path);

     StartAddress = BitConverter.ToUInt32(FileData, 12);
     StartAddress = FileData.ElementAt(12);

     NumOfBytes = BitConverter.ToUInt32(FileData, 16);
     NumOfBytes = FileData.ElementAt(16);

     Block = FileData.Skip(20).Take((int)NumOfBytes).ToArray();
     WriteBlock(StartAddress, Block, Block.Length);
}

private void WriteBlock(UInt32 Address, byte[] Data, int val)
{
    String command2 = "";
    UInt32 Data2;

    String command1 = String.Format("wr {0}", Address.ToString("x").PadLeft(8, '0'));

    for (int i = 0; i <= val ; i= i + 4)
    {
        Data2 = BitConverter.ToUInt32(Data,i);
        command2 = string.Concat(command2, String.Format("{0} ", Data2.ToString("x").PadLeft(8, '0')));
    }

    command1 = string.Concat(command1," ", command2,"\r");
    m_SP.Write(command1);
}


text:
Q: smooth video progress bar update javascript I have a custom video progress bar on my site which is working well.
But the progression update is jumping between values and I'm trying to smooth it.
HTML:
<video id ="myVideo">
 <source src="myvideo.mp4">
</video>

SASS:
.progress
  width: 100%
  height: 8px
  background: #fff
  position: absolute
  bottom: 0
  .timeElapsed
    position: absolute
    height: 100%
    width: 0%
    background: #000

JS:
var myVideo = document.querySelector('#myVideo'),
    progress = document.querySelector('.progress'),
    timeElapsed = document.querySelector('.timeElapsed'),
    duration,
    percentage,
    currentTime;

myVideo.addEventListener('timeupdate', function(){
  duration = myVideo.duration
  currentTime = myVideo.currentTime
  percentage = (100 /duration) * currentTime
  timeElapsed.style.width = percentage + '%'
})

When I console.log(percentage) in my timeupdate event, I have this output :
0.14095513960976902
0.3264236667597889
0.6970909117642735
1.0636110335092854
1.2511968652129803
1.435445001543868
1.79435606004911
1.9811530487715225
2.1658047962829547
2.532771904544853
2.7182242578406437

With this result and the way it's displayed in the console I know that I'm missing something but I don't know what, any solution here ?

A: Try to add to .timeElapsed a transition. For example, transition: 100ms


text:
Q: Mocking xml file for unit testing with Rhinomocks I want to mock xml used as below for unit tests.I am using Rhinomocks framework for mocking.How can I unit test my methods by not using the actual xml file.Do I have to change my code structure.
 [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class MyService : IMyService
{
    private readonly string mSchemaPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data",
        "schema_0.1.xsd");
    private readonly string mXmlPath = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data",
        "MyDataRecords.xml");

    private XDocument mXDocument;

    public MyService()
    {
        try
        {
            //load xml document
            mXDocument = XDocument.Load(mXmlPath);

            if (mXDocument == null)
            {
                throw new Exception("Null returned while reading xml file");
            }
        }
        catch (Exception e)
        {
           //my exception management code
        }
    }

    public List<MyDataRecords> GetAllRecords()
    {
        ////fetch records from xDocument

       mXDocument.Save();
    }
    public void AddRecord(MyRecord record)
    {
        ////add record

       mXDocument.Save();
    }

A: UPDATED:
I've modified your MyService class to have an overloaded constructor, which accepts Func<string, XDocument> to load an XDocument, and also Func<string> to resolve the value that corresponds to HostingEnvironment.ApplicationPhysicalPath . When the default constructor is called, the same call to XDocument.Load is performed, and likewise for using HostingEnvironment.ApplicationPhysicalPath in building the path to the xml and xsd files.
However in an unit test you could call the other constructor like this:
        const string mockDirectory = "TEST";
        var expectedXmlPath = Path.Combine(mockDirectory, "App_Data", "MyDataRecords.xml");
        string xmlPathPassed = "";
        var service = new MyService(path =>
            {
                xmlPathPassed = path;
                return XDocument.Parse("<note><to>Tove</to><from>Jani</from><heading>Reminder</heading><body>Don't forget me this weekend!</body></note>");
            },
            () => mockDirectory);
        Assert.Equal(expectedXmlPath, xmlPathPassed);

You could also expose the XDocument on the Service, perhaps through a readonly property and check that the XDocument represents the Mocked xml.
MyService:
public class MyService : IMyService
{
private const string AppDataDirectoryName = "App_Data";
private const string SchemaFileName = "schema_0.1.xsd";
private const string XmlFileName = "MyDataRecords.xml";
private readonly Func<string, XDocument> mdocumentLoader;
private readonly Func<string> mAppDataDirectoryBuilder;
private readonly string mSchemaPath = "";
private readonly string mXmlPath = "";
private XDocument mXDocument;

public MyService() : this(XDocument.Load, () => HostingEnvironment.ApplicationPhysicalPath)
{
}

public MyService(Func<string, XDocument> documentLoader, Func<string> appDataDirectoryBuilder)
{
    mdocumentLoader = documentLoader;
    mAppDataDirectoryBuilder = appDataDirectoryBuilder;
    try
    {
        var baseDirectory = mAppDataDirectoryBuilder();
        mSchemaPath = Path.Combine(baseDirectory, AppDataDirectoryName, SchemaFileName);
        mXmlPath = Path.Combine(baseDirectory, AppDataDirectoryName, XmlFileName);
        mXDocument = mdocumentLoader(mXmlPath);

        if (mXDocument == null)
        {
            throw new Exception("Null returned while reading xml file");
        }
    }
    catch (Exception e)
    {
        //my exception management code
    }
}

public List<MyRecord> GetAllRecords()
{
    ////fetch records from xDocument
    return null;
    //mXDocument.Save();
}

public void AddRecord(MyRecord record)
{
    ////add record
    // mXDocument.Save(record);
}

}

A: [assembly: InternalsVisibleTo("MyService.UnitTests")]
public class MyService : IMyService
{

private readonly string mSchemaPath;

private readonly string mXmlPath;

 public MyService()
        : this(
            Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data", "MyDataRecords.xml"),
            Path.Combine(HostingEnvironment.ApplicationPhysicalPath, "App_Data", "schema_0.1.xsd"))
    {

    }

internal MyService(string xmlPath,string schemaPath)
{
    try
    {
         mXmlPath=xmlPath;
         mSchemaPath=schemaPath;

        //load xml document
        mXDocument = Xdocument.Laod(mXmlPath);

        if (mXDocument == null)
        {
            throw new Exception("Null returned while reading xml file");
        }
    }
    catch (Exception e)
    {
        //my exception management code
    }
}

public List<MyRecord> GetAllRecords()
{
    ////fetch records from xDocument

    mXDocument.Save();
}

public void AddRecord(MyRecord record)
{
    ////add record

    mXDocument.Save();
}

}


text:
Q: Notifications for SQL Job when a step fails Trying to find out if there is a way to setup email notifications when just 1 (or more) steps fail on a sql job.  I have a job with 9 steps, but each step needs to be set to continue to next step even if it fails.  So even when a step fails, because I need it to go to the next step its not set to "report failure". As SQL Server Agent does not have an option for "Report failure and go to next step" I am wondering if anyone has any workarounds for getting a notification

A: You can add an additional job step to query the msdb tables for steps that failed.  After this, the sp_send_dbmail stored procedure can be used to send an email with the errors if any occurred.  The run_date column of SYSJOBHISTORY is an int column, so the date will be along the format of YYYYMMDD.  The filter below on the run_status column will apply to individual steps regardless of the overall job outcome, with 0 indicating a status of failed.
DECLARE @JobExecutionDate INT

--current date
SET @JobExecutionDate = CAST(CONVERT(VARCHAR(8),GETDATE(),112) AS INT)

--check if there were any errors first
IF EXISTS (SELECT h.instance_id
FROM MSDB.DBO.SYSJOBHISTORY h
         INNER JOIN MSDB.DBO.SYSJOBS j ON h.job_id = j.job_id
         INNER JOIN MSDB.DBO.SYSJOBSTEPS s ON j.job_id = s.job_id AND h.step_id = s.step_id
WHERE h.run_status = 0 AND h.run_date = @JobExecutionDate AND j.name = 'YourJobName')

BEGIN

DECLARE @Title VARCHAR(50)

SET @Title = CONCAT(CONVERT(VARCHAR(12), CAST(GETDATE() AS DATE), 109), ' Job Error Email')

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Your Database Mail Profile',
    @recipients = 'ExampleEmail@Domain.com',
@query = 'SELECT  j.[name] AS JobName,
         s.step_name AS StepName,
         h.run_date AS RunDate,
         h.run_time AS RunTime,
         h.sql_severity As ErrorSeverity,
         h.message AS ErrorMessage
FROM MSDB.DBO.SYSJOBHISTORY h
         INNER JOIN MSDB.DBO.SYSJOBS j ON h.job_id = j.job_id
         INNER JOIN MSDB.DBO.SYSJOBSTEPS s ON j.job_id = s.job_id AND h.step_id = s.step_id
WHERE h.run_status = 0 AND h.run_date = CAST(CONVERT(VARCHAR(8),GETDATE(),112) AS INT) AND j.name = ''YourJobName''
',
  @query_result_no_padding = 1,
    @subject = @Title ;

END


text:
Q: Carregamento assíncrono de vídeos Eu tenho uma página com vários vídeos que vem do Youtube, essa página demora um tempo considerável para carregar e em computadores mais antigos, a página fica travada até que tudo seja carregado.
Existe algum jeito de carregar os vídeos de forma assíncrona sem que os vídeos atrapalhem o carregamento da página?
Tem alguma saída para isso com HTML ou só utilizando Javascript?
Os vídeos são carregados através de iframes.
<iframe width="400" height="220" src="https://youtube.com/embed/id_do_video" allow="autoplay; encrypted-media" allowfullscreen></iframe>


text:
Q: get the first day of each month between two dates in python I would like to perform a cycle between two dates considering only the first day of each month between the selected dates.
My starting point is the following script:
import datetime

start_date = datetime.date(2020, 1, 1)
end_date   = datetime.date(2020, 4, 4)
delta = datetime.timedelta(days=1)

while start_date <= end_date:

    print(start_date)

    start_date += delta

It works when I choose:
delta = datetime.timedelta(days=1)

but it gives me an error when I try to select "months" as delta time.
Could some one give a glue on this.
This is the solution that I set-up following the suggestions reported bellow:
import datetime

start_date = datetime.date(2020, 1, 1)

end_date = datetime.date(2020, 4, 4)

datenow = start_date

while datenow <= end_date:

    y,m     = divmod(datenow.year*12+datenow.month,12)
    datenow = datetime.date(y,m+1,1)
    print(datenow)


text:
Q: youtube statistics API broken First of all, sorry for my badly articulated question, this is my first ever question to post here.
I have programmed a youtube search engine for myself and used it for a long time. Yesterday i noticed it was not working correctly anymore.
I spent some time looking for the problem and soon enough noticed that some of the video statistic data queries return nothing.
Here is an example API URL that doesn't work:
https://www.googleapis.com/youtube/v3/videos?id=nNmfb2FQ8MA&key=PUT API KEY HERE&fields=items(statistics)&part=statistics
If you replace the video ID it should return the statistics of the video.
It just doesnt show anything for some youtube IDs for some reason


text:
Q: How to complete login authentication in react by using react query mutations? I am trying to complete login authentication of my app by using react query.
Firstly i have created mutation function by using use mutation which is,
import { useMutation } from 'react-query'
import MainApi from '../../../api/MainApi'
import { login_api } from '../../../api/ApiEndPoints'

const addLoginCredentials = (loginCredentials) => {
    return MainApi.post(login_api, {
        email_or_phone: loginCredentials.email,
        password: loginCredentials.password,
    })
}
export const useAddLoginCredentials = () => {
    return useMutation(addLoginCredentials)
}

after that i imported it to my main component. Which is,
const {
        mutate,
        isError,
        error,
        isLoading,
        isSuccess,
        status,
        data: loginData,
    } = useAddLoginCredentials()

then i wanted to pass data on the mutate properties of this, within a submit function, which is,
  onSubmit: async (values, helpers) => {
            mutate(values
        },

when i click the login button which calls the onSubmit function, it hits the api, and gets some data, when i get the data, i want to show toasters inside , isSuccess. I wrote the code for the desired outcome, which is,
if(isSuccess){
toast.success('done')
}

but it renders multiple times with my login button click. I want to show the toaster only one time, exactly after the api call done.

A: The fact that is shows multiple toast points to the fact you should not use isSuccess flag of mutations/queries to handle toasts because if the component rerenders for unrelated reasons to the mutation or query, it will show a new toast. Instead, you need to use the onSuccess callback that only fires when success happens.
onSubmit: async (values, helpers) => {
  mutate(values, { onSuccess: () => toast.success('done') })
}


text:
Q: Brio save file without column headings How can I prevent the column headings from appearing in a .txt save file in Hyperion ?

A: Here is the answer from Oracle/Hyperion:
You are correct that the headers still appear on the export of the section to .xls format. If you are attempting to export the section and do not want the headers present, you will need to export out as one of the Office Archive formats that are provided (Microsoft Office 2000 HTML (.html) or  (.mhtml)). There is no option through the GUI to export a file in the Excel (.xls) format and not have the headers present.

A: On the main menu bar select Format. In the dropdown, there is an option for 'Column Titles'. Selecting the 'Column Titles' option with uncheck it, removing the column titles from the results.

A: A workaround, assuming you have no duplicate rows, is to create a Pivot section for the Table/Result set, and bring in every column as a Side Label, and turn off all the Top/Side/Corner labels.  Export the Pivot section.  Works best if you're pulling in a unique identifier for each row.


text:
Q: Remember user selection and redirect We are planing to add a policy page as first page in SharePoint site. Its a simple page with only text about company policy and a continue or exit button.
We would like to track which users have hit the continue button and in future not show the page to them. Instead take them to the homepage.
I was thinking that maybe we should create a list containing all the users but then I will have to fetch all AD accounts into a list and add a column and some code on the policy page to detect whether user hit continue and update the column accordingly.  Then, code a http redirector to query this list and redirect to homepage if column is set.
Is this ideal approach?
UPDATE
I have accepted an answer but we have taken a different approach for this requirement. We have implemented this using the user profile service application. We imported all users from AD into the SP user profile application rather than into a list. Here are links that will help you to fetch/save info into the user profile properties via JS code.
User Profile Service Application to sync User Info List with AD
How can we save data into the User Profile custom property?
How to access the data from Manage User Profiles?

A: Here is the scenario that PirateEric outlines, using SPServices and jQuery.
Prepare:
- A SharePoint custom list called PolicyAccepted with two text fields, i.e. Title and UserName.
- a document library with two web part pages, PolicySplash.aspx and PolicyAccepted.aspx.
The page PolicySplash loads the script at the top, in the first web part on the page, via script link. If the script is loaded in the footer web part, the page content will briefly show before the redirect, which is not desired.
The page PolicySplash also contains a button that is rendered from the following html:
<button onclick="PolicyButtonClick()" type="submit">I accept the policy</button>

Here is the script:
<script language="javascript" type="text/javascript" src="/path/jquery-1.10.2.min.js"></script>
<script language="javascript" type="text/javascript" src="/path/jquery.SPServices-2013.02a.min.js"></script>
<script type="text/javascript">
// start the code even before the DOM is loaded, so not waiting for document ready
//$(document).ready( function() {
// get the user name
  var userName= getUserName();
// find the user name in the list
  var userAccepted = matchUserName(userName);
  if (userAccepted == 1 )
    {
    // redirecting page
        window.location.replace("http://path/Documents/PolicyAccepted.aspx");
    }
//});

function getUserName() {
    var thisUserAccount= $().SPServices.SPGetCurrentUser({
    fieldName: "Name",
    debug: false
    });
    return(thisUserAccount);
}

function createNewItem(theTitle, theUser) {
    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        batchCmd: "New",
        listName: "PolicyAccepted",
        valuepairs: [["Title", theTitle], ["UserName", theUser]],
        completefunc: function(xData, Status) {
        }
    });
}

function matchUserName(userName) {
    var queryText = "<Query><Where><Eq><FieldRef Name='UserName'/><Value Type='Text'>" + userName + "</Value></Eq></Where></Query>";
    $().SPServices({
        operation: "GetListItems",
        listName: "PolicyAccepted",
        async: false,
        CAMLQuery: queryText,
        completefunc: function (xData, status) {
            itemCount = $(xData.responseXML.xml).find("rs\\:data, data").attr("ItemCount");
        }
    });
    return(itemCount);
}

function PolicyButtonClick() {
    var userName= getUserName();
    var theTitle= "Accepted";
    createNewItem(theTitle, userName);
    window.location.href = "http://path/Documents/PolicyAccepted.aspx";
}

</script>

Edit. I wrote this up in a blog post.

A: I would probably take that approach. Create a simple custom list. On page load, query the list to see if the user has acknowledged the agreement. If no, present the agreement. When they agree, insert a new record into the list. Then on subsequent visits if they agree you'd just do a javascript redirect.
This gives you the ability to flush the list and enforce everyone to agree to updated policies.
You could also introduce the use of cookies or local storage to cut down on the traffic.


text:
Q: invalid operands to binary expression when overloading a operator I'm trying to write a c++ program which implements a simple Matrix with mul and add operator overloading. My matrix is stored in a simple Vector. I also overloaded the () operator to easily store the values in my Matrix.
template < typename T1, int rows, int cols>
class Matrix{
public:
int row = rows;
int line = cols;
vector<T1> local_matrix;
Matrix(){
    local_matrix = vector<T1>(rows*cols, 0);
}
T1 &operator () (int i, int j){
    return local_matrix.at(i * cols +j);
}
const Matrix<T1, rows, cols> operator* (const Matrix<T1, rows, cols> &other)     const{
    Matrix<T1, other.row, other.line> result; // store the result here
    int sum_elements_i = 0;
    int left_counter = 0; // counter to iterate over the left Matrix
    int right_counter = 0; // and for the right one
    for(int i = 0; i < rows -1;++i){
        for(int j = 0; j < other.spalte -1; ++j){
            sum_elements_i = 0;
            for(int k = 0; k < other.reihe -1; ++k){
                sum_elements_i += local_matrix.at(left_counter) * other.local_matrix.at(right_counter);
                left_counter++; // get the next value of the left matrix
                right_counter += other.line; // and the next one of the right here we need to skip n-elements
                                            // so its the 1st/2nd/.. value of the next line
            }
            right_counter = j+1;
            result(i, j) = sum_elements_i;
        }
        left_counter = i+1;
    }
    return result;
}
};

My Problem with the * operator is that everytime i want to multiply a 4x3 with a 3x3 matrix the program crashes with the following errormsg:
invalid operands to binary expression ('Matrix<int, 4, 3>' and 'Matrix<int, 3, 3>')
E = D*A;
    ~^~

And here is the Code I'm calling my function:
Matrix<int, 3, 3> A; // Datatype, Rows, Columns
A(0,0) = 1; A(0,1) = 2; A(0,2) = 3;
A(1,0) = 1; A(1,1) = 2; A(1,2) = 3;
A(2,0) = 1; A(2,1) = 2; A(2,2) = 3;

Matrix<int, 4, 3> D, E;
D(0,0) = 1; D(0,1) = 2; D(0,2) = 3;
D(1,0) = 4; D(1,1) = 5; D(1,2) = 6;
D(2,0) = 7; D(2,1) = 8; D(2,2) = 9;
D(3,0) = 7; D(3,1) = 8; D(3,2) = 9;

std::cout << std::endl << "D:\n" << D << std::endl;

E = D*A;

Any help would be much appreciated, thanks.

A: you have to use correct matrix size for operator *:
template <typename T, std::size_t N, std::size_t K, std::size_t M>
Matrix<T, N, M> operator* (const Matrix<T, N, K>& lhs, const Matrix<T, K, M>& rhs);

A: The way you have defined your function, your function has the signature Matrix<int, 4, 3> Matrix<int, 4, 3>::operator(const Matrix<int, 4, 3> &) const which means that you would have to try to multiply a 4 by 3 matrix with a 4 by 3 matrix and that it would somehow give you another 4 by 3 matrix.  What you want instead, at minimum, is to declare your operator* as
    template <int cols2>
    Matrix<int, rows, cols2> operator*(const Matrix<int, cols, cols2> & other) const {...}

That will allow you multiply, for example, a 4 by 3 matrix with a 3 by 3 matrix and that will correctly output a 4 by 3 matrix.
Another change you can make to allow more types of matrices to be multiplied together is to make the signature
  template <class T2, int cols2>
  Matrix<typename std::common_type<T, T2>::type, rows, cols2>
      operator*(const Matrix<T2, cols, cols2> & other) const {...}


text:
Q: How to set custom background color for selected rows in igx-grid I am using Infragistics igxGridComponent. I am trying to style the look of selected rows.
I have tried setting my own css classes:
.selected-row {
  background-clor:red;
  color:white;
  font:bold;
}

However, I am not really sure how to apply them conditionally. Should I be using ngClass or there is another syntax to this?

A: You can use the igx-grid-theme SASS function to create a custom theme:
$custom-theme: igx-grid-theme(
  $row-selected-background: green,
  $row-selected-text-color: #000,
  $row-selected-hover-background: red
);

And then pass it to the igx-grid SASS mixin:
::ng-deep {
  @include igx-grid($custom-theme);
}

Here you can find an example.


text:
Q: Is it possible use different instance of UIMenuController for UITextField in Swift? According to link we should use a singleton UIMenuController instance which is referred to the editing menu.
The problem is I want to show extra items in different situations. For instance, I want to just show "copy" item when keyboard is up. and show "copy" and "reply" when tapping on a tableview row.
When I add "reply" to the UIMenuController instance it is shown when tapping on UITextField too. therefore, I added these codes:
func textViewDidBeginEditing(_ textView: UITextView) {
var nonReplyMenuItems: [UIMenuItem] = []
        if let allMenuItems = UIMenuController.shared.menuItems {
            for menuItem in allMenuItems {
                if menuItem.title != "reply".localized {
                    nonReplyMenuItems.append(menuItem)
                }
            }
        }
        UIMenuController.shared.menuItems = nonReplyMenuItems
        UIMenuController.shared.setMenuVisible(true, animated: true)
}

It fixed the problem in most situations, but not all.
when keyboard is up and tapping on a row in tableview "reply" will be added. Then when I tap on UITextView the reply will be shown there too.

A: It seems your scenario is like it:
tap on textfield ----> shows copy
tap on tableview ---> shows copy and reply
tab on textfield ----> shows copy and reply (you want only copy shows)
As I know the textViewDidBeginEditing calls when your text filed is not editing and you tap on that; So if you have two textfileds by switching on that method  calls every time but when you are switching between a text filed and another action base object your text field is editing and its state has not changed.
When you touch on tableview you must call textfield.resignFirstResponder() so when you tap on text field again the textViewDidBeginEditing  calls again, the problem of this is hiding keyboard; The better way I preferو is adding function to touch down of text field or on gesture to do what you write on textViewDidBeginEditing method


text:
Q: Creating new component fails: Unable to resolve module I created a fresh react native project (version 0.47.1). Now I'm trying to write a new component for my react native app.

/my-component.jsx

import React from 'react';
import {Text} from 'react-native';

export default class MyComponent extends React.Component {
    render() {
        return <Text>My Component</Text>
    }
}

/index.android.js

import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import MyComponent from './my-component';

export default class Test extends Component {
    render() {
        return (
            <MyComponent />
        );
    }
}

AppRegistry.registerComponent('test', () => Test);

The packager throws the following error:
error: bundling failed: "Unable to resolve module `./my-component` from `<project_root_dir>/index.android.js`:
could not resolve `<project_root_dir>/my-component' as a folder: it did not contain a package, nor an index file"

Adding the file extension to the import results in the same error, except with the file extension appended to the paths in the error.
The same error goes for dependencies added via npm. In any case the path shown in the error exists.

A: It seems like you have moved the entry file i.e index.android.js into a custom directory i.e test => (test/index.android.js). For this purpose it cannot locate the entry file. Placing the index.android.js again into the root directory will solve the problem.
If you want to change the entry point of the project you can refer the following:
https://github.com/facebook/react-native/issues/3442
Change entry file path of android and ios in react-native project