text:
Q: How can I fix my built in Mac Screen Sharing App? Screen sharing through the app has been shoddy at best for me since updating.  I thought I had it figured out and now its not working this week.  My device on the same network is a linux machine and connecting to it from ssh works fine (always has).  But for whatever reason the screen sharing functionality is Broken.  I've tried to connect to server using vnc://x.x.x.x  or smb://x.x.x.x as well as without the slashes.

I've tried to connect using the Screen sharing app as well.  There is a weird 3rd option that sees my computer but it NEVER works to connect to it.

So Far I've tried to restart the machines and this:
http://forums.macrumors.com/threads/if-your-screen-sharing-stops-working-read-this.441030/
Summary says:

*

*Launch the Activity Monitor program.

*In the Process Name list, look for "NetAuthAgent". It may show as "Not Responding".

*Select NetAuthAgent, and then click Quit Process (the red stop sign button at the top of the Activity Monitor window). Then, click Force Quit.

Your Screen Sharing should now work.
But that is from 2008 so I know there's no way that they didn't fix that by now.
Bottom Line: How can I fix screen sharing to this other device, for Good?

A: On your Linux computer you will need a to run a VNC server of some sort.
There may be one already installed that you need to start. How to do this depends on the Linux distro you have. Try man vncserver at the command line on the Linux box and see what you get.
VNC is a screen sharing protocol and SMB is a file sharing protocol so you can't get screen sharing using SMB.


text:
Q: php reload page without posting data I'm trying to refresh a page without sending POST from the previous time.
I've tried
window.open("postme.php?r=t", "_self");

Which appends a ?r=t to the end but it doesn't appear to refresh the page as the page displays a number of files in a directory which hasn't change even though I have moved or deleted them.
Can you specify the URL in window.location.reload();?
Any ideas?
Thanks

A: If you want to avoid having refresh reporting data (for any reason, including the user clicking the reload button) then use the POST-REDIRECT-GET pattern.

A: Redirect the user to the same page after you're finished using their POST data.
$URI = $_SERVER['REQUEST_URI'];

if(!empty($_POST)){
    //magic

    header("location:$URI");
}

Now when you refresh, it won't have POST data to resubmit.

A: Well.. late too I suppose, but then it could help someone. I used :
window.location.href = window.location.href;

In replacement of location.reload(); this will refresh the page without prompting user to resend information.

A: You could try:
window.location.reload(true); //true sets request type to GET

A: i know this is way late, and hope it applies: i had the same problem where when someone is confirming their inventory selection, it then emails the order [or subtracts from inventory database] then displays their order. then if they refresh, it resubmits the data. so i added a session_destroy(). but then when they refresh, there're lots of errors.
SO - i divided the code into [a]email the order/subtract from the inventory database, then [b]used a javascript "document.location.href='nextPage.php'" because i sometimes have problems using PHP's "location(nextpage.php)". anyway, it emails the info, then goes to the page that displays it. then one can refresh all they want and all that happens is it displays over and over.
hope that helps!

A: Got this to work...
window.location = "postme.php?r=t";

redpajama_set_name: RedPajamaStackExchange


text:
Q: Undefined reference using Allegro 5 with mingw-w64 I'm trying to compile an Allegro 5 program on Windows 10 with mingw-w64.

*

*I already had installed mingw-w64. Output from g++ --version is:
g++.exe (i686-posix-dwarf-rev2, Built by MinGW-W64 project) 7.1.0
Copyright (C) 2017 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

*I downloaded windows binaries for Allegro 5 from https://github.com/liballeg/allegro5/releases (File: allegro-x86_64-w64-mingw32-gcc-8.2.1-posix-seh-static-5.2.5.0.zip) and unzipped the file into C:/allegro5 so now I have C:/allegro5/bin, C:/allegro5/include, C:/allegro5/lib.

*A small test program:
#include <stdio.h>
#include <allegro5/allegro.h>

int main(int argc, char **argv)
{
   al_init();
   return 0;
}

*And finally the command I run to compile: g++ test.cpp -I"C:/allegro5/include" -L"C:/allegro5/lib" -lallegro (There is a lib file called liballegro.dll.a under C:/allegro5/lib)
But there are some problems while linking:
C:\Users\xxxx\AppData\Local\Temp\ccg5z97Y.o:test.cpp:(.text+0x1e): undefined reference to `al_install_system'
collect2.exe: error: ld returned 1 exit status

A) What may be the reason for this ?
B) What should I do to compile in a static way ? Is changing -lallegro to -lallegro-static enough ?

A: This:
g++.exe (i686-posix-dwarf-rev2, Built by MinGW-W64 project) 7.1.0

is one of the the 32-bit GCC variants provided by MinGW-W64. You are attempting to link the
32-bit code it generates with the 64-bit libraries provided in:
allegro-x86_64-w64-mingw32-gcc-8.2.1-posix-seh-static-5.2.5.0.zip

which will not work. Replace your compiler with the appropriate 64-bit variant x86_64-posix-seh


text:
Q: Angular 2 - How to get rid of extra decimals in angular binding? i have such a statement in my view and the binding has value lets says 6970.87127381382131831 but, i want to limit it at 2 decimal at most. Since i am listing elements with ngFor, could not use an object to limit it with .toFixed(2). Thank you all !

{{ cartitem.original_price * cartitem.qty * cartitem.unit_multiplier }}

I have tried the method below :

 {{ cartitem.original_price * cartitem.qty * cartitem.unit_multiplier | number : 2 }}

Did not help me.

A: The following expression will allow you set decimal part to two digits:
 {{ cartitem.original_price * cartitem.qty * cartitem.unit_multiplier | number : '1.2-2' }}

1.2-2 means:  at least one digit before decimal point, at least 2 digits after decimal point but no more than 2 digits.

{{ cartitem.original_price * cartitem.qty * cartitem.unit_multiplier | number : '1.0-2' }}

1.0-2 means:  at least one digit before decimal point and no more than 2 digits after.

About the Angular DecimalPipes and configuration: https://angular.io/api/common/DecimalPipe

A: as reported in official docs https://docs.angularjs.org/api/ng/filter/number
{{ number_expression | number : fractionSize}}

in your case:
 {{ (cartitem.original_price * cartitem.qty * cartitem.unit_multiplier) | number : 2 }}

if you want a fix number of digits you can create your own filter
App.filter('twoDecimal',function(input, scope){

return function(){

   return input.toFixed(2);

  }
})

and apply it
 {{ (cartitem.original_price * cartitem.qty * cartitem.unit_multiplier) | twoDecimal }}


text:
Q: Having to Submit Twice Ok I am new to programming and I have an issue with some checkboxes.
I want to store if a check box is checked and display this when button is pressed.
I am making a filter search, so when a person selects a check box it will only display that filter.
However it only works if I submit and select or deselect a checkbox twice.
How can I make it to only have to do this once?
<form name="search" action="<? $_SERVER['PHP_SELF']; ?>" method="post">
   <input type="checkbox" name="checkAllMyCB" id="checkAllMyCB" onclick="jqCheckAll2( this.id, 'myCB' )"/>All
   <input name="category[]" type="checkbox" <? if (in_array("art", $_SESSION['category'])) { echo "checked='checked'";  } ?>value="art">Art
   <input name="category[]" type="checkbox" <? if (in_array("church", $_SESSION['category'])) { echo "checked='checked'";  } ?>value="church">Church
   <input name="category[]" type="checkbox" <? if (in_array("education", $_SESSION['category'])) { echo "checked='checked'";  } ?>value="education">Education/Schools
   <input name="category[]" type="checkbox" <? if (in_array("food", $_SESSION['category'])) { echo "checked='checked'";  } ?>value="food">Food
   <input name="category[]" type="checkbox" <? if (in_array("gardening", $_SESSION['category'])) { echo "checked='checked'";  } ?>value="gardening">Gardening
   <input name="category[]" type="checkbox" <? if (in_array("kids", $_SESSION['category'])) { echo "checked='checked'";  } ?>value="kids">Kids
   <input name="category[]" type="checkbox" <? if (in_array("music", $_SESSION['category'])) { echo "checked='checked'";  } ?>value="music">Music
   <input name="category[]" type="checkbox" <? if (in_array("outdoors", $_SESSION['category'])) { echo "checked='checked'";  } ?>value="outdoors">Outdoors
   <input name="category[]" type="checkbox" <? if (in_array("seniors", $_SESSION['category'])) { echo "checked='checked'";  } ?>value="seniors">Seniors
   <input name="category[]" type="checkbox" <? if (in_array("sports", $_SESSION['category'])) { echo "checked='checked'";  } ?> value="sports">Sports/Physical Activity
   <input name="category[]" type="checkbox" <? if (in_array("support", $_SESSION['category'])) { echo "checked='checked'";  } ?>value="support">Club/Support Group
   <input type="submit" name="Go2" id="Go2" value="Go >" />
<?
$_SESSION['category'] = $_POST['category']; ?>

</form>

A: Two things are wrong in your code:

*

*You are first displaying the form and then setting values into the SESSION. This should be the opposite way because when submitted, your form would be displayed first and only after the values would get set which is why you have the problem of submitting it twice to see the values.

*You are not checking whether the SESSION variable has been set before the in_array, this would throw an error initially. The same case with $_POST['category']
First place this on top:
<?
if (isset($_POST['category'])){
$_SESSION['category'] = $_POST['category']; }
else
{
    unset($_SESSION['category']);
}
?>

Then change your form code to:
<form name="search" action="" method="post">
   <input type="checkbox" name="checkAllMyCB" id="checkAllMyCB" onclick="jqCheckAll2( this.id, 'myCB' )"/>All
   <input name="category[]" type="checkbox" <?php if (isset($_SESSION['category']) && in_array("art", $_SESSION['category'])) { echo "checked='checked'";  } ?> value="art">Art
   <input name="category[]" type="checkbox" <?php if (isset($_SESSION['category']) && in_array("church", $_SESSION['category'])) { echo "checked='checked'";  } ?> value="church">Church
   <input name="category[]" type="checkbox" <?php if (isset($_SESSION['category']) && in_array("education", $_SESSION['category'])) { echo "checked='checked'";  } ?> value="education">Education/Schools
   <input name="category[]" type="checkbox" <?php if (isset($_SESSION['category']) && in_array("food", $_SESSION['category'])) { echo "checked='checked'";  } ?> value="food">Food
   <input name="category[]" type="checkbox" <?php if (isset($_SESSION['category']) && in_array("gardening", $_SESSION['category'])) { echo "checked='checked'";  } ?>value="gardening">Gardening
   <input name="category[]" type="checkbox" <?php if (isset($_SESSION['category']) && in_array("kids", $_SESSION['category'])) { echo "checked='checked'";  } ?> value="kids">Kids
   <input name="category[]" type="checkbox" <?php if (isset($_SESSION['category']) && in_array("music", $_SESSION['category'])) { echo "checked='checked'";  } ?> value="music">Music
   <input name="category[]" type="checkbox" <?php if (isset($_SESSION['category']) && in_array("outdoors", $_SESSION['category'])) { echo "checked='checked'";  } ?> value="outdoors">Outdoors
   <input name="category[]" type="checkbox" <?php if (isset($_SESSION['category']) && in_array("seniors", $_SESSION['category'])) { echo "checked='checked'";  } ?> value="seniors">Seniors
   <input name="category[]" type="checkbox" <?php if (isset($_SESSION['category']) && in_array("sports", $_SESSION['category'])) { echo "checked='checked'";  } ?> value="sports">Sports/Physical Activity
   <input name="category[]" type="checkbox" <?php if (isset($_SESSION['category']) && in_array("support", $_SESSION['category'])) { echo "checked='checked'";  } ?> value="support">Club/Support Group
   <input type="submit" name="Go2" id="Go2" value="Go >" />
</form>


text:
Q: chart.js v2.0.0 redrawing the chart I am using chart.js v2 in my application because when I try to use bower to get the latest version it doesn't pull in the dist folder, but that is another issue.
I have created an angular wrapper for this plugin to get it onto my application.
The wrapper looks like this:
.controller('ChartController', function () {
    var self = this;

    // Create our chart
    self.init = function (ctx, data, options, type) {

        // Create our config
        var config = angular.extend({}, { type: type || 'bar', data: data, options: options || {} });

        // Create our chart
        self.chart = new Chart(ctx[0], config);
    };
})

.directive('ngChart', function () {
    return {
        restrict: 'A',
        controller: 'ChartController',
        scope: {
            data: '=ngChart',
            type: '@',
            options: '='
        },
        link: function (scope, element, attrs, controller) {
            scope.$watch('type', function () {
                controller.init(element, scope.data, scope.options, scope.type);
            });
            scope.$watch('data', function () {
                controller.init(element, scope.data, scope.options, scope.type);
            });
        }
    };
});

It is very simple as you can see.
In my controller I have this:
self.reportType = 'raw';
self.reportTypes = [{ name: 'Raw data', type: 'raw' }, { name: 'Bar chart', type: 'bar' }, { name: 'Line chart', type: 'line' }];

And in my view I have this:

        <select class="form-control" ng-model="controller.reportType" ng-change="controller.test()" ng-options="type.type as type.name for type in controller.reportTypes">
        </select>

        <button class="btn btn-default" ng-print> Print</button>

    <canvas class="print-only screen-only" ng-chart="controller.chartData" type="{{ controller.reportType }}"></canvas>

Currently I only show the chart if the type is not raw.
When I select line it will draw a line chart, if I then select bar it won't do anything.
I have tried all sort of things to get it to redraw but it doesn't seem to work. The latest suggestion was the extend the config (which is what I am doing in the init method) so to create a copy and then use that config copy to create a new chart.
This didn't work.
Does anyone know how I can get it to work?

A: I found that if I modified the data, the chart redrew itself.
So with that in mind, I changed my init method to this:
// Create our chart
self.init = function (ctx, data, options, type) {

    // Create our config
    var config = { type: type || 'bar', data: angular.copy(data), options: options || {} };

    // Create our chart
    self.chart = new Chart(ctx[0], config);
};

And that worked, it now redraws properly.
I guess that is because it must check to see if the data has changed, if I do a copy then it is always changing.


text:
Q: How to invoke a lambda function from another lambda in serverless offline? I'm trying to invoke a lambda function within the lambda function using Serverless framework. I'm using this code right now and it works fine when deployed to AWS. But it returns some errors locally in serverless-offline.
Code I'm using right now:
const middy = require("@middy/core");
const httpErrorHandler = require("@middy/http-error-handler");
const httpUrlEncodeBodyParser = require("@middy/http-urlencode-body-parser");

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

const lambda = new AWS.Lambda();

const baseHandler = async (payload) => {
  const params = {
    FunctionName: `my-api-${process.env.STAGE}-handleProcessA`,
    InvocationType: "Event",
    LogType: "None",
    Payload: JSON.stringify(payload),
  };

  await lambda.invoke(params).promise();

  return standardResponse();
}

const endpoint = middy(baseHandler)
  .use(httpUrlEncodeBodyParser())
  .use(httpErrorHandler());

module.exports = { endpoint };

When this is triggered, it says that the function is not found:
Function not found: arn:aws:lambda:us-west-2:893853743015:function:my-api-local-handleProcessA
I tried the suggestions from these SO questions as well:
https://stackoverflow.com/a/58766387/1481519
https://stackoverflow.com/a/69967531/1481519
Based on the suggestions, I changed this part:
const lambda = new AWS.Lambda({
  region: "us-west-2",
  endpoint: process.env.IS_OFFLINE
    ? "http://localhost:6002"
    : "https://lambda.us-west-2.amazonaws.com",
});

But then, it gives me Unsupported Media Type with status 415. Has anyone encountered this before? Any guidance is appreciated.
Thanks.

A: Finally, I figured out the solution with some help. This works when I change the offline endpoint to be http://localhost:3002: where 3002 is the default lambdaPort.
const lambda = new AWS.Lambda({
  region: "us-west-2",
  endpoint: process.env.IS_OFFLINE
    ? "http://localhost:3002"
    : "https://lambda.us-west-2.amazonaws.com",
});

Explanation:
In serverless offline, there are CLI options to set the --lambdaPort and --httpPort.
The default --httpPort is 3000 and the default --lambdaPort is 3002.
In my project, I have set the --httpPort to be 6002 without custom --lambdaPort which defaulted to 3002.
I was invoking the lambda function using 6002 which was incorrect. Using 3002 solved it.


text:
Q: NestJS CORS blocking localhost I am trying to enable CORS to connect my nestJS API with a local react app. But it seems that CORS is blocking access from the React App.

I've tries this so far:
First attempt:
 async function bootstrap() {
  const app = await NestFactory.create(AppModule, { cors: true });
  app.listen(3000);
}
bootstrap();

Second attempt:
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
        methods: ["GET", "POST"],
        origin: '*',
  })
  app.listen(3000);
}
bootstrap();

And third attempt:
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors({
        methods: ["GET", "POST"],
        origin: 'http://localhost:3001/',
  })
  app.listen(3000);
}
bootstrap();

Nothing of that seems to work.
The React app is just a simple superagent call like this:
 const res = sa.get(`http://localhost:3000/jokes/random`).withCredentials().end(res => console.log(res))

