text:
Q: Grouping data in SQL Server by multiple references

Store    Grupa Quantity  Value          ITTYPE
1         A1 -44128       -101409.6          100
1         B1 -50000        -1500             101
1         E1 -32560       -53720.62     100
1         C1 -54730       -29006.9          101
1         D1 -45720       -37033.2          101
1         E1 -370500       -171100.61  100
2         E1 -370500       -227038.7          101
2         C1 -37152       -18575.94          100
2         C1 -145980       -52261.57          100
2         B1 -75600       -40639.65       100
2         B1 -69750       -64170          100

And I want a grouping by Store and Grupa

<!-- begin snippet: js hide: false console: true babel: false -->

And I want a grouping by Store and Grupa

ITTYPE                  100             100           101       101
Store    Grupa   Quantity         Value         Quantity   Value
 1        A1   -44,128.00      -101,409.60       -         -
 1        B1             -         -         -50,000.00   -1,500.00
 1             C1             -         -         -54,730.00    -29,006.90
 1             D1             -          -          -45,720.00   -37,033.20
 1        E1   -403,060.00      -224,821.23       -         -
 2        A1          -               -            -         -
 2        B1    -145,350.00      -104,809.65       -         -
 2             C1    -183,132.00      -70,837.51         -         -
 2        D1          -               -            -         -
 2        E1          -               -        -370,500.00    -227,038.70

IT's like a sumifs by Store, Grupa and also by ITTYPE

A: You could try something like this:
WITH RawData AS (
    SELECT 1 AS Store, 'A1' AS Grupa, -44128 AS Quantity, -101409.6 AS [Value], 100 AS ITTYPE
    UNION ALL
    SELECT 1, 'B1', -50000, -1500, 101
    UNION ALL
    SELECT 1, 'E1', -32560, -53720.62, 100
    UNION ALL
    SELECT 1, 'C1', -54730, -29006.9, 101
    UNION ALL
    SELECT 1, 'D1', -45720, -37033.2, 101
    UNION ALL
    SELECT 1, 'E1', -370500, -171100.61, 100
    UNION ALL
    SELECT 2, 'E1', -370500, -227038.7, 101
    UNION ALL
    SELECT 2, 'C1', -37152, -18575.94, 100
    UNION ALL
    SELECT 2, 'C1', -145980, -52261.57, 100
    UNION ALL
    SELECT 2, 'B1', -75600, -40639.65, 100
    UNION ALL
    SELECT 2, 'B1', -69750, -64170, 100),
Store AS (
    SELECT DISTINCT Store FROM RawData),
Grupa AS (
    SELECT DISTINCT Grupa FROM RawData)
SELECT
    s.Store,
    g.Grupa,
    SUM(CASE WHEN r.ITTYPE = 100 THEN r.Quantity END) AS [100_Quantity],
    SUM(CASE WHEN r.ITTYPE = 100 THEN r.[Value] END) AS [100_Value],
    SUM(CASE WHEN r.ITTYPE = 101 THEN r.Quantity END) AS [101_Quantity],
    SUM(CASE WHEN r.ITTYPE = 101 THEN r.[Value] END) AS [101_Value]
FROM
    Store s
    CROSS JOIN Grupa g
    LEFT JOIN RawData r ON r.Store = s.Store AND r.Grupa = g.Grupa
GROUP BY
    s.Store,
    g.Grupa
ORDER BY
    1,2;

Noting that if you have more ITTYPES than 100 and 101 then you might be better off with a dynamic PIVOT?
Results are:
Store   Grupa   100_Quantity    100_Value   101_Quantity    101_Value
1       A1      -44128          -101409.60  NULL            NULL
1       B1      NULL            NULL        -50000          -1500.00
1       C1      NULL            NULL        -54730          -29006.90
1       D1      NULL            NULL        -45720          -37033.20
1       E1      -403060         -224821.23  NULL            NULL
2       A1      NULL            NULL        NULL            NULL
2       B1      -145350         -104809.65  NULL            NULL
2       C1      -183132         -70837.51   NULL            NULL
2       D1      NULL            NULL        NULL            NULL
2       E1      NULL            NULL        -370500         -227038.70

A: Try This:
DECLARE @table TABLE (
Store INT,Grupa NVARCHAR(5), Quantity DECIMAL(10,2), Value DECIMAL(10,2), ITTYPE INT)
INSERT INTO @table VALUES
(1         ,'A1',   -44128        ,-101409.6     ,100),
(1         ,'B1',   -50000        ,-1500         ,101),
(1         ,'E1',   -32560        ,-53720.62     ,100),
(1         ,'C1',   -54730        ,-29006.9      ,101),
(1         ,'D1',   -45720        ,-37033.2      ,101),
(1         ,'E1',   -370500       ,-171100.61    ,100),
(2         ,'E1',   -370500       ,-227038.7     ,101),
(2         ,'C1',   -37152        ,-18575.94     ,100),
(2         ,'C1',   -145980       ,-52261.57     ,100),
(2         ,'B1',   -75600        ,-40639.65     ,100),
(2         ,'B1',   -69750        ,-64170        ,100)

SELECT Store ITTYPE,Grupa Grupa,SUM(CASE WHEN ITTYPE = 100 THEN Quantity ELSE '0' END) Quantity,
                                SUM(CASE WHEN ITTYPE = 100 THEN Value ELSE '0' END) Value,
                                SUM(CASE WHEN ITTYPE = 101 THEN Quantity ELSE '0' END) Quantity,
                                SUM(CASE WHEN ITTYPE = 101 THEN Value ELSE '0' END) Value
FROM @table GROUP BY Store,Grupa ORDER BY Store,Grupa

Hope it helps. :)


text:
Q: Does Apache FTP client compress files while transfer? I have problem where I need to transfer huge files from server to client through FTP which taking lot of time. We are currently using FTPClient available in apache.commons.net library.
So question is - Does FTPClient compress file while transfer? OR Is there any way I fasten the transfer?
Any pointers or related information would be of great help!

A: Yes that's called Mode Z (or Compressed Transfer Mode).
FTPClient ftpClient = new FTPClient();
ftpClient.connect(server.getServer());
ftpClient.login(server.getUsername(), server.getPassword());
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileTransferMode(FTP.COMPRESSED_TRANSFER_MODE);

You can also obviously compress the files on the server side then send them via standard FTP (it should be the same in the end).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Adding to a column letter excel Hi there I would like to merge seven cells together all the way across row 1.  Instead of clickng A1 pressing shift, then right arrow key six times I'm thinking I can achieve this via a macro.  I have written the following but am unsure how to add seven to the letter reference, especially once I get into the last seven ending on AA1, then it starts AA2 and continues on.  The following code achieves what I would like but how can I introduce variables and a loop to store the letters as int, add six, then cast back to string and continue to the next set? How would I write While (End of row has not been reached)
Range("A1:G1").Select
With Selection
    .HorizontalAlignment = xlGeneral
    .VerticalAlignment = xlBottom
    .WrapText = False
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .ReadingOrder = xlContext
    .MergeCells = True
End With

Range("H1:N1").Select
    With Selection
    .HorizontalAlignment = xlGeneral
    .VerticalAlignment = xlBottom
    .WrapText = False
    .Orientation = 0
    .AddIndent = False
    .IndentLevel = 0
    .ShrinkToFit = False
    .ReadingOrder = xlContext
    .MergeCells = True
End With

A: Is this what you are trying?
'R1 is the row of the first cell
'C1 is the column of the first cell
'R2 is the row of the second cell
'C2 is the column of the second cell

Sub Sample()
    Dim Rng As Range
    Dim ws As Worksheet
    Dim R1 As Long, C1 As Long
    Dim R2 As Long, C2 As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")

    R1 = 1: C1 = 1
    R2 = 1: C2 = C1 + 6

    With ws
        Set Rng = .Range(.Cells(R1, C1), .Cells(R2, C2))
        Application.DisplayAlerts = False
        Rng.Merge
        Application.DisplayAlerts = True
    End With
End Sub

EDIT: You might also find THIS link interesting.


text:
Q: python3 exception invalid syntax error I recently started learning python3, and I am trying to write an exception.
I have this line, which is a list of words.
I want to match the word create to the list, sometimes it's there sometimes its not. When it's not there I get this error:
Traceback (most recent call last):
File "sub_process.py", line 17, in <module>
if (line.index("create")):
ValueError: 'create' is not in list

and I am fine with that. This is expected. So I thought if I wrote an exception to it the script could just continue on and keep doing stuff. So I an exception below and all its suppose to do is nothing. Catch the error and continue on.
line = line.split()

if line.index("create"):
    print("basd");
except ValueError:
    print("123");

But everytime i try to compile this I get syntax error at "except" and I am not sure why. It looks perfectly normal compared against all the tutorials that I could find.

A: Rather than using index, you should just be using the in operator, which returns a simple boolean:
if "create" in line:
    print("basd")
else:
    print("123")

This will not raise an exception so there is no need for try/except.

A: You need to add try before the if statement:
line = line.split()
try: # added 'try'
    if line.index("create"):
        print("basd");
except ValueError:
    print("123");

Also note, you don't need the semicolons at the end of statements, and it is generally frowned upon when they are used in that way.
As an alterintave to @Rosemans solution, you can do that all on one line:
print('basd') if "create" in line else print("123")

A: if/except is not a valid construct. Use try/except:
line = line.split()

try:
    if line.index('create'):
        print('basd')

except ValueError:
    print("123")

Alternatively, you could avoid the exception and the try/except altogether:
line = line.split()

if 'create' in line:
    print('basd')

else:
    print("123")

A: #use try block..
line = line.split()
try:
    if line.index("create"):
        print("basd")
except ValueError:
    print("123")


text:
Q: SQL variables in query cause unexpected SQL syntax error There is a database that holds music - artists, albums and tracks. Each album has several tracks, each track has it's own track_number inside the album.
I try to execute an SQL request that shifts one track number up (for example, track#4 will be track#3) and at the same time shifts another track number down (ex-track#3 should become track#4). SQL code works perfectly while being run in MySQL Workbench or SQL sandbox but it causes an error while being launched via JDBC.
Replacing IF with standart CASE/WHEN/THEN doesn't help a bit.
Replacing prepared statement with ordinary statement does not do anything good as well.
SELECT @current_number := track_number, @current_album := album FROM audio_tracks WHERE id = 4;

UPDATE audio_tracks
    SET track_number = IF(track_number = @current_number - 1, @current_number, @current_number - 1)
    WHERE @current_number > 1
        AND track_number IN (@current_number - 1, @current_number)
        AND album = @current_album;

public void processCustomRequest(String sql) throws DaoException
{
    Statement statement = null;
    try
    {
        statement = connection.createStatement();
        statement.execute(sql);
    } catch (SQLException ex)
    {
        throw new DaoException("Failed to execute custom SQL request", ex);
    } finally
    {
        try
        {
            if (statement != null)
            {
                statement.close();
            }
        } catch (SQLException ex)
        {
            LOGGER.error("Failed to close statement", ex);
        }
    }
}

Instead of expected shifts I got this:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE audio_tracks SET track_number = IF(track_number = @current_number - 1, @c' at line 1
So... Any ideas how to fix this problem?
Again, here is the sandbox that shows how my table looks and how my request works perfectly. In theory.

A: Try printing the SQL string passed to function and check for the syntax error before execution.
Also use statement.executeUpdate(sql) instead of statement.execute(sql) function.


text:
Q: rewriting a pseudo element horiz. to vertical I have code which creates an element at the bottom of a div to act as an 'arrow/pointer' pointing down.
I need it written so that the 'arrow/pointer' points to the left
curent code  -
HTML

mask css is in fiddle
https://jsfiddle.net/hunt0194/gu1sgotd/
I've tried changing 'bottom' values to 'left' values, etc. But can't get it to work
code creates the two black shapes which act as 'masking' out the bottom of the div

A: go here css-triangle-generator , generate your own triangle css.  It is a lot easier than the code you are currently using.
using
border-width: 100px 100px 100px 0;
border-color: transparent red transparent transparent;

will create the desired triangle effect, you can play around with the page and get it just right

A: Try adding at .indx-img
transform:rotate(90deg);

at .mask
left: 10%;

.indx-img {
  position: relative;
  padding: 16% 0;
  background-color: red;
  transform: rotate(90deg);
}
.mask:before {
  border-left: 0 none;
  border-right: 20px solid transparent;
  left: 0;
}
.mask:after {
  border-left: 20px solid transparent;
  border-right: 0 none;
  right: 0;
}
.mask:before,
.mask:after {
  border-bottom: 20px solid #fff;
  content: " ";
  display: block;
  height: 0;
  position: absolute;
  top: 0;
  width: 50%;
  box-sizing: border-box;
}
.mask {
  bottom: 0px;
  height: 20px;
  left: 10%;
  position: absolute;
  width: 100%;
  z-index: 1000;
}

jsfiddle https://jsfiddle.net/gu1sgotd/4/

A:

body {
  margin-right: 50px;
  margin-left: 50px;
}
.arrow_box {
  position: relative;
  background: #FF0000;
  border: 4px solid #FF0000;
  height:150px;
}
.arrow_box:after,
.arrow_box:before {
  right: 100%;
  top: 50%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}
.arrow_box:after {
  border-color: rgba(255, 0, 0, 0);
  border-right-color: #FF0000;
  border-width: 30px;
  margin-top: -30px;
}
.arrow_box:before {
  border-color: rgba(255, 0, 0, 0);
  border-right-color: #FF0000;
  border-width: 36px;
  margin-top: -36px;
}

Made using CSS ARROW PLEASE!


text:
Q: How to import requirements.txt from an existing project using Poetry I am trying out Poetry in an existing project. It used pyenv and virtual env originally so I have a requirements.txt file with the project's dependencies.
I want to import the requirements.txt file using Poetry, so that I can load the dependencies for the first time. I've looked through poetry's documentation, but I haven't found a way to do this. Could you help me?
I know that I can add all packages manually, but I was hoping for a more automated process, because there are a lot of packages...

A: I appreciate this might be a bit late but you can just use
poetry add $( cat requirements.txt )

A: Just use the plain requirements.txt and filter out version numbers with awk:
awk -F '==' '{print $1}' requirements.txt | xargs -n1 poetry add

-F specifies a filter or split point. $1 is the first argument in the split. The input file comes as last argument. Afterwards you can pipe it to poetry add using xargs -n 1 to call poetry add with each line consecutively and not with a space separated string at once. If you want to consume all entries at once just ommit -n 1. Also make sure that a poetry environment is already present.
To just consume the requirements.txt omit the filter and use
awk '{print $1}' requirements.txt | xargs -n1 poetry add

But other tools like cat are fine for that case as well.

A: A one-liner for Windows PowerShell users:
    @(cat requirements.txt) | %{&poetry add $_}

For more about piping arguments with PowerShell see this useful answer.

A: The best method I've found is this one:
$ for item in $(cat requirements.txt); do poetry add "${item}"; done

A: Here's one that works if you have # comments (at the start of a line or at the end of a line) in your requirements file:
poetry add $(sed -e 's/#.*//' -e '/^$/ d' < requirements.txt)

https://www.grymoire.com/Unix/Sed.html#uh-30

A: I don't have enough reputation to comment but an enhancement to @Liang's answer is to omit the echo and call poetry itself.
cat requirements.txt | grep -E '^[^# ]' | cut -d= -f1 | xargs -n 1 poetry add
In my case, this successfully added packages to the pyproject.toml file.
For reference this is a snippet of my requirements.txt file:
pytz==2020.1  # https://github.com/stub42/pytz
python-slugify==4.0.1  # https://github.com/un33k/python-slugify
Pillow==7.2.0  # https://github.com/python-pillow/Pillow

and when calling cat requirements.txt | grep -E '^[^# ]' | cut -d= -f1 (note the omission of xargs -n 1 poetry add for demonstration) it will output the following:
pytz
python-slugify
Pillow
# NOTE: this will install the latest package - you may or may not want this.

Adding dev dependencies is as simple as adding the -D or --dev argument.
# dev dependancies example
cat requirements-dev.txt | grep -E '^[^# ]' | cut -d= -f1 | xargs -n 1 poetry add -D

Lastly, if your dev requirements install from a parent requirements file, for example:
-r base.txt

package1
package2

Then this will generate errors when poetry runs, however, it will continue past the -r base.txt line and install the packages as expected.
Tested on Linux manjaro with poetry installed as instructed here.

A: For Powershell:
$reqs = @(cat requirements.txt)
for($i = 0; $i -lt $reqs.length; $i++){poetry add $reqs[i]}

Note this won't ignore comments or anything else in the requirements file. This is strictly taking it as raw text so it expects every line to be a package.

A: I found none of these answers sufficed so I created one of my own:
https://github.com/src-r-r/python-stanza
It's a new baby, so contributions welcome, but so far it's very cookiecutter-friendly:

*

*automatically detects a setup.py and fetches project info

*allows multiple requirements.txt files to be specified for either dev dependencies or normal dependencies

*allows the name and version to be overwritten.

*also adds referenced requirements (e.g. -r ./special-requirements.txt) if it's included in a requirements file.

A: I made a tool poetry-add-requirements.txt just for this. Code
Install it with pipx install poetry-add-requirements.txt,
then run poeareq.
Usage
Run poetry-add-requirements.txt, optionally specify your requirements.txt files and --dev for dev dependencies.
poeareq is provided is an alias to poetry-add-requirements.txt.
$ poeareq --help

usage: poeareq [-h] [-D] [requirements.txt files ...]

Add dependencies specified in requirements.txt to your Poetry project

positional arguments:
  requirements.txt file(s)
                        Path(s) to your requirements.txt file(s) (default: requirements.txt)

options:
  -h, --help            show this help message and exit
  -D, --dev             Add to development dependencies (default: False)

Features

*

*Auto detect charset of requirements.txt file(s) and feed normalized dependency specs to poetry.

*Stop on first poetry add error.

A: poetry doesn't support this directly. But if you have a handmade list of required packages (at best without any version numbers), that only contain the main dependencies and not the dependencies of a dependency you could do this:
$ cat requirements.txt | xargs poetry add

A: One liner:
cat requirements.txt | grep -E '^[^# ]' | cut -d= -f1 | xargs -n 1 poetry add


text:
Q: Google Sheets API v4 service_account - forbidden: The caller does not have permission (Google::Apis::ClientError) Ruby: 2.3.1
Rails: 5.0.0
I need to access and update my private Google Sheet through Google Sheets API.
Eventually this shall be done by a recurring background job in my Rails application. Hence I have setup a service account in my Google Cloud Console.
But to start playing with Google Sheets API I have created a script:
require 'google/apis/sheets_v4'

ENV["GOOGLE_ACCOUNT_TYPE"] = 'service_account'
ENV["GOOGLE_CLIENT_EMAIL"] = '<client_email_from_downloaded_json_here>'
ENV["GOOGLE_PRIVATE_KEY"] = "<private_key_from_downloaded_json_here>"

SCOPE = Google::Apis::SheetsV4::AUTH_SPREADSHEETS

authorization = Google::Auth.get_application_default(SCOPE)

# Initialize the API
service = Google::Apis::SheetsV4::SheetsService.new
service.authorization = authorization

spreadsheet_id = '<MY SPREADSHEET ID HERE>'

sheet_name = 'Sheet1'

range = "#{sheet_name}!A2:B"

response = service.get_spreadsheet_values(spreadsheet_id, range)

puts 'No data found.' if response.values.empty?

response.values.each do |row|
  # Print columns A and B, which correspond to indices 0 and 1.
  puts "#{row[0]}, #{row[1]}"
end

When I run that script
$ rails runner -e development lib/scripts/google_sheets_api_demo.rb
/home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/google-api-client-0.9.12/lib/google/apis/core/http_command.rb:211:in `check_status': forbidden: The caller does not have permission (Google::Apis::ClientError)
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/google-api-client-0.9.12/lib/google/apis/core/api_command.rb:102:in `check_status'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/google-api-client-0.9.12/lib/google/apis/core/http_command.rb:179:in `process_response'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/google-api-client-0.9.12/lib/google/apis/core/http_command.rb:286:in `execute_once'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/google-api-client-0.9.12/lib/google/apis/core/http_command.rb:107:in `block (2 levels) in execute'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/retriable-2.1.0/lib/retriable.rb:54:in `block in retriable'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/retriable-2.1.0/lib/retriable.rb:48:in `times'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/retriable-2.1.0/lib/retriable.rb:48:in `retriable'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/google-api-client-0.9.12/lib/google/apis/core/http_command.rb:104:in `block in execute'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/retriable-2.1.0/lib/retriable.rb:54:in `block in retriable'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/retriable-2.1.0/lib/retriable.rb:48:in `times'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/retriable-2.1.0/lib/retriable.rb:48:in `retriable'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/google-api-client-0.9.12/lib/google/apis/core/http_command.rb:96:in `execute'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/google-api-client-0.9.12/lib/google/apis/core/base_service.rb:346:in `execute_or_queue_command'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/google-api-client-0.9.12/generated/google/apis/sheets_v4/service.rb:322:in `get_spreadsheet_values'
  from lib/scripts/google_sheets_api_demo.rb:35:in `<top (required)>'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/railties-5.0.0/lib/rails/commands/runner.rb:60:in `load'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/railties-5.0.0/lib/rails/commands/runner.rb:60:in `<top (required)>'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/railties-5.0.0/lib/rails/commands/commands_tasks.rb:138:in `require'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/railties-5.0.0/lib/rails/commands/commands_tasks.rb:138:in `require_command!'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/railties-5.0.0/lib/rails/commands/commands_tasks.rb:104:in `runner'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/railties-5.0.0/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
  from /home/jignesh/.rvm/gems/ruby-2.3.1@my_integrations/gems/railties-5.0.0/lib/rails/commands.rb:18:in `<top (required)>'
  from bin/rails:9:in `require'
  from bin/rails:9:in `<main>'

If I try to access a public sheet it works. I have tried a lot but unable to figure out what is causing this. Initially I used API Key approach for authorization but as per the documentation found at https://developers.google.com/api-client-library/ruby/auth/api-keys it says

When calling APIs that do not access private user data, you can use
  simple API keys. These keys are used to authenticate your application
  for accounting purposes. The Google Developers Console documentation
  also describes API keys.
Note: If you do need to access private user data, you must use OAuth
  2.0. See Using OAuth 2.0 for Web Server Applications, Using OAuth 2.0 for Installed Applications, and Using OAuth 2.0 for Server to Server
  Applications for more information.

Hence I switched to Service Account approach. But it didn't helped.
Can anybody please let me know what is it I am missing?
Additional Findings:
The following post https://stackoverflow.com/a/38530755/936494 looks helpful but as per my requirement I want to avoid 3-Legged oauth the reason being the sheet is supposed to be accessed and updated through a background-job.

A: This is resolved. Thanks to Steve Bazyl (Google member) who provided the following valuable suggestion which straight-away resolved the problem:

Did you share the sheet with the service account? Service accounts are effectively separate users and need to be on the ACLs the same as any other user.

Reference: https://github.com/google/google-api-ruby-client/issues/461#issuecomment-243328234


text:
Q: sqlplus is not working Thanks for reading!
Today i had a very strange issue.
Because my docker app just broken.. I never touched any file, just execute sqlplus, used it, then shut my Host OS.
So i tried to fix this issue. Here is a error.
[oracle@7e421c70357d ~]$ lsnrctl status

LSNRCTL for Linux: Version 12.1.0.2.0 - Production on 02-NOV-2017 16:31:09

Copyright (c) 1991, 2016, Oracle.  All rights reserved.

Connecting to (ADDRESS=(PROTOCOL=tcp)(HOST=)(PORT=1521))
TNS-12541: TNS:no listener
 TNS-12560: TNS:protocol adapter error
  TNS-00511: No listener
   Linux Error: 111: Connection refused
[oracle@7e421c70357d ~]$ sqlplus
Error 6 initializing SQL*Plus
SP2-0667: Message file sp1<lang>.msb not found
SP2-0750: You may need to set ORACLE_HOME to your Oracle software directory
[oracle@7e421c70357d ~]$

So i check everything as i can.ORACLE_HOME is correct.
ORACLE_HOME is /u01/app/oracle/product/12.1.0/dbhome_1.
And there are lots of files and directories, so correct. Checked twice.
And i realize that there is no sqlplus folder in ORACLE_HOME.
I think sqlplus just gone, totally missing..
I don't know why this happened, no clue.
Edited..
I googled anything about my issue and i got this.
Directory: /var/log/oracle-rdbms-server-12cR1-preinstall/results
[root@7e421c70357d results]# ls
orakernel.log
[root@7e421c70357d results]# cat *
Adding group oinstall with gid 54321
Adding group dba
Adding user oracle with user id 54321, initial login group oinstall, supplementary group dba and  home directory /home/oracle
Changing ownership of /home/oracle to oracle:oinstall
Please set password for oracle user
uid=54321(oracle) gid=54321(oinstall) groups=54321(oinstall),54322(dba)
Creating oracle user passed

Saving a copy of the initial sysctl.conf
Verifying  kernel parameters as per Oracle recommendations...
Adding fs.file-max = 6815744
Adding kernel.sem = 250 32000 100 128
Adding kernel.shmmni = 4096
Adding kernel.shmall = 1073741824
Adding kernel.shmmax = 4398046511104
Adding kernel.panic_on_oops = 1
Adding net.core.rmem_default = 262144
Adding net.core.rmem_max = 4194304
Adding net.core.wmem_default = 262144
Adding net.core.wmem_max = 1048576
Adding net.ipv4.conf.all.rp_filter = 2
Adding net.ipv4.conf.default.rp_filter = 2
Adding fs.aio-max-nr = 1048576
Adding net.ipv4.ip_local_port_range = 9000 65500
Setting kernel parameters as per oracle recommendations...
Altered file /etc/sysctl.conf
Saved a copy of the current file in /etc/sysctl.d/99-oracle-rdbms-server-12cR1-preinstall-sysctl.conf
Check /etc/sysctl.d for backups
Verifying & setting of kernel parameters passed

Setting user limits using /etc/security/limits.d/oracle-rdbms-server-12cR1-preinstall.conf

Verifying oracle user OS limits as per Oracle recommendations...
Adding oracle soft nofile  1024
Adding oracle hard nofile  65536
Adding oracle soft nproc  16384
Adding oracle hard nproc  16384
Adding oracle soft stack  10240
Adding oracle hard stack  32768
Adding oracle hard memlock  134217728
Adding oracle soft memlock  134217728
Setting oracle user OS limits as per Oracle recommendations...
Altered file /etc/security/limits.d/oracle-rdbms-server-12cR1-preinstall.conf
Original file backed up at /var/log/oracle-rdbms-server-12cR1-preinstall/backup/Jun-01-2017-23-10-04
Verifying & setting of user limits passed

/boot/grub/grub.conf not present.. ..
Verifying of boot parameters failed.

Trying to add NOZEROCONF parameter...
Taking a backup of existing file to /etc/sysconfig/network.orabackup
Successfully added parameter NOZEROCONF to /etc/sysconfig/network
Setting /etc/sysconfig/network parameters passed

Disabling Transparent Hugepages.
Refer Oracle Note:1557478.1

Disabling defrag.
Refer Oracle Note:1557478.1

Taking a backup of old config files under /var/log/oracle-rdbms-server-12cR1-preinstall/backup/Jun-01-2017-23-10-04
Trying to add NOZEROCONF parameter...
Parameter added by previous preinstall rpm
Parameter already present
/boot/grub/grub.conf not present.. ..
Boot file modifications failed

Anyone have an idea to solve this issue, Please give me a hand.

A: Use this command to find sqlplus. sqlplus is a binary command and it is always in a ../bin directory
$which sqlplus
Usually by default they are located over at this directory:
~/app/oracle/product/your_db_version/dbhome_1/bin/sqlplus
Go to that directory and make sure it has executable permission with something like this if it is there or not missing:
$cd ~/app/oracle/product/your_db_version/dbhome_1/bin/
$ls -la sqlplus
-rwxr-x--x. 1 oracle mygroup 9479 Mar 16  2015 sqlplus
Run this to be sure:
$sudo chmod 755 sqlplus
It is similar to 'sudo chmod u=rwx,go=rx'
Use this command to check your environment setting.
$echo PATH
Make sure you have something like this
/home/oracle/bin:/home/oracle/app/oracle/product/your_db_version/dbhome_1/bin
Add them to your environment if they are not listed.
$sudo vi ~/.bashrc
or
$sudo vi /etc/profile
I am hoping this will help. Good luck!


text:
Q: How do I alternate every second and third background of a list/row? I've seen plenty of posts on how to alternate the background color of a list or row.
$('#news tbody').each(function() {
    $(this).children('tr:odd').addClass('alt');
});

I get it. But what if I wanted to have an alternating background for three rows. In other words the first one would have one color, the second another color, the third another color and then repeat. I've only been able to successfully add a background color to every third without overlap. Any suggestions?

A: You can do this in pure CSS using the nth-child selector:
#news tbody tr:nth-child(3n+1) {
    background-color: #C00;
}

#news tbody tr:nth-child(3n+2) {
    background-color: #0C0;
}

#news tbody tr:nth-child(3n+3) {
    background-color: #00C;
}

Alternatively you can achieve this in jQuery using an array and the modulo operator:
var classes = ['first', 'second', 'third'];
$('#news tbody tr').each(function(i) {
   $(this).addClass(classes[i % classes.length]);
});

A: You can use just :nth-child in your CSS, no JavaScript needed.
http://www.quirksmode.org/css/selectors/nthchild.html

A: Use the pseudo class :nth-of-type
So for example, you could use
tr:nth-of-type(2)
{
background-color: red;
}

That will change the second row to red.  But you could use a formula with n to get rows repeating, so for instance nth-of-type(3n+2) would give you the 2nd row (n = 0), then the fifth row (n = 1), then the eighth row (n = 2) and so on.  Once you get your formulas just right, you can play with rows however you like.
If you also want the first row to be different (i.e. headers), just use (1).


text:
Q: How to extend a sass/compass library My main goal is to add to this compass built-in mixin sprite-position:
@mixin sprite-position($col, $row: 1, $width: $sprite-image-default-width, $height: $sprite-image-default-height, $margin: $sprite-default-margin) {
  $x: ($col - 1) * -$width - ($col - 1) * $margin;
  $y: ($row - 1) * -$height - ($row - 1) * $margin;
  background-position: $x $y;
}

and to add this retina mixin sprite-position-retina:
@mixin sprite-position-retina($col, $row: 1, $width: $sprite-image-default-width, $height: $sprite-image-default-height, $margin: $sprite-default-margin) {
  ...
  background-position: $x/2 $y/2;
}

Eventually I want to replace this line of code in my file (this line is working):
    background-position: sprite-position($sprites2x, $name);

With this line (this line is not working):
    background-position: sprite-position-retina($sprites2x, $name);

The problem is that it doesn't even recognise sprite-position-retina ad a mixing and if I add @include to that line it doesn't recognise any of the variables and constants (as if the parameter I am passing are not the right ones)
My questions are:

*

*Where should I add my new mixin? (Adding it to the built in file _sprite-img.scss seems like wrong practice because I don't want to change compass' inner files). Adding it to my files doesn't seem to make it work.

*Why isn't it working? How can I make it work?

Project is built with grunt/bower/yo etc..

A: I found a nice workaround for this problem:
I'm using this simple mixin to get the new sprite position:
/* Converts sprite position to half of its original size (since we're 'squizing' the retina image by 2)*/
@mixin sprite-position-retina($spriteUrl, $name) {
  $spriteData: sprite-position($spriteUrl, $name);
  $x: nth($spriteData,1)/2;
  $y: nth($spriteData,2)/2;
  background-position: $x $y;
}


text:
Q: how to call range::-webkit-slider-runnable-track? Basically I need to call .range::-webkit-slider-runnable-track using either jquery or javascript so I can make some changes over to it's background and do other implementations over it.
To be precise I am currently using
$('<style>.myrange::-webkit-slider-runnable-track{background:linear-gradient(to right, white'+val+'%, #bbb '+val+'%);}</style>').appendTo('head');

This works pretty much fine, but the problem is that I'm calling .myrange::-webkit-slider-runnable-track like couple of thousands of times which every time it appends to head my range gets to face some performance issue and so.
I would really appreciate if some one tell how to do this with something like $('.myrange::-webkit-slider-runnable-track').css("background", "black");
Question Update:
<input type="range" value="0" min="0" max="100" id="myrange" class="myrange"/>

This range has connected to a video which track the video duration and changes the color of the track up to the point that the video has been watched.
And to do the coloring of the range tracker this is what I am doing:
vid.addEventListener('progress', function() {
    var range = 0;
    var bf = this.buffered;
    var time = this.currentTime;

    while(!(bf.start(range) <= time && time <= bf.end(range))) {
        range += 1;
    }
    var loadStartPercentage = bf.start(range) / this.duration;
    var loadEndPercentage = bf.end(range) / this.duration;
   var loadPercentage = loadEndPercentage -      loadStartPercentage;

   val = loadPercentage*100;
   thmpos = $('.vidskb_r').val();
   var style = $("<style>", {type:"text/css"}).appendTo("head");
   style.text('.vidskb_r::-webkit-slider-runnable-track{background:linear-gradient(to right, #ff7e20 '+thmpos+'%, #fff '+thmpos+'%, #fff '+val+'%, #bbb '+val+'%);}');

});

Thanks in advance:)

A: Append css text to a single <style> element, substitute .text() for .append()
Note, you do not need to create a new <style> element at each iteration of a loop or event handler. Create <style> element once outside of loop or event handler and use a variable to reference the single <style> element within loop or event handler.
// create and append `<style>` element to `<head>` once, here
// before attaching `progress` event to `vid`, and outside
// of `progress` event handler
var style = $("<style>", {type:"text/css"}).appendTo("head");

vid.addEventListener('progress', function() {
    var range = 0;
    var bf = this.buffered;
    var time = this.currentTime;

    while(!(bf.start(range) <= time && time <= bf.end(range))) {
        range += 1;
    }
    var loadStartPercentage = bf.start(range) / this.duration;
    var loadEndPercentage = bf.end(range) / this.duration;
   var loadPercentage = loadEndPercentage -      loadStartPercentage;

   val = loadPercentage*100;
   thmpos = $('.vidskb_r').val();

   style.text('.vidskb_r::-webkit-slider-runnable-track{background:linear-gradient(to right, #ff7e20 '+thmpos+'%, #fff '+thmpos+'%, #fff '+val+'%, #bbb '+val+'%);}');

});


text:
Q: Downsized images in fabricjs are pixelated When I load an image like the one I've included to say 400 dpi high it becomes very pixelated.  I've looked around and nothing seems to work.  I have a collection of images that a user could put on the canvas and the images are re-sized depending on a scale so I can't re-size them ahead of time.
Any help would be greatly appreciated.
Thanks
Jody
http://rockofagescanada.com/test33_6287.png

A: As of version 1.4.13 FabricJs support image resize filters.
The resize filter can be used in 2 ways:

-Static resize on load with fixed scale
-Dynamic resize on scaling the image object by code o by mouse drags.

There are 4 filters implemented as of now:

-SliceHack , not really a filter but an hack to get smoother resize by resizing 0.5 the image multiple times.
-Hermite filter
-Bilinear filtering
-Lanczos resizing with lobes parameter

Here follow some examples:

*

*Static resize at load with Hermite filter, fixed scale
var theImage = new fabric.Image(imag, {
    top: 0,
    left: 0
});
theImage.filters.push(
               new fabric.Image.filters.Resize({
                        resizeType: 'hermite',
                        scaleX: 0.1,
                        scaleY: 0.1
                       })
                     );
theImage.applyFilters();
canvas.add(theImage);

*Dynamic resize with Lanczos filter, 2 lobes
var theImage = new fabric.Image(imag, {
    top: 0,
    left: 0
});
theImage.resizeFilters.push(new fabric.Image.filters.Resize({
    resizeType: 'lanczos', // typo fixed
    lanczosLobes: 2 // typo fixed
}));
canvas.add(theImage);

A: If you want to set the width to 1500, then below code can be used for rezise. It worked for me. Image looks normal.
var scale = 1500 / oImg.getWidth();

var newWidth = oImg.getWidth() * scale;
var newHeight = oImg.getHeight() * scale;

oImg.set({width : newWidth, height : newHeight});


text:
Q: .htacess rewrite from folder breaks the website I am trying to make a rewrite rule so if a visitor types:
https://mywebsite.com/app/invite/abc123
it gets parsed as:
https://mywebsite/invite.php?id=abc123
using the following code:
RewriteRule ^app/invite/(.+)$ /app/invite.php?id=$1

The issue is that all relative links break after rewriting, as the invite is not a real existing directory and it is added to all relative links.
How can I fix this or prevent adding the invite directory to links?

I wanted to point out that I use the following rules in my .htaccess file.
RewriteEngine On

# Redirect http  to https
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# Redirect www to non-www
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# Remove php file extension from links
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php

I am trying to adjust all they do not result in infinite redirects or interval server errors.
I use Apache/2.4.46.

A: I finally managed to solve this issue by using this code:
RewriteRule "^app/invite/([0-9a-zA-Z]+)" "/app/invite?id=$1" [NC,L,QSA]

and in the invite.php I set the base in the <head> tag to:
<base href="../">

So it jump back to the actual directory and don't break the website links.
If any one has a better approach, I will be delighted if they share with me.
Cheers!


text:
Q: How do I connect my MS Access database to the LAN? I wrote a database program in MS Access a couple of years ago, and it is used to keep track of some personal stuffs. I now want to expand this personal project and allow several computers to have access to this database. Assuming that all I am interested in connecting to are my home computers, i.e. all connected to the same router (same LAN), what are the basic steps I need to do this?
Also, I am very new to database, but I happened to know how to write VBA on MS Access. Is there any tutorial that can help on what I do?
Thanks!

A: There is nothing magical about this.  Just put the Access database file in a file share on your LAN and let people access it from whatever computer they are using.
If you will need to be sure to open the database in shared mode.  Go to the options, select client settings, advanced, and set the default open mode to "shared".  (Depending on your version of access, the way to get to this setting may vary.)
You can do something more elaborate, like segregating your data and your GUI and joining the front end databases to the back end with linked tables, but that may well be overkill.


text:
Q: GMail: Count searched hits I have a problem with the GmailApp search(query) function.
According to the manual it uses Gmail queries, so all the arguments should be accessible and return correct results.

var bigThreads = GmailApp.search('in:chats newer_than:1d');
Logger.log(bigThreads.length);

When I take the filter on the eMail-search-field I get 6 line back. In the log I see the count 2.
Does anyone have a idea - where my fault is?


text:
Q: Get first col in matrix I have simple program that gets the sum of main and anti diagonals of a matrix. And then it get the sum of first and last column of a matrix.For example:
1 2 3
4 5 6  --> The matrix
7 8 9

md = 1 + 5 + 9 = 15
ad = 7 + 5 + 3 = 15
lastCol = 3 + 6 + 9 = 18
firstCol = 1 + 4 + 7 = 12

How can i get the sum of the firstCol of a square matrix ? Here is my code:
int main(){
    int n;
        scanf("%d",&n);
        int i,j,a[n][n],firstCol=0,lastCol=0,md=0,ad=0;
        for(i = 0;i <n;i++){
            for(j=0;j<n;j++){
                scanf("%d",&a[i][j]);
            }
        }
        for(i = 0;i <n;i++){
            for(j=0;j<n;j++){
                if(i==j){
                    md+=a[i][j];
                }
                if(i+j==n-1){
                    ad+=a[i][j];
                }
            }
        }
        for(i=0;i<n;i++){
                lastCol+=a[i][n-1];
        }
}

A: for (i = 0; i < n; i ++) {
    firstCol += a[i][0];
}

A: Use functions. Try to make them a bit more universal. This one will return sum of the first column of any size array.
long long int sumFirstCol(size_t rows, size_t cols, int (*array)[cols])
{
    long long int result = 0;
    if(array && rows && cols)
    {
        for(size_t row = 0; row < rows; row++)
        {
            result += array[row][0];
        }
    }
    return result;
}

int main(void)
{
    int matrix[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9},};

    printf("%lld\n", sumFirstCol(3, 3, matrix));
}


text:
Q: ASP.NET 5 add app as IIS application I'm in the process of migrating some applications from ASP.NET 5 beta7 to RC1.  Using HTTPPlatformHandler I am able to run any of these ASP.NET 5 RC1 applications as the root of an IIS site.  But they will not run as a subdir (right-click 'add application') of the site.  The full response shows:
HTTP/1.1 404 Not Found
Content-Length: 0
Server: Kestrel
X-Powered-By: ASP.NET
Date: Tue, 24 Nov 2015 14:59:04 GMT

It isn't a permissions issue, as the route is served successfully when the app is the root of the site and using the same app pool.
The app pool is configured for 'no managed code' and integrated pipeline.
The web.config for the root application looks like this:
<configuration>
  <system.webServer>
    <handlers>
      <add name="httpplatformhandler" path="*" verb="*" modules="httpPlatformHandler" resourceType="Unspecified" />
    </handlers>
    <httpPlatform processPath="..\approot\web.cmd" arguments="" stdoutLogEnabled="false" stdoutLogFile="..\logs\stdout.log" startupTimeLimit="3600"></httpPlatform>
  </system.webServer>
</configuration>

For the sub application I've had to remove the httpplatformhandler handler to avoid the error "Cannot add duplicate collection entry of type 'add' with unique key attribute 'name' set to 'httpplatformhandler'".
Now that we have to use kestrel/httpplatformhandler, is it possible to run as an application under a site?

A: This problem started with beta8 and is still an open issue in RC1.  See ASP.NET IIS Integration issue #14.  "That fix is coming." says @davidfowl. "This is a workaround until the fix is available. We're working with the httpPlatformHandler team to fix bugs found in beta8 and rc1."
The workaround is to map the IIS app path in Startup.Configure like this:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.Map("/MyAppPath", (myAppPath) => this.ConfigureMyAppPath(myAppPath, env));
}

public void ConfigureMyAppPath(IApplicationBuilder app, IHostingEnvironment env)
{
    // the actual Configure code
}


text:
Q: Meu formulario de contato esta chegando no email de destino como "undefined" estava funcionando tudo perfeitamente, porém, quando preencho as informações do formulário e clico em enviar, no e-mail chega assim:
Nome: undefined
Email: undefined
Mensagem: undefined
Alguém pode me ajudar por favor, segue abaixo meu código html e php:
PHP
<?php
$errorMSG = "";

if (empty($_POST["name"])) {
    $errorMSG = "Name is required ";
} else {
    $name = $_POST["name"];
}

if (empty($_POST["email"])) {
    $errorMSG = "Email is required ";
} else {
    $email = $_POST["email"];
}

if (empty($_POST["message"])) {
    $errorMSG = "Message is required ";
} else {
    $message = $_POST["message"];
}

if (empty($_POST["terms"])) {
    $errorMSG = "Terms is required ";
} else {
    $terms = $_POST["terms"];
}

$to = "contato@supremotec.com.br";
$subject = "Contato - Supremotec Tecnologia";
$body = "Nome: " . $name . "\n" . "Email: " . $email . "\n" . "Mensagem: " . $message;

// prepare email body text $Body = ""; $Body .= "Name: "; $Body .= $name; $Body .= "\n"; $Body .= "Email: "; $Body .= $email; $Body .= "\n"; $Body .= "Menssagem: "; $Body .= $message; $Body .= "\n";

// send email

$header = "From:comercial@supremotec.com.br" . "\r\n" . "Reply-To:" . $email . "\e\n" . "X=Mailer:PHP/" . phpversion(); {

    if (mail($to, $subject, $body, $header)) {

        echo ("Email enviado com sucesso!");
    } else {
        echo ("O email não pode ser enviado");
    }
}
?>

HTML
                <form id="contactForm" data-toggle="validator" data-focus="false">

                        <input type="text" class="form-control-input" id="name" required>
                        Nome

                        <input type="email" class="form-control-input" id="email" required>
                        Email

                        <textarea class="form-control-textarea" id="message" required></textarea>
                        Sua mensagem

                        <button type="submit" class="form-control-submit-button">ENVIAR MENSAGEM</button>

                </form>

Obs. Desde já agradeço a ajuda!

A: ATUALIZADO
Encontrei alguns erros no seu formulário.

*

*Está faltando o atributo name nos inputs do seu formulário hmtl.

*está faltando o atributo action no seu formulário com a rota para o arquivo php

*Está faltando o atributo method="post" no seu formulário.

<form id="contactForm" data-toggle="validator" data-focus="false" action="mail.php" method="POST">

            <input type="text" class="form-control-input" id="name" name="name" required>
            Nome

            <input type="email" class="form-control-input" id="email" name="email" required>
            Email

            <textarea class="form-control-textarea" id="message" name="message" required></textarea>
            Sua mensagem

            <button type="submit" class="form-control-submit-button">ENVIAR MENSAGEM</button>

    </form>


text:
Q: Storing user-generated text in database securely (Ruby/Rails) I'm trying to figure out a way to store user-generated text securely in a database (so that only the user is the one who can access his/her stored text). I could have Rails encrypt and decrypt the user's text entries using the user's password as the key, but if the user ever forgot their password there would be no way to ever decrypt their previous content/text (since the Rails app uses BCrypt to store only a hash of the password).
Does anyone know how that could be done? It looks like Dropbox does something like it: "All files stored on Dropbox servers are encrypted (AES-256) and are inaccessible without your account password." (http://www.dropbox.com/help/27) Yet they allow you to reset your password and I'm assuming they don't store your plain text password anywhere.
What am I missing? Any suggestions would be greatly appreciated. Thanks!

A: Logic dictates that are only two options:

*

*You encrypt using a key known to the server (user's key hash or some other identifier). Intruders can potentially read all the encrypted data, but the user can never lose the encryption token because it is on your server.

*You encrypt the data using a key known to the user only (e.g. his password). Then intruders will not be able to read encrypted data, but if the user loses his key, the data is as good as a pile of random bits.

It's clear that Dropbox has chosen (1) from the fact that they allow to reset your password.

A: Build on Gintautas' Option 1 with a two-prong encryption plan:

*

*Apply option 1, with a key that is known to the server, and

*Store the database on disk in an encrypted format with a key that is known only to the server.  E.g., in an encrypted volume.  When the server starts up, the key must be manually entered in order to access the database.

This "static security" provided by part 2 protects against an intruder in the system gaining access to the database files.  Maybe not 100% the exact security you're after, but getting closer.


text:
Q: Supported browser in Botframework using Bing speech I am using Bing for speech in botframework and when i deploy it the microphone is enabled only in Chrome and Edge, I read that its supported also in some other browser?

A: First, the error is triggered in this piece of the WebChat code (https://github.com/Microsoft/BotFramework-WebChat/blob/master/src/SpeechModule.ts#L117)
Then, I guess that there is a combination of things.
Based on this page, the browser compatibility is:

As you can read, it seems that recognition on Firefox Desktop is not yet available.
Also, this page shows speech (recognition and synthesis) support.
Then, not sure if the following will also apply to other browser, than Chrome, but maybe yes


text:
Q: Android Animation Alternatives I want to implement a news ticker in my application, with vertical and horizontal scrolling, as well as some alpha animations.
I need the animation to be unaffected by the rest of the application (GPU/hardware accelerated). Especially since the application will be run on a Google TV box, and the user is expected to be using D-Pad navigation which can cause animation to become choppy.
These appear to be my options (I need to support Honeycomb and above):

*

*Use the Android Animation classes

*

*Will the performance of this approach ever match using OpenGL?

*Is hardware acceleration possible, and reliable?

*Easiest to work with.

*OpenGL ES 2

*

*There appears to be a limit to the texture size of 2048.  If I have a headline longer than that

*RenderScript

*

*The documentation is sparse here.

In your opinion, what is the best solution?  What other solutions are there?

A: One pattern that's common is to enable hardware acceleration, animate, then disable it.  However, on the Intel based GoogleTV boxes there is a problem with text when you turn on Hardware Acceleration.  I haven't tried it on an ARM based Google TV yet.
I am by no means an OpenGL ES expert, but I am a huge fan and have seen some wonderful things done using it for Google TV.  That said, I think your understanding of OpenGL ES Textures is incorrect.  The size of the texture should have little bearing on the length of a headline.  I currently have an intern working on a bunch of OpenGL ES examples that we hope to publish by the end of August.
There is excellent sample code for working with RenderScript, even if the documentation is sparse.  However some developers haven't been able to integrate RenderScript w/ d-pad navigation.
My suggestion is to try your worst case senario using OpenGL ES as a very short program and see how it works.  It's likely to be the best solution.
I can imagine why your seeing choppiness on some GoogleTV animations, StateLists firing when D-Pading, but it's not an insolvable issue.


text:
Q: Split Java String with multiple occurence of special character I would like to do the following in Java, and I can't figure out how.
Suppose I have this variable:
String text = "test1;test2;test3;test4;";

I would like to create a variable splitText that has the following :
splitText[0] = test1
splitText[1] = test2
splitText[2] = test3
splitText[3] = test4

If I use the split method given in Java, I obtain:
splitText[0] = test1
splitText[1] = test2;test3;test4

How can I do this?

A: I disagree that split doesn't work:
String text = "test1;test2;test3;test4;";
String[] splitText = text.split(";");

System.out.println(Arrays.toString(splitText));

outputs
[test1, test2, test3, test4]

You probably used split(2) which tells Java to split the string into at most 2 parts.

A: String [] arr = text.split(";");

arr contains all elements in array form.


text:
Q: Linux drops redirected by OVS packets Colleagues,
I can't get working forwarding of redirected (externally) packets through Linux host. There is network model I'm experimenting with:
     +----+(enp2)   +----+   +----+
     | H2 +---------+ o- +---+ H3 | (192.0.2.153)
     +--+-+         | br |   +----+
        |(enp1)     +-+--+
        |             |
        |             |
        |             |
+-------+--------+  +-+--+
|   ovs i-br     +--+ R1 |
+-------+--------+  +----+
        |
        |
     +--+-+
     | H1 | (10.9.8.100)
     +----+

for traffic from H1 to H3 there is regular routing exists (through R1), but for some reasons I need to divert some kinds of the traffic through H2, using OVS rules for this. After I've added the rule:
ovs-ofctl add-flow i-br dl_type=0x0800,in_port=1,nw_proto=6,tp_dst=80,actions=output:4

I'm seeing incoming packets on enp1@H2:
15:21:51.596752 IP (tos 0x0, ttl 64, id 48926, offset 0, flags [DF], proto TCP (6), length 60)
    10.9.8.100.44444 > 192.0.2.153.http: Flags [S], cksum 0x5f93 (correct), seq 774826047, win 64860, options [mss 1410,sackOK,TS val 3466298181 ecr 0,nop,wscale 7], length 0

While forwarding on H2 is allowed (net.ipv4.ip_forward=1), rpf switched off (net.ipv4.conf.(default|all).rp_filter=0), pings from H2 to both sides are working, iptables FORWARD accepts everything and routing is configured:
10.9.8.0/24 dev enp1s0 proto kernel scope link src 10.9.8.135
192.0.2.0/24 dev enp2s0 proto kernel scope link src 192.0.2.135

I don't see these packets on egress on enp2@H2.
Any ideas why this can happen and what to troubleshoot in order to find the cause?
Thank you.

A: Solved. It is required to rewrite dst MAC address on OVS as well, so rule must be:
ovs-ofctl add-flow i-br dl_type=0x0800,in_port=1,nw_proto=6,tp_dst=80,actions=mod_dl_dst:xx:xx:xx:xx:xx:xx,output:4

where xx:xx:xx:xx:xx:xx is H2's mac address. This is because H1, when forming ethernet header of outgoing packet, set R1's dst mac (according to H1's routing table). After being redirected on OVS, this packet comes to H2 and the latter ignores it since it's destined to another host.


text:
Q: Copy a reference formula down to stay in line with updating data I have a macro and one of the columns it produces is a column of dates. I wish to use this excel formula
=IF(COUNTIF(Sheet2!A9:A102,K2)>0, K2,J1)

But have it copy down so it always goes as far as the column of dates do its left. Basically when a new date gets added, this formula will copy down another cell. I tried using this:
Range("J2:J" & LastRow).FormulaR1C1 = "=IF(COUNTIF(Sheet2!R[7]C[-9]:R[100]C[-9],RC[1])>0, RC[1],R[-1]C)"

But get "method 'range' of object '_global' failed.

A: This Works. The destination of lastrow was incorrect but this now tracks the data in the row to the left.
Range("J2:J" & (Range("I" & Rows.Count).End(xlUp).Row)).FormulaR1C1 = "=IF(COUNTIF(Sheet2!R[7]C[-9]:R[100]C[-9],RC[1])>0, RC[1],R[-1]C)"


text:
Q: Cannot find custom tool AGDataSetGenerator on this system I've inherited a legacy .Net 3.5 VB app to support from a client and they'd like to make some small data changes. Before we begin I think it's important to note that I am running Windows 7 64 bit, and VS 2013 Ultimate R2.
While making my first changes to the project, I noticed their datasets use a custom tool AGDataSetGenerator (written by Shawn Wildermuth in 2004). I did a lot of poking around on how to register custom tools. I went over to http://www.codeproject.com/Articles/8582/Inherit-from-ADO-NET-DataSet-to-create-your-own-bu and got the source code of the tool, inside the project there are a couple of utility files that you need to run in order to register the tool. Remember this was made in 2004 so things were a little different back then.
I modified the Reg.cmd file to point to v2.0.50727 since my project is running .Net 3.5 and  .Net 3.0 and 3.5 are both just minor updates from .Net 2.0 and not completely new .net versions. Also I noticed that there is both a Framework and a Framework64 folder with the C:\Windows\Microsoft.Net folder, so I added both locations to my .cmd file in hopes to cover all of my bases. Code Below
Reg.cmd - Original
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\regasm /codebase /verbose F:\AGDataSetGenerator.dll`

Reg.cmd - My Modified Version
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\regasm /codebase /verbose F:\AGDataSetGenerator.dll
C:\WINDOWS\Microsoft.NET\Framework64\v2.0.50727\regasm /codebase /verbose F:\AGDataSetGenerator.dll

Then it was on to the.reg file.
Upon opening the file my first thought was, cool, I can just switch the version from 7.1 to 12.0 and away we go. Not the case. After quite a bit of googling I found the first line registers the tool for VB.Net, and the second registry entry registers the tool for C#, so for me I only need the first line, also VS now a days registers to a new location HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\ for 64 bit specific registers. So in hopes to cover my bases once again, I tried including both 32 bit and 64 bit locations. I even threw in a more global register for both 32 and 64 bit that in hopes that would point visual studio to the generator entry, unfortunately I'm a bit out of my wheelhouse here so I was pretty much grabbing at straws.
BSDataSetGenerators.reg - Original
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.1\Generators\{164B10B9-B200-11D0-8C61-00A0C91E29D5}\AGDataSetGenerator]
@="ADOGuy DataSet Generator"
"CLSID"="{87BF1B1C-E1DF-4f24-A07E-2BD9B8CAD316}"
"GeneratesDesignTimeSource"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\7.1\Generators\{FAE04EC1-301F-11d3-BF4B-00C04F79EFBC}\AGDataSetGenerator]
@="ADOGuy DataSet Generator"
"CLSID"="{3C13044D-394D-45cd-89FF-51C885BFBCD9}"
"GeneratesDesignTimeSource"=dword:00000001