I've tried to use the superagent with and without the withCredentials.
Any idea of what is going on? thank you.


text:
Q: add space between bars in each subgroup in pandas barplot I have a dataframe like so:
    chart = pd.DataFrame({'test1_bottom': {'Information Technology': 0.2533668392286677,
  'Health Care': 0.15018887027604233,
  'Financials': 0.11250374171121448,
  'Communication Services': 0.10598698851685082,
  'Consumer Discretionary': 0.09930980115655588,
  'Industrials': 0.08341663798744221,
  'Consumer Staples': 0.077755633372036,
  'Utilities': 0.03633802369644037,
  'Real Estate': 0.030599694393051324,
  'Energy': 0.026211182457138587},
 'test1_top': {'Information Technology': 0.2533668392286677,
  'Health Care': 0.15018887027604233,
  'Financials': 0.11250374171121448,
  'Communication Services': 0.10598698851685082,
  'Consumer Discretionary': 0.09930980115655588,
  'Industrials': 0.08341663798744221,
  'Consumer Staples': 0.077755633372036,
  'Utilities': 0.03633802369644037,
  'Real Estate': 0.030599694393051324,
  'Energy': 0.026211182457138587}})

Im trying to add spaces between bars in each subgroup as my value label over each bar is overlapping:
figsize=(9,4)
ax = chart.iloc[::-1].plot.barh(figsize=figsize, color=['#0574A0','#FF5233'],width=0.5);
for p in ax.patches:
    v = ax.annotate("{:,.2%}".format(p.get_width()), (p.get_width(), p.get_y() + p.get_height()/4), xytext=(4, -1),
                textcoords='offset points',ha='left');
plt.legend(loc='lower right',fontsize=10)
plt.tight_layout(pad=-5)

Im trying to add a small space between the red and green bars above.  Thanks
You can see the figure generated:

A: You can do some manual plot and alignment:
# set up figure
fig, ax = plt.subplots(figsize=(10,6))
y=np.arange(len(chart))

# height of bar and gap
height = 0.4
gap = 0.02

# plot with plt.barh
for offset, col in zip([-1,1], chart.columns):
    plt.barh(y + offset * (height+gap)/2, chart[col], height=height, label=col)

for p in ax.patches:
    v = ax.annotate("{:,.2%}".format(p.get_width()), (p.get_width(), p.get_y() + p.get_height()/4), xytext=(4, -1),
                textcoords='offset points',ha='left');
plt.legend(loc='lower right',fontsize=10)
plt.tight_layout(pad=-5)

# invert the yaxis so you don't need [::-1]
ax.invert_yaxis()

# force yticks
plt.yticks(y, chart.index)
plt.show()

Output:


text:
Q: I need help making this regular expression to match part of url I am writing a rewrite rule in web.config file and want to match against a url (using regular expression) if it containes:
*/admin*

So as long as the url contains above it should match. Example of legal matches:
http://test.com/admin
https://test.com/admin
http://test.com/admin/
http://test.com/admin/test
http://test.com/admin/grgr/hht/

Example of illegal matches:
http://test.com
https://test.com/adminpage
https://test.com/adminpage/

I have tried the followings without success:
<match url="(.*)/admin$" ignoreCase="false" />
<match url="/admin?" ignoreCase="false" />
<match url=".*/admin?" ignoreCase="false" />

A: Try something like this
.*\b\/admin\b.*

https://regex101.com/r/zq0SAy/1
Details:

*

*\b asserts position at a word boundary

A: Try this regex
.*admin(\/.*|$)


text:
Q: DevExpress TreeListControl create custom cell template I am having trouble binding stuff with THIS CONTROL.
I want to create a custom cell template not the default one. When using the default cell template my binding works. Here is my project:
XAML:
<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:dxt="http://schemas.devexpress.com/winfx/2008/xaml/grid" >
    <Window.Resources>

    </Window.Resources>
    <Grid>
        <dxt:TreeListControl Name="treeList">
            <dxt:TreeListControl.Columns>

                <!-- Custom Column -->
                <dxt:TreeListColumn FieldName="Name" Header="Name">
                    <dxt:TreeListColumn.CellTemplate>
                        <DataTemplate >
                            <TextBlock Text="{Binding Path=Name}" Foreground="Blue" />
                        </DataTemplate>
                    </dxt:TreeListColumn.CellTemplate>
                </dxt:TreeListColumn>

                <!-- default Column -->
                <dxt:TreeListColumn FieldName="Position" Header="Position"/>

            </dxt:TreeListControl.Columns>
            <dxt:TreeListControl.View>
                <dxt:TreeListView Name="treeListView1" AutoWidth="True"
                                  KeyFieldName="ID" ParentFieldName="ParentID"/>
            </dxt:TreeListControl.View>
        </dxt:TreeListControl>
    </Grid>