BSDataSetGenerators.reg - My Modified Version
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\12.0\CLSID\{87BF1B1C-E1DF-4f24-A07E-2BD9B8CAD316}]
@="AGDataSetGenerator"
"InprocServer32"="C:\\WINDOWS\\system32\\mscoree.dll"
"Class"="BottomLine.Generators.VBNETAGDataSetGenerator"
"Assembly"="AGDataSetGenerator, Version=1.0.0.0, Culture=neutral, PublicKeyToken=35e4ca7ea38d2508"
"ThreadingModel"="Both"

[HKEY_LOCAL_MACHINE\Software\Wow6432Node\Microsoft\VisualStudio\12.0\CLSID\{87BF1B1C-E1DF-4f24-A07E-2BD9B8CAD316}]
@="AGDataSetGenerator"
"InprocServer32"="C:\\WINDOWS\\system32\\mscoree.dll"
"Class"="BottomLine.Generators.VBNETAGDataSetGenerator"
"Assembly"="AGDataSetGenerator, Version=1.0.0.0, Culture=neutral, PublicKeyToken=35e4ca7ea38d2508"
"ThreadingModel"="Both"

[HKEY_LOCAL_MACHINE\Software\Microsoft\VisualStudio\12.0\Generators\{164B10B9-B200-11D0-8C61-00A0C91E29D5}\AGDataSetGenerator]
@="AGDataSetGenerator"
"CLSID"="{87BF1B1C-E1DF-4f24-A07E-2BD9B8CAD316}"
"GeneratesDesignTimeSource"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\VisualStudio\12.0\Generators\{164B10B9-B200-11D0-8C61-00A0C91E29D5}\AGDataSetGenerator]
@="AGDataSetGenerator"
"CLSID"="{87BF1B1C-E1DF-4f24-A07E-2BD9B8CAD316}"
"GeneratesDesignTimeSource"=dword:00000001

Regardless of everything I've tried. When I right-click a dataset and try to run custom tool. BAM! I get the following:

If anyone can get this working in similar settings to my own, I'd love to know how you did it.

A: I'm very much the type of person that find's it very hard to take NO for an answer when it comes to technology. Unfortunately the answer here is simply just "No". The custom tool is very much outdated and to get it to work in VS 2013 just isn't feasible (I still can't bring myself to say impossible).
I'm writing this answer because I have a workaround that I suggest anyone in the same situation use straight out of the gate instead of trying to get that old tool to work. As a workaround, I created a new data project in .Net 3.5 and used entity framework to bring in just the models I needed to update. I generated my models from database and then went to the .aspx code behinds and replaced references to the outdated generated datasets. It took some refactoring but using EF instead of those ancient generated datasets cut the code by about 40%. Win Win in my opinion. Hope this helps someone else in the future.

A: According to the old .reg reference to VS 7.1, that means it was built to work in VS 2003.  I know that VS plugin coding changed a lot in VS 2010 and later editions.  So, it is possible this plugin may only work in VS 2003... possibly all the way up to VS 2008.  But, it may need to be re-written to work in anything later.
Hopefully you have MSDN or know someone who does.  I would spin up a VM, install VS 2003 (or you could try up to VS 2008), and install this plugin using the original .reg/.cmd.