</Window>

Code Behind:
using System.Collections.Generic;
using System.Windows;
using System.Windows.Documents;

namespace WpfApplication2
{
    public partial class MainWindow : Window
    {
        public MainWindow ( )
        {
            InitializeComponent( );
            treeList.ItemsSource = GetStuff( );
            treeListView1.ExpandAllNodes( );
        }

        public static List<Employee> GetStuff ( )
        {
            List<Employee> stuff = new List<Employee>( );

            stuff.Add( new Employee( ) { ID = 1 , ParentID = 0 , Name = "Gregory S. Price" } );
            stuff.Add( new Employee( ) { ID = 2 , ParentID = 0 , Name = "Irma R. Marshall" } );
            stuff.Add( new Employee( ) { ID = 3 , ParentID = 0 , Name = "John C. Powell" } );

            stuff.Add( new Employee( ) { ID = 6 , ParentID = 2 , Position = "Brian C. Cowling" } );
            stuff.Add( new Employee( ) { ID = 7 , ParentID = 2 , Position = "Thomas C. Dawson" } );
            stuff.Add( new Employee( ) { ID = 8 , ParentID = 2 , Position = "Angel M. Wilson" } );
            stuff.Add( new Employee( ) { ID = 9 , ParentID = 2 , Position = "Bryan R. Henderson" } );

            stuff.Add( new Employee( ) { ID = 10 , ParentID = 3 , Position = "Harold S. Brandes" } );
            stuff.Add( new Employee( ) { ID = 11 , ParentID = 3 , Position = "Michael S. Blevins" } );
            stuff.Add( new Employee( ) { ID = 12 , ParentID = 3 , Position = "Jan K. Sisk" } );
            stuff.Add( new Employee( ) { ID = 13 , ParentID = 3 , Position = "Sidney L. Holder" } );

            stuff.Add( new Employee( ) { ID = 14 , ParentID = 1 , Position = "Brian C. Cowling" } );
            stuff.Add( new Employee( ) { ID = 15 , ParentID = 1 , Position = "Thomas C. Dawson" } );
            stuff.Add( new Employee( ) { ID = 16 , ParentID = 1 , Position = "Angel M. Wilson" } );
            stuff.Add( new Employee( ) { ID = 17 , ParentID = 1 , Position = "Bryan R. Henderson" } );

            return stuff;
        }
    }
}

public class Employee
{
    public int ID { get; set; }
    public int ParentID { get; set; }
    public string Name { get; set; }
    public string Position { get; set; }
}

why is it that my (<!-- Custom Column -->) does not display the Name of the employe? what do I have to do to bind it to that Property? If I remove the CellTemplate it works but I want to have my custom style...

A: Ok I'm going to answer before Devex Team :)
Change this :
<TextBlock Text="{Binding Path=Name}" Foreground="Blue" />

To this :
<TextBlock Text="{Binding Path=Data.Name}" Foreground="Blue" />

Or simply :
<TextBlock Text="{Binding Data.Name}" Foreground="Blue" />


text:
Q: Browsers do not accept a valid encryption certificate I used to import self signed certificates generated by me to the Windows' Root CA storage. It always did the trick.
Now I encountered a self signed certificate generated by our company as a part of a product. It is installed along with the product.
When I go to a web site of the application, all browsers (MS Edge, Vivaldi, Chrome) show that the certificate is invalid, but when I view certificate's properties with the same browser, everything is valid.
How could it be and what is the problem? Importing this certificate to Root CA storage does not help.

A: Browser vendors have recently tightened their validity rules. I wouldn't be surprised if some of the UI hasn't kept up with the recent changes. For example, certificates are no longer allowed to have a validity period longer than something like 821 days (2 years with a ~90 day grace period). If your cert's "not valid before" and "not valid after" dates are farther apart than that, you should regenerate your cert with a validity period within the new limit.


text:
Q: Unable to find Lucene contrib jar in maven repository This is probably a very basic question, but I am unable to find Lucene contrib jar in Apache's Maven repository. For e.g. I looked here, but there's only a .pom, there's no jar file, same with repositories mentioned here.
Am I missing anything obvious?