text:
Q: How do I submit a form with a link in ASP.Net MVC? I have a HTML form, and I have a Controller Action that accepts the POST request. Everything works with a regular submit button, but I would like to submit the form with a link (-tag) instead, to be able to further control the formatting. Is there any way of doing this nicely built into the ASP.NET MVC Framework, or should I write my own extension method? Is it even possible to do this without javascript (I will use AJAX in the future, but it has to work without).

A: Here is a complete example. Note that this particular example does something fairly important: it has a fallback for browsers with JavaScript disabled.

A: If javascript and jQuery is enabled this effectively replaces all submit-buttons with links:
$("input:submit").hide().each(function (index, Element) {
    var elm = $(Element);
    elm.after($("" + elm.val() + "")
            .click(function () { elm.click(); })
        );
});

Based on post linked to in the accepted answer.

A: I'm not aware of a helper and as far as I know it is impossible to submit a form using an anchor tag without using javascript.

A: You cannot 'submit a form' using a link ( tag) without Javascript.  The javascript is going to generate a standard POST request (same as clicking a submit form button) behind the scenes.
There are other workarounds for those with JS disabled, look at what @Craig Stuntz submitted.


text:
Q: What is the right way to upload CentOS packages to Nexus 3? I uploaded CentOS-8.1 AppStream and BaseOS packages to Nexus-3 with curl.
When I try to install httpd using Nexus-3 yum repository, it gives me

"Package httpd-2.4.37 requires mod_httpd2 but none of providers can be
  installed."

First I thought I missed some packages to upload. But that was not the case.
Then I mount CentOS iso file and tried to install httpd using local repository, success!
Problem is repomd.xml files are different. Nexus creates it's own repomd.xml files after a package is uploaded which create conflicts.
In addition "yum group list" does not work with Nexus.
What is the right way to upload CentOS packages to Nexus repository?

A: Instead of uploading all rpm to yum(hosted) repository, I uploaded all directories and files to raw(hosted) repository. Works fine!


text:
Q: making changes to a base64 string and saving it as an image I'm converting an image to a base64 string in python, turning that into a list, making changes to a few characters and converting the base64 string back to an image.
The purpose of this is to create glitch art, where small changes in the image's encoding can produce certain effects.
This is what my code looks like:
import base64
import random
import string

times = 0
with open(r"C:\Users\Justin\Desktop\image.jpg", "rb") as image:
    text = base64.b64encode(image.read())
text = str(text)
text = list(text)
char_no = len(text)
while True:
    crpt_amn = input("how much do you want to corrupt the image? insert a value from 0 to " + str(char_no) + " ")
    try:
      if int(crpt_amn) < 0:
          print("value is out of range!")
      elif int(crpt_amn) > char_no:
          print("value is out of range!")
      else:
          break
    except ValueError:
          print("that isn't a number")
while times < (int(crpt_amn) + 1):
    picked = random.randint(0, char_no)
    if text[picked] == '/':
        times += 1
    else:
        text[picked] = random.choice(string.ascii_letters)
        times += 1
text = ''.join(text)
text = str.encode(text)
text = base64.b64decode(text)
filename = "out_img.jpg"
with open(filename, "wb") as picture:
    picture.write(text)

However, there seems to be an issue with converting text to str(text) to str.encode(text) and back to base64.b64decode(text) as the output image wouldn't open.
The changes made to the base64 string are minuscule, and even if you set crypt_amn to 0, such that no changes are made to it, the output image still wouldn't open.
I've tried getting rid of the whole corruption part and stripped down the code to just this:
import base64
import random
import string

with open(r"C:\Users\Justin\Desktop\image.jpg", "rb") as image:
    text = base64.b64encode(image.read())
text = str(text)
text = str.encode(text)
text = base64.b64decode(text)
filename = "out_img.jpg"
with open(filename, "wb") as picture:
    picture.write(text)