A: You can download the jars for maven repositories in here: http://mvnrepository.com/artifact/org.apache.lucene/lucene-core/4.4.0
For the contrib package there is a .jar only for the 3.0.2 and not 3.0.3 (don't know why):
http://mvnrepository.com/artifact/org.apache.lucene/lucene-contrib
Also, you can still download de source code and generate the .jar yourself. Should be as easy as running mvn package.

A: I found out the answer. Except for couple of versions mentioned by Felipe Hummel, there is not single contrib jar. Contrib contains multiple components such as analyzers, highlighters, etc. and each of them have a JAR.


text:
Q: Emacs replacing require with autoload After profiling my Emacs init file, I saw that many of my modes are taking a long time to load, explaining why I've been having slow start times.
I am trying to use after-load or autoload to decrease the load time but have been unsuccessful in many modes.
For example, I have a mode called multiple-cursors.el that I downloaded manually and placed in my .emacs.d directory. Here is the code I have now:
;; Multiple Cursors
(add-to-list 'load-path "~/.emacs.d/multiple-cursors.el/")
(require 'multiple-cursors)
(global-set-key (kbd "C-c c") 'mc/edit-lines)
(global-set-key (kbd "C-c .") 'mc/mark-next-like-this)
(global-set-key (kbd "C-c ,") 'mc/mark-previous-like-this)
(global-set-key (kbd "C-c /") 'mc/mark-all-like-this)

I tried to replace the require line with (autoload 'multiple-cursors-mode "multiple-cursors.el" "Multiple cursors mode") but that did not work.
This format of the autoload seems to work well only with Melpa-installed packages. How can I do the equivalent for manually installed packages, such as the example above?

A: You need to write autoloads for the functions that you are actually calling through the key bindings (i.e. mc/edit-lines, mc/mark-next-like-this, mc/mark-previous-like-this and mc/mark-all-like-this), since that's how the loading of the file is triggered.  The autoloads need to refer to the files where the respective functions are defined, which is mc-edit-lines for mc/edit-lines, and mc-mark-more for the others.
So after setting the load path and binding the keys, add something like this:
(autoload 'mc/edit-lines "mc-edit-lines" "" t)
(autoload 'mc/mark-next-like-this "mc-mark-more" "" t)
(autoload 'mc/mark-previous-like-this "mc-mark-more" "" t)
(autoload 'mc/mark-all-like-this "mc-mark-more" "" t)


text:
Q: The all-powerful "to have" "To have" seems to fill a lot of different needs in the English language, apart from its literal meaning of possessing something.
It's an integral part of perfect and perfect progressive verb tenses: I have run, I had run, I had been running, I will have been running, etc.
It also indicates need: I have to eat, I had to leave (or is this another tense of some sort?)
This leads to forms of to have showing up multiple times in a sentence, and yet it makes perfect sense: I had to have had at least three apples.
How did this come about?  I've noticed avoir and tener also have these same uses in French & Spanish, respectively.

A: First, a little side note: To have in English (as in other languages such as French, Spanish, and Italian) is an auxiliary verb most commonly used for forming the simple/continuous perfect and pluperfect tenses, among others. The other mean example of an auxiliary verb is to be, which is used very similarly in other European languages. (To do is another, though rather more specific to English perhaps.)
As far as the history/origin of auxiliary verbs goes, in particular to have, I'm afraid I don't know - this is rather a specialty of a historical linguist. However, I can tell you that the use of auxiliary/compound verbs (certainly in forming various past tenses) was not apparent in Classical Latin, which utilized only word suffixes for changing verb mood and tense. Since however the use of the auxiliary to form the perfect and pluperfect tenses is present in the three main Romance languages of today (French, Spanish, Italian), this suggests that the origin most likely lies with Vulgar Latin, i.e. the vernacular tongue spoken during the late period of the Roman Empire and early Middle Ages, which evolved into the various modern Romance languages. Whether English developed this compound verb form (auxiliary + principal verb) independently via a Germanic route, I do not know, but it is quite possible that it inherited this form from Norman French.
Apologies for the bit of speculation, hopefully it provides some useful information, or perhaps at least a starting point for further research!

A: Have is one of the verbs of being. The verbs of being are:

*

*Be

*Am

*Is

*Are

*Was

*Were

*Being

*Been

*Have

*Has

*Had

*Shall

*Will

*May

*Can

*Might

*Could

*Should

*Would

The verbs of being are "special" in that they can exist as helper verbs when placed in a supporting position (I have gone to the show), and also as primary verbs when placed in a more normal position: (I have measles).
All of the verbs of being have a multitude of uses in English because they are used to convey state and changes of state, which exist quite often in real world scenarios.


text:
Q: Insufficient privileges when uploading to sonarqube.com I am trying to upload the sonar analysis for my open-source project to sonarqube.com but am getting Insufficient privileges:
[ERROR] Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.3.0.603:sonar (default-cli) on project metrics-transport-parent: Insufficient privileges -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.sonarsource.scanner.maven:sonar-maven-plugin:3.3.0.603:sonar (default-cli) on project metrics-transport-parent: Insufficient privileges
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:212)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
Caused by: org.apache.maven.plugin.MojoExecutionException: Insufficient privileges
    at org.sonarsource.scanner.maven.bootstrap.ExceptionHandling.handle(ExceptionHandling.java:36)
    at org.sonarsource.scanner.maven.bootstrap.ScannerBootstrapper.execute(ScannerBootstrapper.java:80)
    at org.sonarsource.scanner.maven.SonarQubeMojo.execute(SonarQubeMojo.java:139)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    ... 20 more
Caused by: Insufficient privileges

The following are the steps I have completed:

*

*Logged into sonarqube.com via github

*Generated a User-Token

*Added the following maven properties:
sonar.host.url=https://sonarqube.com
sonar.login=token

*Ran the build with sonar:sonar
Any help would be greatly appreciated.

A: You need to specify the organization into which you want to push your project - using the following parameter:
sonar.organization=...

Please note that this is described on the "Get Started" page:

A: In my case, the root cause was trying to upload the sonar result to non-existing git branch
-Dsonar.branch=NON_EXISTING_GIT_BRANCH

Hint:
sonar.branch is deprecated, and you should use sonar.branch.name


text:
Q: Bootstrap columns that don't scroll I have a webpage made with bootstrap, say i'm using 4 columns on the left and 6 on the right. I need for the 4 on the left to not scroll. How do I acheive this?
I know I can use
class="affix"

On the left column, but the problem with this is that the left column no longer resizes when the size of the viewport changes.

A: Here is a solution. You need to set overflow: auto and define nested div in the right column:

.cell {
  background: lightgreen;
  border: 1px solid teal;
  height: 100vh;
  overflow: auto;
}
.data_cont {
  height: 200vh;
  background: lightblue;
  margin: 0 -15px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

      left column

data in the right column


text:
Q: Extend MasterPage class in child page I am programming a website with ASP.NET/C#. I am using master pages for simplifying the layout design.
I have a BaseMasterPage.master master page, which has some code behind in an .master.cs file defining among others a BaseMasterPage class (extends System.Web.UI.MasterPage) and some methods in it (page_load,...). What I want to do, is to have a child page with an associated ChildPage class that extends BaseMasterPage, in order to reuse some of the methods in BaseMasterPage.
But this throws several errors. E.g ASP.child_aspx.GetTypeHashCode(): No matching method found for overwriting, same as for ASP.child_aspx.ProcessRequest(System.Web.HttpContext), ASP.login_aspx does not implement the field System.Web.IHttpHandler.IsReusable and so on.
I'm quite new to ASP.NET, so I guess it is just a beginner mistake... Could anybody tell me what I am doing wrong?
Thanks in advance for your answers.

A: Pages and MasterPages are different types of things. You are having problems because an ASPX page cannot inherit from System.Web.UI.MasterPage. It should ultimately inherit from System.Web.UI.Page.
So your plan of having both the master page and the content page (aspx) inherit from the same base class will not work.

A: I think you can define the class of your child page like this :
public partial class Default : ChildPageClass.
In your ChildPageClass :
public class ChildPageClass : YourMasterPageClass.
Can you try this ?
I'm not sure of this solution.


text:
Q: CKEditor 4 gives CKEDITOR not defined in react application I am using https://www.npmjs.com/package/react-ckeditor-component package to integrate ckeditor in my react app. This component provides props for custom ckeditor scripts. It works fine with default script. it works fine when I use cnd script.
Problem.
it does not works when I try to use my custom build script url. It gives CKEDITOR is not defined error in console. here is how I am using.
enter code here
<CKEditor
    activeClass="p10"
    scriptUrl={require('assets/ckeditor/ckeditor.js')}
    content={this.state.footerContent}
    events={{
           "change": this.onFooterChange
    }}
/>


text:
Q: Not sure why the data object is not passing through to the display function? So I have an object that contains information that has the ID, input value for a new task, date, and time.
The HTML element is for user input and to show where I am getting the information from.
HTML

        <input class ="user-input" type="text">
        <input class="date" type="date">
        <input class="time" type="time">
        <button onclick="addTask()" class="add" id="add">+</button>

JS
const el = {
  form: document.querySelector(".form"),
  input: document.querySelector(".user-input"),
  list: document.querySelector(".list"),
  date: document.querySelector(".date"),
  time: document.querySelector(".time"),
};

function makeNewTask() {

  const data = {

    id: createId(),
    taskNew: el.input.value,
    taskDate: el.date.value,
    taskTime: el.time.value,
  };

  return data

}
//function that creates new tasks with date and time
function display(data) {
  const tasks = document.createElement("div");

  tasks.innerHTML = `

${data.taskNew}

        ${data.taskDate}
        ${data.taskTime}

        <button onclick="editItem()" class="edit" data-id="${data.id}">Edit</button>
        <button onclick="deleteItem()" class="delete" data-id="${data.id}">Delete</button>
        <button onclick="completeItem()" class="complete" data-id="${data.id}">Complete</button>

`;

  taskList.push(data);
  el.list.appendChild(tasks);
  makeNewTask();
}

// this function is the add the task
function addTask() {
  display();
}

The End goal is to figure out why the data object is not being passed into the new function when I returned the data in the makeNewTask() and add the callback function of makeNewTask() to display(data)
I have also added a picture of the error I am getting, and by that error, the data object is not being passed through to the display function where you can see the ```data.id`` etc. that is where the information is meant to go and print on the screen. when the user clicks on the add task button

A: Your display function was having empty parameter inside addTask() function and createID() was not defined. so I modified it to fix the issue as follows:

*

*Added createID() function, taskList and currentId vars.

*Explicitely call makeNewTask() inside display() and remove existing declaration ot the makeNewTask() function from bottom.

*Added div to view the tasks

HTML:

  <input class="user-input" type="text" />
  <input class="date" type="date" />
  <input class="time" type="time" />
  <button onclick="addTask()" class="add" id="add">+</button>

JS:
  var taskList = [];
  var currentID = 0;
  function createId() {
    currentID++;
    return currentID;
  }
  const el = {
    form: document.querySelector(".form"),
    input: document.querySelector(".user-input"),
    list: document.querySelector(".list"),
    date: document.querySelector(".date"),
    time: document.querySelector(".time"),
  };

  function makeNewTask() {
    const data = {
      id: createId(),
      taskNew: el.input.value,
      taskDate: el.date.value,
      taskTime: el.time.value,
    };

    return data;
  }
  //function that creates new tasks with date and time
  function display() {
    const tasks = document.createElement("div");
    data = makeNewTask();
    tasks.innerHTML = `

${data.taskNew}

    ${data.taskDate}
    ${data.taskTime}

    <button onclick="editItem()" class="edit" data-id="${data.id}">Edit</button>
    <button onclick="deleteItem()" class="delete" data-id="${data.id}">Delete</button>
    <button onclick="completeItem()" class="complete" data-id="${data.id}">Complete</button>

`;

    taskList.push(data);
    el.list.appendChild(tasks);
  }

  // this function is the add the task
  function addTask() {
    display();
  }

Now, addTask() should work. Hope that helps!


text:
Q: Python sqlite3 string formatting I have a function like this:
def func(self, id):
    self.cursor.execute("SELECT * FROM my_table WHERE id=?", (id,))

This works when I pass an integer value in id:
obj.func(id=55)

Now I might want to reuse this function like so:
obj.func(id="associated_id")

Where associated_id is actually a second column in my_table. However this doesn't work (it finds no results even though there is a row where id==associated_id).
It works if I change the function like so:
def func(self, id):
    self.cursor.execute("SELECT * FROM my_table WHERE id=%s" % str(id))

Why does the first version not work? Is there any way to solve this problem using sqlite3.execute parameters instead of native python string formatting?

A: In the first case you are doing parameter binding. Which is correct, sqlite libraries will bind the value 55 to the query call. In the second case you should not use parameter binding because the sql will be something equivalent to:
SELECT * FROM my_table WHERE id='associated_id'

Because the binding call detects that you are passing a string and then it treats it internally like a string.
When you do
"SELECT * FROM my_table WHERE id=%s" % str(id)

You don't do parameter binding but simply pass the SQL as it is to sqlite.
Some documentation on parameter binding in:
http://www.sqlite.org/c3ref/bind_blob.html

A: The "?" in SQL represents a value to be provided when the query executes, such as "55".
"associated_id" is the name of a column in the table, if you pass it in via the "?" placeholder then it will be treated a string. There is no way for the database to recognize this as a column name.


text:
Q: embed video in html? I want to embed a video in an asp page. I am using this code
<embed autoplay="false" controller="true" loop="false" name="JF Video"
pluginspage="http://www.apple.com/quicktime/download/"
src="https://www.anylink.com/english/video/videoname.mp4" height="250" border="1" width="320">

problem is that autoplay=false is not working as is starts playing automatically as page loads and this video is not getting played in firefox ? I have wasted more than 5 hours in it.
What is the solution of this problem and if there is any other better way to play video in asp web page [no html5 tag], please let me know.
Thanks in advance.

A: Make use of the object tag and replace your code with this.
<object name="Video" classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/quicktime/download/" standby="Loading Quicktime components..." width="400" height="200" > <param name="src" value="https://www.anylink.com/english/video/videoname.mp4"></param> <param name="autoplay" value="false"></param> <param name="controller" value="true"></param> <param name="enablejavascript" value="true"></param> <param name="playCount" value="1"></param> <param name="starttime" value="0"></param> <embed name="Video" pluginspage="http://www.apple.com/quicktime/download/" type="video/quicktime" src="https://www.anylink.com/english/video/videoname.mp4" autoplay="false" controller="true" enablejavascript="true" starttime="0" width="400" height="200"></embed> </object>


text:
Q: can't post data via ajax call I'm trying to post to the controller some data that I retrieve from the form. Here is my form:

<form id="hourForm" name="hourForm"  >
//first part of the form -----

//second part:

                        <?php
                           for ($i=0 ; $i<3; $i++){
                   echo '

                      <input type=hidden id="date'.$i.'" name="date'.$i.'" value=""/>

                      <input type=text name="action'.$i.'"  placeholder="Votre action" value=""/>
                      <input type="text" name="temps'.$i.'"  placeholder="nombre heures" value=""/>

 ';}
                echo '  <input type=hidden id="dateTest" name="dateTest" value=""/>  '; // just to test
                  ?>

  </form>

Firebug shows that date0, date1 and date2 are empty but dateTest is not.
Here is how I set my variables ( js function)
         for (var i = 0; i < 3; i++) {

              $('#date'+i).html('myVariable');
              $('#date'+i).val('myVariable');
                 }
              $('#dateTest').val('dateTest');

And here is how I post the data to the controller :
function insert_hour() {
         var form_values= $('#hourForm').serialize();
         alert($('#date0').val());// prints the correct value also for date1 and date2

         $.ajax({
            type:'POST',
                url : '<?php echo site_url()."/path/to/controller/"; ?>',
            data : form_values,

            success:function(data)
                {   alert(' ajax_call ok ');
                }

            });

}

A: I think you are doing here wrong

      and

<input type=hidden id="date'.$i.'" name="date'.$i.'" value=""/>

In this case $('#date'+i).html('myVariable'); Will not work

You are using same id.Id must be unique.


text:
Q: Issue In Installing Azure IoT Python SDK I am trying to install azure-iot-sdk python but according to but when I am trying to build my device I have to face the crash error at 92% as mentioned below:

If someone knows about the alternative to avoid this error,
your suggestion will be much valuable
For tutorial reference, mentioned below are the site links which I am using
https://github.com/Azure/azure-iot-sdk-python
https://github.com/Azure/azure-iot-sdk-python/blob/master/doc/python-devbox-setup.md#linux


text:
Q: ActionView::Template::Error (Webpacker can't find application in /app/public/packs/manifest.json i've tried many suggestions and answers from all around the web and something is just missing.
I keep getting the above error while trying to open my app (which works perfectly locally) on Heroku.
I've followed the standard instructions for deploying an app using git and heroku cli.
I have pushed everything to heroku but while trying to visit my site via the html i keep getting "We're sorry, but something went wrong." and the console shows this error:
2020-09-22T12:29:49.151911+00:00 heroku[router]: at=info method=GET path="/" host=thawing-retreat-03527.herokuapp.com request_id=eac8d868-4c14-4c1d-be40-0741778518c7 fwd="83.130.59.73" dyno=web.1 connect=0ms service=27ms status=500 bytes=1827 protocol=https
2020-09-22T12:29:49.410973+00:00 heroku[router]: at=info method=GET path="/favicon.ico" host=thawing-retreat-03527.herokuapp.com request_id=3b73846f-7d13-4159-b33b-be26db60b209 fwd="83.130.59.73" dyno=web.1 connect=0ms service=6ms status=200 bytes=143 protocol=https
2020-09-22T12:53:00.330777+00:00 app[web.1]: I, [2020-09-22T12:53:00.330645 #4]  INFO -- : [9d66d3df-99bc-4899-93d2-a203bddc9291] Started GET "/" for 83.130.59.73 at 2020-09-22 12:53:00 +0000
2020-09-22T12:53:00.332093+00:00 app[web.1]: I, [2020-09-22T12:53:00.332025 #4]  INFO -- : [9d66d3df-99bc-4899-93d2-a203bddc9291] Processing by PagesController#about as HTML
2020-09-22T12:53:00.334335+00:00 app[web.1]: I, [2020-09-22T12:53:00.334265 #4]  INFO -- : [9d66d3df-99bc-4899-93d2-a203bddc9291]   Rendering pages/about.html.erb within layouts/application
2020-09-22T12:53:00.335195+00:00 app[web.1]: I, [2020-09-22T12:53:00.335130 #4]  INFO -- : [9d66d3df-99bc-4899-93d2-a203bddc9291]   Rendered pages/about.html.erb within layouts/application (Duration: 0.7ms | Allocations: 141)
2020-09-22T12:53:00.336616+00:00 app[web.1]: I, [2020-09-22T12:53:00.336554 #4]  INFO -- : [9d66d3df-99bc-4899-93d2-a203bddc9291] Completed 500 Internal Server Error in 4ms (Allocations: 839)
2020-09-22T12:53:00.338353+00:00 app[web.1]: F, [2020-09-22T12:53:00.338286 #4] FATAL -- : [9d66d3df-99bc-4899-93d2-a203bddc9291]
2020-09-22T12:53:00.338354+00:00 app[web.1]: [9d66d3df-99bc-4899-93d2-a203bddc9291] ActionView::Template::Error (Webpacker can't find application in /app/public/packs/manifest.json. Possible causes:
2020-09-22T12:53:00.338357+00:00 app[web.1]: 1. You want to set webpacker.yml value of compile to true for your environment
2020-09-22T12:53:00.338357+00:00 app[web.1]: unless you are using the `webpack -w` or the webpack-dev-server.
2020-09-22T12:53:00.338358+00:00 app[web.1]: 2. webpack has not yet re-run to reflect updates.
2020-09-22T12:53:00.338359+00:00 app[web.1]: 3. You have misconfigured Webpacker's config/webpacker.yml file.
2020-09-22T12:53:00.338359+00:00 app[web.1]: 4. Your webpack configuration is not creating a manifest.
2020-09-22T12:53:00.338360+00:00 app[web.1]: Your manifest contains:
2020-09-22T12:53:00.338361+00:00 app[web.1]: {
2020-09-22T12:53:00.338362+00:00 app[web.1]: }
2020-09-22T12:53:00.338362+00:00 app[web.1]: ):
2020-09-22T12:53:00.338363+00:00 app[web.1]: [9d66d3df-99bc-4899-93d2-a203bddc9291]      6:     <%= csp_meta_tag %>
2020-09-22T12:53:00.338364+00:00 app[web.1]: [9d66d3df-99bc-4899-93d2-a203bddc9291]      7:
2020-09-22T12:53:00.338365+00:00 app[web.1]: [9d66d3df-99bc-4899-93d2-a203bddc9291]      8:     <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
2020-09-22T12:53:00.338365+00:00 app[web.1]: [9d66d3df-99bc-4899-93d2-a203bddc9291]      9:     <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
2020-09-22T12:53:00.338366+00:00 app[web.1]: [9d66d3df-99bc-4899-93d2-a203bddc9291]     10:   </head>
2020-09-22T12:53:00.338366+00:00 app[web.1]: [9d66d3df-99bc-4899-93d2-a203bddc9291]     11:
2020-09-22T12:53:00.338367+00:00 app[web.1]: [9d66d3df-99bc-4899-93d2-a203bddc9291]     12:   <body>
2020-09-22T12:53:00.338367+00:00 app[web.1]: [9d66d3df-99bc-4899-93d2-a203bddc9291]
2020-09-22T12:53:00.338368+00:00 app[web.1]: [9d66d3df-99bc-4899-93d2-a203bddc9291] app/views/layouts/application.html.erb:9

I think I made a mistake while making this app bootstrap friendly. Or maybe something is wrong with my files.. I'm truly lost at this point.
These are my files:
package.json:
{
  "name": "project",
  "private": true,
  "dependencies": {
    "@rails/actioncable": "^6.0.0",
    "@rails/actiontext": "^6.0.3-2",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "4.3.0",
    "bootstrap": "^4.5.2",
    "jquery": "^3.5.1",
    "popper.js": "^1.16.1",
    "trix": "^1.2.0",
    "turbolinks": "^5.2.0",
    "webpack": "^4.0.0"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.11.0"
  }
}

application.js:
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)
require("trix")
require("@rails/actiontext")

//= require jquery3
//= require popper
//= require bootstrap
import 'bootstrap'
import '../stylesheets/style'

style.scss:
    @import "bootstrap";

webpacker.yml:
# Note: You must restart bin/webpack-dev-server for changes to take effect

default: &default
  source_path: app/javascript
  source_entry_path: packs
  public_root_path: public
  public_output_path: packs
  cache_path: tmp/cache/webpacker
  check_yarn_integrity: false
  webpack_compile_output: true

  # Additional paths webpack should lookup modules
  # ['app/assets', 'engine/foo/app/assets']
  resolved_paths: []

  # Reload manifest.json on all requests so we reload latest compiled packs
  cache_manifest: false

  # Extract and emit a css file_
  extract_css: false

  static_assets_extensions:
    - .jpg
    - .jpeg
    - .png
    - .gif
    - .tiff
    - .ico
    - .svg
    - .eot
    - .otf
    - .ttf
    - .woff
    - .woff2

  extensions:
    - .mjs
    - .js
    - .sass
    - .scss
    - .css
    - .module.sass
    - .module.scss
    - .module.css
    - .png
    - .svg
    - .gif
    - .jpeg
    - .jpg

development:
  <<: *default
  compile: true

  # Verifies that correct packages and versions are installed by inspecting package.json, yarn.lock, and node_modules
  check_yarn_integrity: true

  # Reference: https://webpack.js.org/configuration/dev-server/
  dev_server:
    https: false
    host: localhost
    port: 3035
    public: localhost:3035
    hmr: false
    # Inline should be set to true if using HMR
    inline: true
    overlay: true
    compress: true
    disable_host_check: true
    use_local_ip: false
    quiet: false
    pretty: false
    headers:
      'Access-Control-Allow-Origin': '*'
    watch_options:
      ignored: '**/node_modules/**'

test:
  <<: *default
  compile: true

  # Compile test packs to a separate directory
  public_output_path: packs-test

production:
  <<: *default

  # Production depends on precompilation of packs prior to booting for performance.
  compile: false

  # Extract and emit a css file
  extract_css: true

  # Cache manifest.json for performance
  cache_manifest: true

application.html.erb:
// This file is automatically compiled by Webpack, along with any other files
// present in this directory. You're encouraged to place your actual application logic in
// a relevant structure within app/javascript and only use these pack files to reference
// that code so it'll be compiled.

require("@rails/ujs").start()
require("turbolinks").start()
require("@rails/activestorage").start()
require("channels")

// Uncomment to copy all static images under ../images to the output folder and reference
// them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
// or the `imagePath` JavaScript helper below.
//
// const images = require.context('../images', true)
// const imagePath = (name) => images(name, true)
require("trix")
require("@rails/actiontext")

//= require jquery3
//= require popper
//= require bootstrap
import 'bootstrap'
import '../stylesheets/style'

Gemfile:
source 'https://rubygems.org'
git_source(:github) { |repo| "https://github.com/#{repo}.git" }

ruby '2.7.1'

# Bundle edge Rails instead: gem 'rails', github: 'rails/rails'
gem 'rails', '~> 6.0.3', '>= 6.0.3.2'
# Use sqlite3 as the database for Active Record
group :development do
   gem 'sqlite3', '~> 1.4'
end

group :test, :production do
    gem 'pg'
end
# Use Puma as the app server
gem 'puma', '~> 4.1'
# Use SCSS for stylesheets
gem 'sass-rails', '>= 6'
# Transpile app-like JavaScript. Read more: https://github.com/rails/webpacker
gem 'webpacker', '~> 4.0'
# Turbolinks makes navigating your web application faster. Read more: https://github.com/turbolinks/turbolinks
gem 'turbolinks', '~> 5'
# Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder
gem 'jbuilder', '~> 2.7'
# Use Redis adapter to run Action Cable in production
# gem 'redis', '~> 4.0'
# Use Active Model has_secure_password
# gem 'bcrypt', '~> 3.1.7'

# Use Active Storage variant
 gem 'image_processing', '~> 1.2'

#### custom gem area
gem 'bootstrap', '~> 5.0.0.alpha1'
gem 'sprockets-rails', :require => 'sprockets/railtie'
gem 'jquery-rails'

gem 'devise'
gem 'simple_form'
gem 'faker'
gem 'will_paginate'
gem 'validates_timeliness', '~> 5.0.0.beta1'
gem 'solargraph', group: :development
gem 'rubocop', group: :development
####

# Reduces boot times through caching; required in config/boot.rb
gem 'bootsnap', '>= 1.4.2', require: false

group :development, :test do
  # Call 'byebug' anywhere in the code to stop execution and get a debugger console
  gem 'byebug', platforms: [:mri, :mingw, :x64_mingw]
end

group :development do
  # Access an interactive console on exception pages or by calling 'console' anywhere in the code.
  gem 'web-console', '>= 3.3.0'
  gem 'listen', '~> 3.2'
  # Spring speeds up development by keeping your application running in the background. Read more: https://github.com/rails/spring
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
end

group :test do
  # Adds support for Capybara system testing and selenium driver
  gem 'capybara', '>= 2.15'
  gem 'selenium-webdriver'
  # Easy installation and use of web drivers to run system tests with browsers
  gem 'webdrivers'
end

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem 'tzinfo-data', platforms: [:mingw, :mswin, :x64_mingw, :jruby]

Manifest.json:
{
  "application.js": "/packs/js/application-0da4851a98444f0352a0.js",
  "application.js.map": "/packs/js/application-0da4851a98444f0352a0.js.map",
  "entrypoints": {
    "application": {
      "js": [
        "/packs/js/application-0da4851a98444f0352a0.js"
      ],
      "js.map": [
        "/packs/js/application-0da4851a98444f0352a0.js.map"
      ]
    }
  }
}


text:
Q: Can't declare an object in *ngFor iterator of Angular I'm using the following code to iterate a bunch of custom controls. Since those need to know some stuff, like index and position in the structure, I'm passing in a config object to keep the junk together like this.
<div *ngFor="let thing of stuff; let first=first; let last=last; let index = index;">
  <app-thingy [data]="thing"
              [config]="{first:first,last:last,index:index}">
  </app-thingy>
</div>

I'd prefer to keep the code more compact and it seems like a very repetitive syntax with let this and let that. So I figured that I could create the object straight off in the iterative tag like this.
<div *ngFor="let thing of stuff; let config={first:first,last:last,index:index};">
  <app-thingy [data]="thing"
              [config]="config">
  </app-thingy>
</div>

However, Angular barks at this claiming that the curly bracket in the definition of config is an invalid syntax.

Uncaught Error: Template parse errors:
  Parser Error: Unexpected token {, expected identifier, keyword, or string at column 45 in [let thing of stuff; let config={first:first,last:last,index:index};] in
  ...
  <div [ERROR ->]*ngFor="let thing of stuff; let config=

As far I can goolearch it, the syntax is wrong but I can't see why. Can someone, please, shed some light on why those two samples aren't equivalent?
I noticed that using new MyType(...) in the HTML markup isn't working neither but that's apparently by design. However, this is a anonymous object (type any) so I'm a bit puzzled.

A: You cannot declare an object using let inside the component.html
WRONG
<div *ngFor="let thing of stuff; let config={first:first,last:last,index:index};">

Instead you can create the object in ts and pass it in the HTML

A: This is wrong
<div *ngFor="let thing of stuff; let config={first:first,last:last,index:index};">
  <app-thingy [data]="thing"
              [config]="config">
  </app-thingy>
</div>

Because first:first,last:last,index:index referencing to loop condition, they are not handled as objects. You can understand it as  for loop in javascript like
for(let i=0; i<somelength ;i++){}

like i=0 is equal to first:first and somelength equals last:last and i as index:index. They can't be passed like above.


text:
Q: No Suitable Driver found Postgres JDBC I am receiving a "no suitable driver found" error when I test my web service on tomcat. I have the JDBC .jar in the lib folder as various tutorials says to do. Here is my code:
public class PostDBConnection {

 PreparedStatement st;
 ResultSet rs;
 Connection con;
 DataSource ds;
 InitialContext cxt;

 String url = "jdbc:postgresql://127.0.0.1:5432/UptonDB";
 String user = "*****";
 String password = "*******";
 String query = "";
 StringBuilder response = new StringBuilder();

@SuppressWarnings("unused")
public String getInfo(){

    int size = 0;

    try {

        cxt = new InitialContext();
        ds = (DataSource) cxt.lookup("java:comp/env/jdbc/UptonDB");

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    try{

        try {

            Class.forName("org.postgres.Driver");

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        con = DriverManager.getConnection(url, user, password);
        st =  con.prepareStatement("SELECT VERSION()");
        rs = st.executeQuery();

        while(rs.next())
            {
                    response.append(rs.getString(1));

            }
        }

    catch(SQLException exc)
        {
            Logger lgr = Logger.getLogger(PostDBConnection.class.getName());
            lgr.log(Level.SEVERE, exc.getMessage(), exc);
        }
    finally {
        try {
           if (rs != null) {
                rs.close();
            }
            if (st != null) {
                st.close();
            }
            if (con != null) {
                con.close();
            }

        } catch (SQLException ex) {
            Logger lgr = Logger.getLogger(PostDBConnection.class.getName());
            lgr.log(Level.WARNING, ex.getMessage(), ex);
        }
    }

    return response.toString();
}

Also here are the web.xml and context.xml files I created by following instructions on the Tomcat website:
 <resource-ref>
<description>PostgreSQL Data Source </description>
<res-ref-name>jdbc/UptonDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

web.xml:
   <?xml version="1.0" encoding="UTF-8"?>
   <Context>
   <Resource name="jdbc/UptonDB" auth="Container" type="javax.sql.DataSource"
    removeAbandoned="true" removeAbandonedTimeout="30" maxActive="80"
    maxIdle="30" maxWait="10000" username="*****" password="*******"
    driverClassName="org.postgresql.Driver"
    url = "jdbc:postgresql://127.0.0.1:5432/UptonDB" useUnicode="true"
    characterEncoding="utf-8" characterSetResults="utf8"/>
   </Context>

Any help is appreciated thanks!

A: The proper Driver name is: org.postgresql.Driver and not org.postgres.Driver
Update:
Check this page give it a bit os study and you should be fine
:)
http://tomcat.apache.org/tomcat-6.0-doc/jndi-datasource-examples-howto.html
Than instead of using DriverManager, you should just do a lookup(you did already) and than get a connection from the DataSource(You can remove pwd, user, and other unused stuff from your code):
Context initContext = new InitialContext();
Context envContext  = (Context)initContext.lookup("java:/comp/env");
DataSource ds = (DataSource)envContext.lookup("jdbc/UptonDB");
Connection conn = ds.getConnection();


text:
Q: Kafka Username password authentication Issue I am using Apache kafka version 2. I am trying to implement authentication for Kafka using Username and password(SASL_PLAINTEXT).I am following below link to implement the same.
https://developer.ibm.com/hadoop/2017/04/10/kafka-security-mechanism-saslplain/
I have changed the configuration based on above url. But I am getting below error.
java.lang.IllegalArgumentException: Could not find a 'KafkaServer' or 'sasl_plaintext.KafkaServer' entry in the JAAS configuration. System property 'java.security.auth.login.config' is /usr/hdp/current/kafka-broker/config/kafka_jaas.conf

A: Try to export kafka_opts.
export KAFKA_OPTS="-Djava.security.auth.login.config=/usr/hdp/current/kafka-broker/config/kafka_jaas.conf"


text:
Q: difference between single double and three phase If single phase is 230 V and 3 phase is 440 v then what about for 2 phase?
And why is it so?

A: The 230 V is phase-to-ground voltage. 400 V (not 440) is phase-to-phase voltage, because 230 * sqrt(3) = 400.
For two-phase system eg. 100 V the phase-to-phase would be sqrt(2) * 100 V, because phases differ in angle of 90 degrees and you can calculate this from Pythagorean theorem.

A: Here is what wikipedia says about two-phase power.

Two-phase electrical power was an early 20th century polyphase
  alternating current electric power distribution system. Two circuits
  were used, with voltage phases differing by 90 degrees. Usually
  circuits used four wires, two for each phase. Less frequently, three
  wires were used, with a common wire with a larger-diameter conductor.
  Some early two-phase generators had two complete rotor and field
  assemblies, with windings physically offset by 90 electrical degrees
  to provide two-phase power. The generators at Niagara Falls installed
  in 1895 were the largest generators in the world at the time and were
  two-phase machines.
The advantage of two-phase electrical power was that it allowed for
  simple, self-starting electric motors. In the early days of electrical
  engineering, it was easier to analyze and design two-phase systems
  where the phases were completely separated. It was not until the
  invention of the method of symmetrical components in 1918 that
  polyphase power systems had a convenient mathematical tool for
  describing unbalanced load cases. The revolving magnetic field
  produced with a two-phase system allowed electric motors to provide
  torque from zero motor speed, which was not possible with a
  single-phase induction motor (without extra starting means). Induction
  motors designed for two-phase operation use the same winding
  configuration as capacitor start single-phase motors.

Single phase and 3 phase are unrelated to 2 phase described above. Basically, 3 phase is what the power stations produce now and ultimately this gets distributed as 3 single phases to our homes: -

There are three line voltages shown in red that are 120º apart in phase orientation. This can be seen as three single phase voltages (blue) and if you did the trigonometry you'd see that the length of red is sqrt(3) times bigger than the length of blue hence, if you have 230V phase voltage, the line voltage would be 398V. Here's how the voltages look in time: -

Going back a few years when the UK had 240V, the line voltage was 415V and sometimes 440V line voltages were referred to ans they yielded a phase voltage of 250V.

A: Voltage is measured relatively from a point. You cannot say how much voltage is passing through a point, instead you may say how much more voltage a point has than any other point.
Here in single phase, where you are supplied with a neutral wire and a phase wire, if you measure the voltage between the phase and the neutral, it would be 230 V.
But in the case of three phases, where you are supplied with three phase wires and a single neutral wire, if you measure the voltage between phase to neutral it would still be 230 V.
And if you measure the voltage between any two of the phase wires you would get 440 398 V.
Thanks @Transistor for the correction.


text:
Q: How to make 'post' HTTP request in Swift? I've a log in page in my app in which I'm doing authentication and making a post request.
I'll be grabbing the token from the API that I'm provided with.
However, my code isn't printing anything on the print log. Please help!!
    @IBAction func submit(sender: AnyObject) {

//creating a function that will connect to API

        func connectToWebAPI(){

//setting up the base64-encoded credentials
        let userName = "user"
        let password = "pass"
        let loginString = NSString(format: "%@:%@", userName, password)
        let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
        let base64LoginString = loginData.base64EncodedStringWithOptions(nil)

//creating the request
        let url = NSURL(string: "http://www.telize.com/geoip")
        var request = NSMutableURLRequest(URL: url!)
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession.sharedSession()
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        let urlConnection = NSURLConnection(request: request, delegate: self)
        request.HTTPMethod = "POST"
        request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")

        let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in
        if (error != nil) {
                    println(error)

        }
        else {

// converting the data into Dictionary

        let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary

        println(jsonResult)

                }
            })

//fire off the request

        task.resume()

        }

A: A couple of issues:

*

*First, you're using both NSURLConnection and NSURLSession. This means that you're actually performing the request twice. Nowadays, with NSURLConnection being deprecated soon, you should eliminate NSURLConnection portion of this code snippet and use just NSURLSession.

*Second, when parsing the JSON, you've explicitly told it to not report any error (you set error parameter to nil). You should actually look at the error, if any:
var parseError: NSError?
if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSDictionary {
    println("jsonResult = \(jsonResult)")
} else {
    // if it didn't work, show enough so we can figure out why:

    println("parseError = \(parseError)")
    println("response = \(response)")
    let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
    println("responseString = \(responseString)") // this will probably be HTML from the server describing some problem in the request
}

Usually these sorts of requests fail because of something wrong with how the original NSURLRequest was created, but you are not showing us enough information source of the problem.

A: Here's the final code for anyone looking for an answer.
//setting up the base64-encoded credentials
        let userName = "user"
        let password = "pass"
        let loginString = NSString(format: "%@:%@", userName, password)
        let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
        let base64LoginString = loginData.base64EncodedStringWithOptions(nil)

//creating the request
        let url = NSURL(string: "http://www.telize.com/geoip")
        var request = NSMutableURLRequest(URL: url!)
        let config = NSURLSessionConfiguration.defaultSessionConfiguration()
        let session = NSURLSession.sharedSession()
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPMethod = "POST"
        request.setValue(base64LoginString, forHTTPHeaderField: "Authorization")

        let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

            var parseError: NSError?

        if let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &parseError) as? NSDictionary {
        println("jsonResult = \(jsonResult)")

        }
        else {
        //if this didn't work, show enough so we can figure out why:
            println("parseError = \(parseError)")
            println("response = \(response)")
            let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("responseString = \(responseString)")

            }
            })

//fire off the request

        task.resume()

        }


text:
Q: Make object accessible outside JavaScript fetch function My project to compare two cities weather
my problem that I can't access the objects outside the fetch function call
my object
submitBtn.addEventListener("click", function () {
  // getting user data
  resultArea.innerHTML = "";

  loadingSec.style.display = "block";
  const firstCityName = document.getElementById("firstCityName");
  const secondCityName = document.getElementById("secondCityName");
  // inilize arrays for strong city weather daya for 8 days
  const firstCitydata = new Array();
  let secondCitydata = [];
  // get request date and calulte 8 days bevore and store it in dates array
  const dates = req_dates();
  let currentReq = [new HisCityDayWeather(), new HisCityDayWeather()];
  //fetch each day wether data
  for (let i = 0; i < dates.length; i++) {
    // first city fetch function call

    getData(firstCityName.value, dates[i]).then((data) => {
      currentReq[0].name = data.location.name;
      currentReq[0].day.push(data.forecast.forecastday[0].day);
      currentReq[0].date.push(data.forecast.forecastday[0].date);
    });

    getData(secondCityName.value, dates[i]).then((data) => {
      currentReq[1].name = data.location.name;
      currentReq[1].day.push(data.forecast.forecastday[0].day);
      currentReq[1].date.push(data.forecast.forecastday[0].date);
      stor_in_array(currentReq);
    });
  }
  function stor_in_array(citydata) {
    console.log(
      `store function call first ctiy length: ${citydata[0].day.length} second ctiy length: ${citydata[1].day.length}`
    );

    if (citydata[1].day.length === 8 && citydata[0].day.length === 8) {
      console.log(`call complte`);

      loadingSec.style.display = "none";

      build_3Row_table(dates, citydata[0], citydata[1]);
    }
  }
});

This the only way my code kind of work but I have to call the function "stor_in_array" 8 times
if the first fetch call didn't finish before the second one the the condition inside "stor_in_array" doesn't get passed
If I tried to call the function pillow the for loop I can't access the arraay
the fetch function
async function getData(cityName, date) {
  try {
    let response = await fetch(
      `https://api.weatherapi.com/v1/history.json?key=${wKey}&q=${cityName}&dt=${date}`
    );
    let data = await response.json();
    if (response.ok) {
      return data;
    } else {
      return data["error"]["code"];
    }
  } catch (err) {
    console.log(err);
  }
}

github repo: here
project on netifly: here when trying check the network and press compare two times the second always work if you enter the names right
note: I know there a lot of work should be done I Validation I am still working on


text:
Q: Error en mostrar una snackBar en onRequestPermissionsResult Como se puede usar un snackbar dentro de onRequestPermissionsResult como necesita de una vista le asigno con findViewById(R.id.root_view)
@Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    Snackbar.make(findViewById(R.id.root_view), getString(R.string.permission_request_advice),
            Snackbar.LENGTH_LONG)
            .setAction(getString(R.string.permission_settings), new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    PermissionUtils.openInstalledAppDetailsActivity(RouteActivity.this);
                }
            })
            .show();

}

Me da el siguiente error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.view.ViewGroup.getContext()' on a null object reference

A: El problema es definitivamente el contexto.
Te sugiero obtener la vista root de esta forma:
 View rootView = getWindow().getDecorView().getRootView();

y usarla en tu Snackbar:
Snackbar.make(rootView, getString(R.string.permission_request_advice),
            Snackbar.LENGTH_LONG)
            .setAction(getString(R.string.permission_settings), new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    PermissionUtils.openInstalledAppDetailsActivity(RouteActivity.this);
                }
            })
            .show();


text:
Q: Logic flaw in trie search I'm currently working on a trie implementation for practice and have run into a mental roadbloack.
The issue is with my searching function. I am attempting to have my trie tree be able to retrieve a list of strings from a supplied prefix after they are loaded into the programs memory.
I also understand I could be using a queue/shouldnt use C functions in C++ ect.. This is just a 'rough draft' so to speak.
This is what I have so far:
bool SearchForStrings(vector<string> &output, string data)
{
    Node *iter = GetLastNode("an");
    Node *hold = iter;
    stack<char> str;

    while (hold->visited == false)
    {
        int index = GetNextChild(iter);
        if (index > -1)
        {
            str.push(char('a' + index));
            //current.push(iter);
            iter = iter->next[index];
        }
        //We've hit a leaf so we want to unwind the stack and print the string
        else if (index < 0 && IsLeaf(iter))
        {
            iter->visited = true;
            string temp("");
            stringstream ss;

            while (str.size() > 0)
            {
                temp += str.top();

                str.pop();
            }

            int i = 0;
            for (std::string::reverse_iterator it = temp.rbegin(); it != temp.rend(); it++)
                ss << *it;

            //Store the string we have
            output.push_back(data + ss.str());
            //Move our iterator back to the root node
            iter = hold;
        }
        //We know this isnt a leaf so we dont want to print out the stack
        else
        {
            iter->visited = true;
            iter = hold;
        }

    }
    return (output.size() > 0);

}

int GetNextChild(Node *s)
{

    for (int i = 0; i < 26; i++)
    {
        if (s->next[i] != nullptr && s->next[i]->visited == false)
            return i;
    }

    return -1;
}

bool IsLeaf(Node *s)
{
    for (int i = 0; i < 26; i++)
    {
        if (s->next[i] != nullptr)
            return false;
    }

    return true;
}
struct Node{
int value;
Node *next[26];
bool visited;

};

The code is too long or i'd post it all, GetLastNode() retrieves the node at the end of the data passed in, so if the prefix was 'su' and the string was 'substring' the node would be pointing to the 'u' to use as an artificial root node

A: (might be completely wrong... just typed it here, no testing)
something like:
First of all, we need a way of indicating that a node represents an entry.
So let's have:
struct Node{
    int value;
    Node *next[26];
    bool entry;
};

I've removed your visited flag because I don't have a use for it.
You should modify your insert/update/delete functions to support this flag. If the flag is true it means there's an actual entry up to that node.
Now we can modify the
bool isLeaf(Node *s) {
    return s->entry;
}

Meaning that we consider a leaf when there's an entry... perhaps the name is wrong now, as the leaf might have childs ("y" node with "any" and "anywhere" is a leaf, but it has childs)
Now for the search:
First a public function that can be called.
bool searchForStrings(std::vector<string> &output, const std::string &key) {
    // start the recursion
    // theTrieRoot is the root node for the whole structure
    return searchForString(theTrieRoot,output,key);
}

Then the internal function that will use for recursion.
bool searchForStrings(Node *node, std::vector<string> &output, const std::string &key) {
    if(isLeaf(node->next[i])) {
        // leaf node - add an empty string.
        output.push_back(std::string());
    }

    if(key.empty()) {
        // Key is empty, collect all child nodes.
        for (int i = 0; i < 26; i++)
        {
            if (node->next[i] != nullptr) {
                std::vector<std::string> partial;
                searchForStrings(node->next[i],partial,key);
                // so we got a list of the childs,
                // add the key of this node to them.
                for(auto s:partial) {
                    output.push_back(std::string('a'+i)+s)
                }
           }
       } // end for
   } // end if key.empty
   else {
       // key is not empty, try to get the node for the
       // first character of the key.
       int c=key[0]-'a';
       if((c<0 || (c>26)) {
           // first character was not a letter.
           return false;
        }
        if(node->next[c]==nullptr) {
           // no match (no node where we expect it)
           return false;
        }
        // recurse into the node matching the key
        std::vector<std::string> partial;
        searchForStrings(node->next[c],partial,key.substr(1));
        // add the key of this node to the result
        for(auto s:partial) {
            output.push_back(std::string(key[0])+s)
        }
    }
    // provide a meaningful return value
    if(output.empty()) {
       return false;
    } else {
       return true;
    }
}

And the execution for "an" search is.

*

*Call searchForStrings(root,[],"an")

*

*root is not leaf, key is not empty. Matched next node keyed by "a"

*Call searchForStrings(node(a),[],"n")

*

*node(a) is not leaf, key is not empty. Matched next node keyed by "n"

*Call searchForStrings(node(n),[],"")

*

*node(n) is not leaf, key is empty. Need to recurse on all not null childs:

*Call searchForStrings(node(s),[],"")

*

*node(s) is not leaf, key is empty, Need to recurse on all not null childs:

*... eventually we will reach Node(r) which is a leaf node, so it will return an [""], going back it will get added ["r"] -> ["er"] -> ["wer"] -> ["swer"]

*Call searchForStings(node(y),[],"")

*

*node(y) is leaf (add "" to the output), key is empty,

*recurse, we will get ["time"]

*we will return ["","time"]

*At this point we will add the "y" to get ["y","ytime"]

*And here we will add the "n" to get ["nswer","ny","nytime"]

*Adding the "a" to get ["answer","any","anytime"]

*we're done


text:
Q: Trying to clone raid (striped) To USB Hard Drive I am trying to clone a raid drive that was striped over to an external USB hard drive.
I have tried Paragon in both clone and image and restore, EaseUS in both clone options, and Acronis.  Nothing seems to work.
I did this once before a few years ago, and cannot seem to get it right this time.
I have archived image. That won't restore to the drive. I have tried to clone the partition(s), clone the drive itself.   Always I get a sector error.
I realize the sectors are different, but isn't there something that just copies and makes the conversion?

A: Thank you for all your help. I finally was able to accomplish this.
I used Casper 8.0. It worked well. Casper cloned both drives and operating systems (windows 7 and xp) onto the external USB drive. Once the main drive partitions/operating system were cloned, I was able to clone the second drive partitions/os into a separate set of partitions. Resizing of the partitions was done with EaseUS. Set the appropriate partitions to active. Did comparison on partitions/files etc. All ran perfectly. Just took a bit of time.
Note:The Casper software allows for cloning the partition into an unallocated space which is contrary to the other cloning software. So, in cloning the partitions, it was not necessary to set any partitions first.
I thought others might like to know that Casper is capable of accomplishing this task. I don't understand quite why the other major cloning software won't do the same. All the others I tried showed errors of sector mismatch, even though the allocations/sectors on the two partitions matched perfectly. Even trying to clone drives, still showed sector mismatch errors. It obviously has to do with the Raid 0. I hope this is helpful to others. Thank you.


text:
Q: Convert Datetime in Epoch-Python I want to convert a datetime into epoch.
For example, I have datetime in this format: 2018-02-14T22:15:00.232029+01:00.
How can I convert it into epoch? I get a lot of errors when i try to use datetime or timestamp in python,because of my datetime's format. Any ideas?

A: This is one way:
import pandas as pd

base = '1970-01-01'
x = '2018-02-14T22:15:00.232029+01:00'

(pd.to_datetime(x) - pd.to_datetime(base)).total_seconds()

# 1518642900.232029

A: Without using any external libraries:
>>> import datetime
>>> datetime.datetime.now().strftime('%s.%f')
'1518655350.410295'


text:
Q: How to execute url which has xml data as query parameter through Apache HttpClient? I have a XML like below which is stored as a String in xmlData variable and I need to pass this String to my url in client_data variable -
<?xml version="1.0"?>
<ClientData
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.google.com model.xsd"
 xmlns="http://www.google.com">
    <client id="100">
        <clock>
                <for>
                    <etc>val(tery) = 1</etc>
                    <while><![CDATA[val(tery)  < 20]]></while>
                </for>
        </clock>
    </model>
</ClientData>

Below is the URL I am hitting on the browser by URL encoding client_data value to get the response back and it works fine.
http://localhost:8080/test_tmp?max_time=30&users=1000&client_data=<?xml version="1.0"?>
<ClientData
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.google.com model.xsd"
 xmlns="http://www.google.com">
    <client id="100">
        <clock>
                <for>
                    <etc>val(tery) = 1</etc>
                    <while><![CDATA[val(tery)  < 20]]></while>
                </for>
        </clock>
    </model>
</ClientData>

Now I need to do the same thing through Apache HttpClient. What is the best way to do this?
I have got below code but not sure whethere there is any better way to do this? Is there anything I can improve on or some better way of doing it?
public static void main(String[] args) {
    String xmlData = getXMLData();
    String url = generateURL(xmlData);

    HttpClient httpclient = HttpClientBuilder.create().build();
    HttpGet request = new HttpGet(url);

    HttpResponse httpResponse = httpclient.execute(request);

    BufferedReader rd = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent()));

    StringBuffer response = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        response.append(line);
    }

    // prints response
    System.out.println(response);
}

private static String generateURL(final String clientData) {
    StringBuilder url = new StringBuilder();
    url.append("http://localhost:8080/test_tmp?max_time=30&users=1000&client_data=");
    url.append(URLEncoder.encode(clientData, "UTF-8"));

    return url.toString();
}

A: Honestly, I don't think you want to try and pass XML through your URI.   There are several things to consider.  One, some servers will block long URIs (Google first result: http://www.checkupdown.com/status/E414.html ).  Next, you would want to "encode" the URI so it escapes all of your chars that are not ready to be passed raw.
Consider doing a "POST" with the xml the body of the HTTP message.
Hope this helps.

A: I guess you could make your request without using Apache HttpClient, you could just open stream by url
This is how you could pass XML in the query parameter and read the response as stream:
URI uri = new URIBuilder("http://localhost:8080/test_tmp")
    .addParameter("max_time", "30")
    .addParameter("users", "1000")
    .addParameter("client_data", xmlData)
    .build();

BufferedReader rd = new BufferedReader(
    new InputStreamReader(uri.toURL().openStream())
);

If you insist on using Apache HttpClient, then code could look like:
URI uri = new URIBuilder("http://localhost:8080/test_tmp")
    .addParameter("max_time", "30")
    .addParameter("users", "1000")
    .addParameter("client_data", xmlData)
    .build();

HttpClient httpClient = HttpClients.createDefault();
HttpGet request = new HttpGet(uri);
HttpResponse httpResponse = httpClient.execute(request);

BufferedReader rd = new BufferedReader(
    new InputStreamReader(httpResponse.getEntity().getContent())
);


text:
Q: How can I compare two lists elements in Python 3.8? For example:
if two lists elements are
a = [1,2,3,4,5]
b = [2,3,4,5,6]

and I want to get [2,3,4,5] because its sharing the same number?
Can somebody help me?
Oh, and by the way, how to wrote the code if the a and b is random list?

A: You can either use list comprehension or set union:
a = [1,2,3,4,5]
b = [2,3,4,5,6]

res = [x for x in a if x in b]
res_set = set(a) & set(b)

print(res)     # [2, 3, 4, 5]
print(res_set) # {2, 3, 4, 5}

A: a = [1,2,3,4,5]
b = [2,3,4,5,6]

c=[x for x in a if x in b]
d=[y for y in (a+b) if y not in c]

print(c)    # [2, 3, 4, 5]
print(d)    # [1,6]

You can get the same element and get different elements.


text:
Q: Existence of limit of the sequence $x_n=\sqrt{n^2+1}-n$ I need to find the limit of the following sequence
$x_n=\sqrt{n^2+1}-n$.
I am having trouble on where to start for this question. Any help would be appreciated.

A: Multiply the expression by
$\frac{\sqrt{n^2+1}+n}{\sqrt{n^2+1}+n}
$.
Nothing original here - move along now.

A: Hint: Multiply and divide by $\sqrt{n^2+1} + n$


text:
Q: ¿Se puede generar un loop con un Timer0 en Pic C Compiler? Estoy realizando un proyecto, se trata un juego donde mi programa elige una figura de cierto color y yo tengo que colocar la figura en dos orificios. El 1° verifica si el color que yo coloco coincide con el color pedido por el programa, el 2° verifica si estoy colocando la figura que me pide en el orificio correcto del gabinete.
Una vez que acierte dentro de unos 10 seg, el programa sigue adelante. Pero si fallo el programa tiene que volver a repetir esos 10 segundos esperando a que se coloque la figura con el color que se me pide.
Utilizo un pic que con un oscilador interno de 8MHz :) No tengo mucha mano con el lenguaje C, pero me lo pide la escuela! Si alguno pudiera aportar alguna estructura para generar esto con el timer0 se lo agradecería mucho!
No estoy segura de que función utilizar para realizar la vuelta al inicio del timer. Mi prioridad es utilizar una función que me ayude a realizar algún loop.
Lo que tengo hecho hasta ahora es esto:
SET_TIMER0(236);
if((red > redmin) && (red < redmax)) // Si toma las frecuencias del color seleccionado (ROJO)
{
   generate_tone(C_NOTE[1],800), generate_tone(D_NOTE[1],800), generate_tone(E_NOTE[1],800); // Se genera música WIN
   delay_ms(2000);
} //LIMPIAR TIMER
else
{
  generate_tone(E_NOTE[1],800), generate_tone(D_NOTE[1],800),generate_tone(C_NOTE[1],800); // CASO CONTRARIO: Se genera música FAIL
  delay_ms(2000);
  //ACÁ TENDRÍA QUE VOLVER AL SETTIMER
}


text:
Q: Prepend list-item using JQuery with close event I want to prepend new list item with checkbox, input box and close button when i click in "+ List item" and by press enter in input box. Like: Google Keep checked item event is work in notes.

In this code when i press enter on input box it works fine and it also
prepend new list item when i click on "+ List item". But here, I am
facing some problem When i add new list item on click "+ list item"
and then I click in list item anywhere then it again add new list
item.
I want to make list like list item. I want it add list item when i
press enter or when click on "+ List Item" only.

$( "#list_item" ).keypress(function(e) {
  var key = e.keyCode ? e.keyCode : e.which;
  if(key == '13'){
    $('#list_item').prepend('
<input type="checkbox" name="checkb"><input type="text" name="txt" class="inpt">×

');
  }
});

$("#add-list").click(function(){
  $('#add-list').prepend('
<input type="checkbox" name="checkb"><input type="text" name="txt" class="inpt" >×

');
});
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

<input type="checkbox" name="checkb"><input type="text" name="txt" class="inpt" >×

 + List item

A: With prepend() you are actually adding your checkbox row inside the add-list li element. So basically you are making the add-list li element a bigger target each time you click on it.
Place your add-list element outside the ul and use append().

$( "#my-list" ).keypress( function(e) {
    var key = e.keyCode ? e.keyCode : e.which;
    if ( key == '13' ) {
        addListItem()
    }
});

$( "#add-list" ).click( function() {
  addListItem();
});

function addListItem() {
    $('#my-list').append('
<input type="checkbox"><input type="text">×
');
}
ul {
  list-style: none;
  padding: 0;
}

button { margin-top: 10px; }

li { margin-bottom: 10px; }

li span,
li input[type="text"] {
  margin-left: 10px;
}

<input type="checkbox"><input type="text">×

<button id="add-list"> + List item </button>


text:
Q: Different hostname to ip resolving results (nslookup) Good day, everyone.
Let's say I have a following setup:

*

*Windows 7 as host machine, DNS 192.168.0.100, 8.8.8.8, 8.8.4.4

*Ubuntu 16.04 as guest machine on VirtualBox, DNS 192.168.0.100 (host?)

Ubuntu is connected to Windows's network via VirtualBox's NAT.
When I'm performing nslookup google.com, the results are totally different.
On Windows I see 6 x 172.xxx.xxx.xxx while on Ubuntu I see 6 x 62.xxx.xxx.xxx
So I guess even if I resolve google.com locally on my "router" machine on my network to block it from users, if a user has custom DNS server on its machine, they'll resolve another IP addresses? Any solution for that except forcing them using my DNS server?

A: Many DNS providers are using anycast to respond with the "best" result depending on where on the Internet the query is coming from.
Executing the same query on multiple DNS servers located in various parts of the world therefore will commonly result in different results. This is normal, and it helps with, among many other things, routing traffic to the closest caching server.

A: I suppose google is using a round-robin approach to do load balancing. So on different DNS queries you will get different results for your query for google.com. With the response being cached on the local machine you will get the same IP when trying multiple times.
If you don't want users to be able to access a host you have to block on IP level.
Even if you force them to use your DNS by a firewall rule they still could enter these details in their local /etc/hosts file to directly get an IP address for google.com and connect to it.


text:
Q: PopSQL error when testing connection: Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2) I am new to using SQL and MySQL. I recently installed MySQL Server 8.0.27 on Windows 10. Everything appeared to be going fine at first, since I started the server for port 3306 (I checked on services and the status says 'running') and ran the command line client with no problems. I opened the command line client, entered my password and used the command 'create database database name;'. This seemed to work as below it read "Query OK, 1 row affected (1.82 sec)".
I signed up to PopSQL and created a new connection for my database. I used an arbitrary nickname, "localhost" for hostname, 3306 for port number, the correct database name, root for username and the correct password. When I tested this connection I received the error: Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2).
I've been searching online for solutions, and tried using 127.0.0.1 as hostname instead. After testing again I received the error: Can't connect to MySQL server on '127.0.0.1' (115). Additionally, I searched through the 'MySQL Server 8.0' folder and couldn't find a .sock file anywhere in any of the folders inside. Please help me with this :)

A: 1.Select 'Connect directly from my computer' button option.
2.Put username to root.

A: Im new to SQL, and I had a similar problem to you. I was able to fix it by going to preference > connections > managing connection > advance options: selecting Connect directly from my computer PopSQL servers won't have access to your database. This method worked for me.

A: I had the same error with popsql and when i changed my username to root everything worked. Also make sure you enter your database name (the one you create from mysql command line client) correctly .

A: I solved the same error just by restarting my PC*.
*It was a fresh install of both PopSQL and MySQL Server so perhaps it was due to that.

A: I just set every name as root and it works for me
see this image