yet the output image is still unable to be opened.
Is there any way to achieve the desired functionality, with the user being able to make edits to the base64 string as a list?
Thank you!
(sorry if I got some terminology wrong or my question seems absurd, I'm still a beginner at python)


text:
Q: Error when saving entities using breezejs(missing ScriptAssemblyAttribute ) I get the following error when clicking on the save button in the breezejs nuget sample:
Could not load type 'System.Runtime.CompilerServices.ScriptAssemblyAttribute' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
I get the error when SaveChanges in the code below is called:
[HttpPost]
public SaveResult SaveChanges(JObject saveBundle) {
   return _contextProvider.SaveChanges(saveBundle);
}

Actually ScriptAssemblyAttribute does not exist in the intellisense when I lookup System.Runtime.CompilerServices in the code editor and I'm targeting .NET 4.5.
What am I missing?
Thanks in advance.

A: Turns out Script# has something to do with it. I uninstalled it and the error was gone.


text:
Q: Ideas to represent such a case I am designing a flight simulation  program and I am looking for ideas on how to properly
implement such requirement.
Kindly look at my picture below.  The points represents location.

The idea is this,  I wanted to properly create a data structure to best represent such scenario
in java such that

*

*when I am in Point 1, how far I am from the last point which is Point 8?

*

*Points 2, 3 and 5 are at the same distance from Point 8

*From Point 1, I could traverse to Point 3 to Point 6 then 7  then eight that would equate to 4 Steps.

*when I am in Point 0

*

*I could traverse to  Point 4 then 5  then 7 then reach point 8 which would equate to 4 steps also.

I just wanted to assist user to help them find different route.
Is this possible and which java data structure should best fit this requirement? Also any design ideas how to implement this?
Sorry if my question might be vague, I am just trying to get as much information as I can to properly handle such requirement.

A: What you have is a weighted graph where the weights represent the distance between the nodes (which is very common). You could easily implement this yourself (and it's a great way to learn!), but there are lots of java source code for this out there.
Of course, this is not a java data structure. It's simply a data structure (or a concept), used by everyone, everywhere.
Calculating steps and distances is very easy once you've implemented a weighted graph.
There are massive amounts of documentation on all of this, especially here on Stackoverflow.

A: This is a Shortest Path problem, a common Graph problem. The usual way to represent the data is an Adjancency List or Matrix:
An adjancency list keeps, for every node, all 1-step reachable destinations. This is often implemented as a Linked List. It's the proper choice if your graph is relatively sparse (i.e. few destinations per node).
An adjancency matrix is used for (very) dense graphs. Basically, you keep an NxN matrix of values (weights/costs, or yes/no booleans). Then, distances[i][j] represents the cost of travelling to j from i. An unavailable arc has a cost of INF (or some error value).
The problem itself is generally solved by Dijkstra's Algorithm.


text:
Q: How to add delay to document.getElementById I have this:
I'm trying to load this js code, value.id corresponds to an element that is detected after loading page. But actually this code is running before the element is loaded and im having this error:
Cannot read property 'nodeType' of null
I want to add something like delay on the document.getElementById(value.id)
I tried this, but nothing:
    const area = setTimeout(document.getElementById(value.id), 4000);
    Count.on(area, counter => {
    ...

and:
function setDelay() {
  document.getElementById(value.id);
}
setTimeout(setDelay, 4000);
const area = setDelay
Count.on(area, counter => {
...

both giving same error, any idea??

A: You can put code inside one function and call it setDelay function
function setDelay() {
    const area = document.getElementById(value.id);
    Count.on(area, counter => {
    ...
}
setTimeout(setDelay, 4000);

setTimeout will not return anything to caller.

A: Thanks to all, i solved it with this:
$(document).ready(function(){
// your code
});


text:
Q: Runtime.ImportModuleError Error: Cannot find module 'axios/lib/utils' Serverless I am using the Serverless framework. Backend as node.js. I have several microservices and all others are working fine, but now I have created now microservice where I have not used Axios but still, it is throwing error in the console.
One more issue is that in my local system it works perfectly, but as I push the same into the server then it starts creating issues.

This is the sample code which is throwing error
    const { IamAuthenticator } = require('ibm-watson/auth');
    const NaturalLanguageUnderstandingV1 = require('ibm-watson/natural-language-understanding/v1');

    async function textAnalyse(req, res) {
      const naturalLanguageUnderstanding = new NaturalLanguageUnderstandingV1({
      version: '2019-07-12',
      authenticator: new IamAuthenticator({
        apikey: 'API KEY'
      }),
    url: 'https://URL/natural-language-understanding/api'
    });

    const analyzeParams = {
       'text': HtmlToText.fromString('Test text here'),
       'features': {
         'entities': {
           'sentiment': true,
           'limit': 100
          }
        }
    };

    const analysis = await naturalLanguageUnderstanding.analyze(analyzeParams);

    // prepare the response object
    res.send({ analysis: analysis });
  }

Error in AWS Cloud watch
{
    "errorType": "Runtime.ImportModuleError",
    "errorMessage": "Error: Cannot find module 'axios/lib/utils'",
    "stack": [
        "Runtime.ImportModuleError: Error: Cannot find module 'axios/lib/utils'",
        "    at _loadUserApp (/var/runtime/UserFunction.js:100:13)",
        "    at Object.module.exports.load (/var/runtime/UserFunction.js:140:17)",
        "    at Object.<anonymous> (/var/runtime/index.js:45:30)",
        "    at Module._compile (internal/modules/cjs/loader.js:778:30)",
        "    at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)",
        "    at Module.load (internal/modules/cjs/loader.js:653:32)",
        "    at tryModuleLoad (internal/modules/cjs/loader.js:593:12)",
        "    at Function.Module._load (internal/modules/cjs/loader.js:585:3)",
        "    at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)",
        "    at startup (internal/bootstrap/node.js:283:19)",
        "    at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)"
    ]
}

A: I found the fixes for this.
when we call third-party API from our Lambda it requires the Axios to be implemented internally. So you need to create a folder that will have a package.json file with the dependency
"dependencies": {
    "axios": "^0.19.2"
  }

Then add the layer in the functions from AWS UI, left side menu

Then add the layer to your function

Now, by doing the above activity the issue will be resolved and Axios dependency is added successfully individually to the microservice.

A: Also, what you name the folders matters before zipping. Review these AWS docs for folder naming so you can import the library like you would in any other project.
https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html


text:
Q: How to set navigation params from outside navigation stack? I have a header in my app that needs to render a different button depending on whether or not the user has notifications. This is how I currently have it set up in my pages:
static navigationOptions = ({ navigation }) => {
    return {
      title: 'My Profile',
      headerRight: () => (
        <Button
          type="clear"
          icon={() => <Icon
            type="material-community"
            size={25}
            name={UserProvider.bNotifications ? 'bell' : 'bell-outline'}
            color={UserProvider.bNotifications ? COLORS.WARNING : COLORS.WHITE}
          />}
          onPress={() => navigation.navigate('Notifications', null)}
        />
      )
    }
  };

The problem is, if UserProvider.bNotifications changes value, the header button doesn't update unless the page is changed / rerendered.
I want to switch to use the navigation property that is passed into those navigationOptions, but I don't no how to access it from outside the navigation stack. UserProvider is a static class (NOT a component) so I can't access the navigation prop through the usual manner (or by using the useNavigation hook).
I do have a NavigationProvider class that has access to the NavigationContainer for the app. I use it to trigger navigation without components. Is there some way I can set the params on the navigation property using that same reference?
NavigationProvider:
import { NavigationActions } from 'react-navigation';

let _navigator;

function getNavigator() {
  return _navigator;
}

function setTopLevelNavigator(navigatorRef) {
  _navigator = navigatorRef;
}

function navigate(routeName, params) {
  _navigator.dispatch(
    NavigationActions.navigate({
      routeName,
      params,
    })
  );
}

function goBack() {
  _navigator.dispatch(
    NavigationActions.back()
  );
}

export default {
  navigate,
  setTopLevelNavigator,
  getNavigator,
  goBack
};

The ref is set like this in my top level App component:
<AppContainer
        ref={navigatorRef => {
          console.log(navigatorRef.props.navigation);
          NavigationProvider.setTopLevelNavigator(navigatorRef);
        }}
      />

EDIT - UserProvider
This is just the gist of my UserProvider class, but should convey how it works.
export default class UserProvider {
  private static _bNotifications: boolean;

  static get bNotifications(): boolean {
    if (!this.hasInitNotifications)
      this.initNotficationWatch();
    return this._bNotifications;
  }

  static set bNotifications(bNotifications: boolean) {
    this._bNotifications = bNotifications;
  }

  static initNotficationWatch() {
    //Firebase listener on notification
    if(notifications){
      this.bNotifications = true;
    } else {
      this.bNotifications = false;
    }
  }
}

A: How to set navigation params from outside navigation stack?
to do this you have to utilize the getParam method that comes from the navigation prop. the way I would di it would be to set a variable to a parameter that would equal to UserProvider.bNotifications.
static navigationOptions = ({ navigation }) => {
 let notifications = navigation.getParam('notifications')
    return {
      title: 'My Profile',
      headerRight: () => (
        <Button
          type="clear"
          icon={() => <Icon
            type="material-community"
            size={25}
            name={notifications ? 'bell' : 'bell-outline'}
            color={notifications ? COLORS.WARNING : COLORS.WHITE}
          />}
          onPress={() => navigation.navigate('Notifications', null)}
        />
      )
    }
  };

you can set the param to an initial value by adding it as a second argument if needed navigation.getParam('paramName', 'param initial value')

To update the parameter you need to use the setParams method. For this you can use the useNavigation hook.

You can also do this inside of a functions instead of a element

// remember to const navigation = useNavigation()

 <Button
    title="Update param"
    onPress={() => navigation.setParams({notifications: 'new value'})}
  />

you can also initiate the value this way... but I would recommend to initialize the value inside your navigationOptions

I haven't tested the code but it should work
RN DOCS: https://reactnavigation.org/docs/2.x/headers/


text:
Q: JSON Schema 'Required' validation set/removed by checkbox I am designing a web application modelled using JSON Schema. I am attempting to create a page with a text area and a checkbox. The text area is to explain why I like pizza. If the user clicks the check box, they are confirming they don't like pizza. The text box is 'required' unless the checkbox is selected. The checkbox is effectively operating as a boolean, but the components being used cannot be altered (because a user researcher said so). At the moment, I'm using AJV to validate my schema, and it is configured to throw errorMessages.required when a property is required but no input is entered/selected.
Unfortunately I'm completely inexperienced when it comes to JSON schema. Below is my current attempt to get this to validate. This renders correctly, but it doesn't work as I want - In my dev environment it just validates anything, yet on jsonschemavalidator.net it wont validate unless the checkbox is checked. How can my desired function be achieved?
{
$schema: 'http://json-schema.org/draft-07/schema#',
type: 'object',
additionalProperties: false,
propertyNames: {
    enum: [
        'q-why-i-love-pizza',
        'q-i-hate-pizza'
    ]
},
properties: {
    'q-why-i-love-pizza': {
        type: 'string',
        title: 'If you love pizza, tell us why',
        maxLength: 500,
        errorMessages: {
            required: "Please tell us why you love pizza, or select 'I hate pizza'"
        }
    },
    'q-i-hate-pizza': {
        type: 'array',
        maxItems: 1,
        uniqueItems: true,
        items: {
            anyOf: [
                {
                    title: 'I hate pizza',
                    const: 'hate'
                }
            ]
        },
        errorMessages: {
            required: "Please tell us why you love pizza, or select 'I hate pizza'"
        }
    }
},
allOf: [
    {
        $ref: '#/definitions/if-not-checked-then-q-why-i-love-pizza-is-required'
    }
],
definitions: {
    'if-not-checked-then-q-why-i-love-pizza-is-required': {
        if: {
            not: {
                properties: {
                    'q-i-hate-pizza': {
                        const: 'hate'
                    }
                }
            }
        },
        then: {
            required: ['q-why-i-love-pizza'],
            propertyNames: {
                enum: [
                    'q-i-hate-pizza',
                    'q-why-i-love-pizza'
                    ]
                }
            }
        }
    }
}

EDIT:
I expect the following:
{
    'q-why-i-love-pizza' : '',
    'q-i-hate-pizza' : ['']
}

This should FAIL validation as no values have been selected.
{
    'q-why-i-love-pizza' : 'I love pizza because it's amazing',
    'q-i-hate-pizza' : ['']
}

This should PASS because the user has entered why they love pizza, so clicking the check box was not necessary.
{
    'q-why-i-love-pizza' : '',
    'q-i-hate-pizza' : ['hate']
}

This should PASS because although the user has not told us why they love pizza, they have checked the box to indicate they hate pizza.
{
    'q-why-i-love-pizza' : 'I am a user, so decided to tell you I hate pizza too',
    'q-i-hate-pizza' : ['hate']
}

This should also PASS because I need to accept the possibility that a user will tick the box to say they hate Pizza, but proceed to tell me anyway.
Solution:
{
    type: "object",
    properties: {
        'q-why-i-love-pizza': {
            type: 'string',
            title: 'If you love pizza, tell us why',
            maxLength: 500,
            errorMessages: {
            required: "Please tell us why you love pizza, or select 'I hate pizza'"
            }
        },
        'q-i-hate-pizza': {
            type: 'array',
            maxItems: 1,
            uniqueItems: true,
            items: {
                anyOf: [
                    {
                        title: 'I hate pizza',
                        const: 'hate'
                    }
                ]
            },
            errorMessages: {
                required: "Please tell us why you love pizza, or select 'I hate pizza'"
            }
        }
    },
    allOf: [
        { $ref: "#/definitions/if-not-checked-then-q-offender-contact-description-is-required" }
    ],
    definitions: {
        "if-not-checked-then-q-offender-contact-description-is-required": {
            if: {
                not: {
                    required: ["q-i-hate-pizza"]
                }
            },
            then: {
                required: ["q-why-i-love-pizza"]
            }
        }
    }
}

A: I've simplified your schema, so this might not be perfect, but this general approach should work.
{
  "type": "object",
  "properties": {
    "q-why-i-love-pizza": { "type": "string", "maxLength": 500 },
    "q-i-hate-pizza": { "const": ["hate"] }
  },
  "allOf": [
    { "$ref": "#/definitions/if-hates-pizza-then-q-why-i-love-pizza-is-required" }
  ],
  "definitions": {
    "if-hates-pizza-then-q-why-i-love-pizza-is-required": {
      "if": { "not": { "required": ["q-i-hate-pizza"] } },
      "then": { "required": ["q-why-i-love-pizza"] }
    }
  }
}

A: You're most of the way there, but you've missed something you may not have expected.
Your schema for if-not-checked-then-q-why-i-love-pizza-is-required.
The const keyword is only applicable to the property, IF it exists.
You need to add a required constraint to the if schema.
Obviously this is at a guess, as you haven't provided your JSON instance data.


text:
Q: Injecting unicode characters via termios.TIOCSTI I have a piece of python code that injects entries from the bash history into the command prompt.
Everything worked perfectly until I switched to Python 3.
Now German Umlaute appear wrong.
eg.
python3 console_test.py mööp

results in:
$ m�

Here's the relevant code:
import fcntl
import sys
import termios

command = sys.argv[1]

fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~termios.ECHO  # disable echo
termios.tcsetattr(fd, termios.TCSANOW, new)
for c in command:
    fcntl.ioctl(fd, termios.TIOCSTI, c)
termios.tcsetattr(fd, termios.TCSANOW, old)

I tried encoding the input to utf-8 but that gave me:
OSError: [Errno 14] Bad address

A: Found the answer myself, Python3 automatically decodes the arguments with the filesystem encoding so I had to reverse that before calling the ioctl:
import fcntl
import sys
import termios
import struct
import os

command = sys.argv[1]

if sys.version_info >= (3,):
    # reverse the automatic encoding and pack into a list of bytes
    command = (struct.pack('B', c) for c in os.fsencode(command))

fd = sys.stdin.fileno()
old = termios.tcgetattr(fd)
new = termios.tcgetattr(fd)
new[3] = new[3] & ~termios.ECHO  # disable echo
termios.tcsetattr(fd, termios.TCSANOW, new)
for c in command:
    fcntl.ioctl(fd, termios.TIOCSTI, c)

termios.tcsetattr(fd, termios.TCSANOW, old)


text:
Q: how to setup firefox debugger properly? I tried the steps for quick setup of firefox debugger at http://firefox-dev.tools/debugger/#quick-setup a few times but had the same problem.
I have pasted all my commands and warning (including error) messages in a gist at the bottom.
I suspect two things may cause the failure of the setting up.

*

*when running curl -o- -L https://yarnpkg.com/install.sh | bash -s, I got warning message saying it is advised to not mix npm with yarn. However, I have not yet found out a way to separate them.

*when running yarn, I got a lot of warning message saying the versions of packages are not matching, a lot of error messages for failing to run commands which I suspect to be the result of unmet packages but I can be wrong about it.
or what do you think the problem is?
could you give me some guidance on how to resolve this setting up problem? Thanks
please see the warning and error messages here in the gist.
https://gist.github.com/EmbraceLife/f84993112c5b4a894c30b0a4ba4bb4fc

A:
it is advised to not mix npm with yarn

...in a single project. If you follow the instructions of cloning a clean repository and running yarn install inside, you should be fine.

I got a lot of warning message saying the versions of packages are not matching

I get these too, so I don't think anything is wrong on your end.
warning " > react-redux@5.0.7" has unmet peer dependency "redux@^2.0.0 || ^3.0.0 || ^4.0.0-0".
warning "devtools-launchpad > svg-inline-react@3.0.0" has incorrect peer dependency "react@^0.14.0 || ^15.0.0".
warning "devtools-launchpad > url-loader@0.5.9" has unmet peer dependency "file-loader@*".
warning " > eslint-plugin-mozilla@1.2.1" has unmet peer dependency "eslint-plugin-no-unsanitized@^3.0.0".
warning "devtools-reps > devtools-components > @storybook/react@3.4.8" has unmet peer dependency "babel-core@^6.26.0 || ^7.0.0-0".
warning "devtools-reps > devtools-components > @storybook/react@3.4.8" has unmet peer dependency "babel-runtime@>=6.0.0".
warning " > babel-jest@23.6.0" has unmet peer dependency "babel-core@^6.0.0 || ^7.0.0-0".

node-pre-gyp WARN Pre-built binaries not found for fsevents@1.2.4 and node@12.9.1 (node-v72 ABI, unknown) (falling back to source compile with node-gyp)

followed by a large number of build errors, ending with:
30 warnings and 14 errors generated.
make: *** [Release/obj.target/fse/fsevents.o] Error 1
gyp ERR! build error

...looks like a problem with your running node12 (the CI seems to be running with node10) but I'm not even sure lack of fsevents is fatal...

Listening for WS on localhost:8116, all traffic is proxied to localhost:6080
TCP connection failed: Error: connect ECONNREFUSED 127.0.0.1:6080

These messages in your output are expected - you're supposed to run a controlled instance of the browser that listens on port 6080, until you do the "launcher" page tries to connect and fails repeatedly.
Apart from the console messages, is there a problem or does the debugger work?


text:
Q: Geometry - Intersection over Union for 2 squares with the same orientation I have 2 squares with the same orientation. I know the coordinate of their centers. They have the same size area.
They may intersect each other. I want to compute their area of their intersection as well as area of their union.
Let's say that their centers are (a, b) for the first square and (x, y) for the second square. The length of one of their sides is l. How can I compute their intersection and their union based on this?

A: Since they have the same orientation, you can rotate the two squares first so their sides are aligned with the x, y coordinates, then it should be easy to compute what you want.


text:
Q: VC-dimension of parity functions Consider the boolean hypercube $\{0,1\}^N$. For a set I $\subseteq$ {1,2,...N}, we define the parity function $h_I$ as follows. For a binary vector x = $(x_1, x_2, ...,x_N) \in \{0,1\}^N$,
$h_I(x) = \bigg(\sum_{i\in I}x_i\bigg)mod 2$
What is the VC-dimension of the class of all such parity functions, $H_{N-parity} = \{h_I:I\subseteq \{1,2,..., N\}\}$? [Courtesy: Shai Ben-David et al.,]

A: We have $\vert H_{N-parity}\vert = 2^N$, and since this is a finite number, we know that VCdim$(H_{N-parity}) \leq \log_2{2^N} = N$. If we can find a subset of $\{0,1\}^N$ of cardinality $N$ which is shattered by $H_{N-parity}$, then we conclude that VCdim$(H_{N-parity})=N$.
But notice that such a set is possible if you take $x_i=e_i$, i.e., the vector of all zeros with a $1$ at the $i_{th}$ position, $i=1, 2, \dots, N$.
Given any subset $K\subset \{1,2,\dots,N\}$, we wish to find a hypothesis $h$ with the property that $h(x_i)=1$ for all $i\in K$. Simply let $I=K$ and the result easily follows.

A: $ Claim: VC-dimension(H_{N-Parity})=N $
The upper bound is given by the $\log H_{N-parity}$ , which gives $N $ as there can be at most $2^N$ many such functions.
For the lower bound of the VC-dimension we need to show that there is a set of size $N$ which can be shattered. Let the set be S.
$S=\{x \in {0,1}^N | \sum_{i=1}^N x_i=1\}$
To show $\forall S' \subseteq S, \exists h \in H_{N-Parity} ~such ~that~~ h \cap S=S'$.
Here is $h$ for a particular $S'$.
$$h(x)=\sum_{i=1}^N x_i~, where~ i \in \\{ i \in [N]~ |~ e_i \in S' \\}$$.
In simple engish, h is defined to be parity of the bits which is set to 1 for each element in S'.


text:
Q: How to get image from gallery in a .jpg file format? I am trying to get image from gallery. It is giving me image as bitmap. I want the image in .jpg file so that I can save file name in my database.
I have followed this tutorial :
http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample
gallery image selected code:
@SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {

    Bitmap bm=null;
    if (data != null) {
        try {
            bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Uri selectedImage = data.getData();

    String[] filePath = {MediaStore.Images.Media.DATA};

    Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);

    c.moveToFirst();

    int columnIndex = c.getColumnIndex(filePath[0]);

    String picturePath = c.getString(columnIndex);

    c.close();
    File file = new File(picturePath);// error line

    mProfileImage = file;

    profile_image.setImageBitmap(bm);
}

I tried this. But I am getting null pointer on file.
Exception :
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference

Also I don't want this newly created file to be saved in external storage. This should be a temporary file. How can I do this?
Thank you..

A: The good news is you're a lot closer to done than you think!
Bitmap bm=null;
if (data != null) {
    try {
        bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

At this point, if bm != null, you have a Bitmap object. Bitmap is Android's generic image object that's ready to go. It's actually probably in .jpg format already, so you just have to write it to a file. you want to write it to a temporary file, so I'd do something like this:
File outputDir = context.getCacheDir(); // Activity context
File outputFile = File.createTempFile("prefix", "extension", outputDir); // follow the API for createTempFile

Regardless, at this point it's pretty easy to write a Bitmap to a file.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream); //replace 100 with desired quality percentage.
byte[] byteArray = stream.toByteArray();

Now you have a byte array. I'll leave writing that to a file to you.
If you want the temporary file to go away, see here for more info: https://developer.android.com/reference/java/io/File.html#deleteOnExit()
Bitmap bm=null;
if (data != null) {
    try {
        bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
    } catch (IOException e) {
        e.printStackTrace();
    }
}
if (bm != null) { // sanity check
    File outputDir = context.getCacheDir(); // Activity context
    File outputFile = File.createTempFile("image", "jpg", outputDir); // follow the API for createTempFile

    FileOutputStream stream = new FileOutputStream (outputFile, false); // Add false here so we don't append an image to another image. That would be weird.
    // This line actually writes a bitmap to the stream. If you use a ByteArrayOutputStream, you end up with a byte array. If you use a FileOutputStream, you end up with a file.
    bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
    stream.close(); // cleanup
}

I hope that helps!

A: Looks like your picturePath is null. That is why you cannot convert the image. Try adding this code fragment to get the path of the selected image:
private String getRealPathFromURI(Uri uri) {
    String[] projection = { MediaStore.Images.Media.DATA };
    @SuppressWarnings("deprecation")
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    int column_index = cursor
        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

After that, you need to modify your onSelectFromGalleryResult. Remove/disable line String[] filePath = {MediaStore.Images.Media.DATA}; and so on and replace with below.
 Uri selectedImageUri = Uri.parse(selectedImage);
 String photoPath = getRealPathFromURI(selectedImageUri);
 mProfileImage = new File(photoPath);

 //check if you get something like this  - file:///mnt/sdcard/yourselectedimage.png
 Log.i("FilePath", mProfileImage.getAbsolutePath)
 if(mProfileImage.isExist()){
     //Check if the file is exist.
     //Do something here (display the image using imageView/ convert the image into string)
 }

Question: What is the reason you need to convert it in .jpg format? Can it be .gif, .png etc?