Q: SqlDataReader.GetString and sqlnullvalueexception I am new to C#. I was executing some select queries from database tables using System.Data.SqlClient classes. I got sqlnullvalueexception while executing some select query. On googling I come to know that if the value is null in the database, SqlDataReader.GetString (or it's variants) will throw sqlnullvalueexception.
What is the best coding practice for this?
if (!sqlDataReader.IsDBNull(n)) value = r.GetString(n);

Any better way of coding?

A: If you don't want to repeat this a lot, just create a helper function, like this:
public static class DataReaderExtensions
{
    public static string GetStringOrNull(this IDataReader reader, int ordinal)
    {
        return reader.IsDBNull(ordinal) ? null : reader.GetString(ordinal);
    }

    public static string GetStringOrNull(this IDataReader reader, string columnName)
    {
        return reader.GetStringOrNull(reader.GetOrdinal(columnName));
    }
}

Which you can call like this:
value = reader.GetStringOrNull(n);

A: That really is the best way to go about it if you wish to avoid any exceptions.  You need to decide whether or not a null field represents an exceptional situation in your code - if it doesn't then use this method.  If it does then I would suggest that you either allow the exception to be thrown or catch the exception and wrap it in a more meaniful exception and throw that one.
But the main thing to know is that this is the standard way to retrieve values from a data reader when a null field does not represent an exceptional situation in the application domain.

A: This worked for me:
value = reader.GetValue(n).ToString();

A: The code you posted is fine. You could also do something like that :
value = r[n] as string;

If the value in the database is null, r[n] will return DBNull.Value, and the cast to string will return null.


Q: Selenium Chrome Driver opens a different page than regular Chrome Browser I'm trying to pull some information from this URL and ones like it: "https://www.rockymountainatvmc.com/tires-and-wheels/tusk-impact-complete-wheel-rear-p?s=1033997&v=1216"
My goal is to get the MSRP and other info for a specific part. To do this, I'm using python to run a selenium chrome webdriver that opens several of these URLs. The problem is the links aren't opening with the same information that I would get in my regular Chrome browser.
The link is supposed to contain all the information to "select a vehicle" and thus a specific part. When I open this in my regular chrome browser, everything works fine. When I open this using the automated Chrome page, it fails to select a vehicle and shows a general part page.
I can't figure out what the difference might be between these two browsers that would cause this. My regular chrome browser and the chromedriver are both version 81.0.4044.113. I've tried going to whatismybrowser.com and all settings are identical. Another interesting thing is opening this in internet explorer gives me the same result as the automated chrome browser. Help!
regular chrome browser
automated chrome browser

A: The Regular chrome browser is fetching the details of your bike(Something -- yamaha 125). It could be from past cookies or cache.
However, once you are opening it with Automation, a clean session s opened.
Try cleaning your cookies and cache on the browser(regular) and then try, both of them should appear same.
Or you can use options in chrome to select the profile your regular chrome browser is using. See https://startingwithseleniumwebdriver.blogspot.com/2015/07/working-with-chrome-profile-with.html.
Hope it Helps!


Q: Envoy proxy forward to https endpoint: facing protocol error I'm trying to do this one: call public.com/api/v1/{proxy} to envoy proxy behind an ingress proxy. Envoy proxy will forward traffic to https private endpoint inside my VPC with diffrent path: https://private.com/internal/{proxy}.
But I'm still facing the issue

upstream reset: reset reason: connection termination, transport failure reason:

I even tried with public https endpoint but it's still the same.
Below is my configuration:
admin:
  access_log_path: /tmp/admin_access.log
  address:
    socket_address:
      protocol: TCP
      address: 0.0.0.0
      port_value: 9901
static_resources:
  listeners:
    - name: listener
      address:
        socket_address:
          address: 0.0.0.0
          port_value: 10000
      filter_chains:
        - filters:
          - name: envoy.filters.network.http_connection_manager
            typed_config:
              '@type': "type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager"
              stat_prefix: http_proxy
              access_log:
                - name: envoy.access_loggers.stdout
                  typed_config:
                    "@type": type.googleapis.com/envoy.extensions.access_loggers.stream.v3.StdoutAccessLog
              route_config:
                name: all
                virtual_hosts:
                  - name: local_service
                    domains:
                      - '*'
                    routes:
                      - match: { prefix: "/api/v1"}
                        route:
                          prefix_rewrite: "/internal/"
                          cluster: allbackend_cluster
              http_filters:
                  - name: envoy.filters.http.router
  clusters:
    - name: allbackend_cluster
      connect_timeout: 1s
      type: strict_dns
      lb_policy: round_robin
      load_assignment:
        cluster_name: allbackend_cluster
        endpoints:
          - lb_endpoints:
            - endpoint:
                address:
                  socket_address:
                    address: private.com
                    port_value: 443
      transport_socket:
        name: envoy.transport_sockets.tls
        typed_config:
          "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext
          common_tls_context:
            validation_context:
              trusted_ca: {filename: /etc/ssl/certs/ca-certificates.crt}

A: I believe you need to add certificates information for envoy
tls_context:
          common_tls_context:
            tls_certificates:
              - certificate_chain:
                  filename: "/etc/ssl/certs/https.crt"
                private_key:
                  filename: "/etc/ssl/certs/key.pem"

And also add trust the certificate used by cluster.
tls_context:
      common_tls_context:
          validation_context:
            trusted_ca:
              filename: "/etc/ssl/certs/cluster.crt"


Q: Passing Value in ASP.NET Pages I am developing a web application using asp.net and C#. I have a question
Is there any way for passing values in asp pages without using QueryString or Session values or Cookies or previous page?

A: You may see: ASP.NET State Management Overview
Profile Properties

You can use: ASP.NET provides a feature called profile properties,
  which allows you to store user-specific data. This feature is similar
  to session state, except that the profile data is not lost when a
  user's session expires. The profile-properties feature uses an ASP.NET
  profile, which is stored in a persistent format and associated with an
  individual user. The ASP.NET profile allows you to easily manage user
  information without requiring you to create and maintain your own
  database. In addition, the profile makes the user information
  available using a strongly typed API that you can access from anywhere
  in your application. You can store objects of any type in the profile.
  The ASP.NET profile feature provides a generic storage system that
  allows you to define and maintain almost any kind of data while still
  making the data available in a type-safe manner.

A: You can use asp.net cache or  save data from one page in to some persistent medium and other page would read from that medium could be database or xml etc.

A: Beside your requirements(not using QueryString or Session values or Cookies) yes you can use public property like
public String YourProperty
{
    get
    {
        return "Return What you want to pass";
    }
}

Check this MSDN article for full code


Q: Different unit for Kubernetes resource memory on pods My question is related to Kubernetes and the units of the metrics used for the HPA (autoscaling).
When I run the command
kubectl describe hpa my-autoscaler
I get (a part of more information) this:
...
Metrics:                                               ( current / target )
  resource memory on pods:                             318067507200m / 1000Mi
  resource cpu on pods  (as a percentage of request):  1% (1m) / 80%
...

In this example, when you can see the metrics for the resource memory on pods, you can see that the unit for the current value is m, which is "millis" (as is described in the official documentation), but the unit used for the target value is Mi, which is "Mebis"
Is there any problem with the usage of different units?
Thanks!

A: No, they are just different multipliers. The actual code is using a raw number of bytes under the hood.


Q: Haskell Attoparsec infinite loop The code is based on Haskell Attoparsec, and when I use parseOnly pString "v", it gives me the right answer as Right (DontNeedTrim, "v").
While when I use the instruction parseOnly (many' pString) "v", it seems drops into the infinite loop and finally failed with the overflowed stack.
data Signal = NeedTrim
              | DontNeedTrim
              deriving (Show)

pString :: Parser (Signal, [Char])
pString = ((char '\"' *> many' pChar' <* char '\"') >>= \s -> return (NeedTrim, s))
          <|> (many' pChar >>= \s -> return (DontNeedTrim, s))

pChar :: Parser Char
pChar = char '\\' *> (pEscape <|> spaces *> endOfLine *> pChar)
        <|> satisfy (`C.notElem` "\"\\\n#;")

pChar' :: Parser Char
pChar' = char '\\' *> pEscape
         <|> satisfy (`C.notElem` "\\\"")

pEscape :: Parser Char
pEscape = choice (zipWith decode "bnt\\\"" "\b\n\t\\\"")
  where decode c r = r <$ char c

A: The second alternative in pString accepts the empty string: many' pChar >>= \s -> return (...). Thus many' pString keeps consuming the empty string ad infinitum.


Q: Jquery select element outside of li by ID im looking to select the follow element by id toggleThisDiv. The markup looks like:

       <asp:HyperLink ID="lnkCategory" runat="server">
       <asp:Literal ID="litCategory" runat="server" Visible="true" />
       <asp:Image ID="imgMan" runat="server" Visible="false" /></asp:HyperLink>
       <asp:Button ID="btnToggleDiv" runat="server" Text="+" Visible="false" />

And the jQuery:
$(document).ready(function () {
        $('[id*="btnToggleDiv"]').click(function () {
            $(this).next().slideToggle(100);
            return false;
        });
    });

This works when the button is outside of the listitem but this is all inside a repeater and if i leave it like that, all of the buttons created will be next to each other instead of within their associated list item.
I'm looking for something within jQuery that would allow me to select the next div (toggleThisDiv), is this possible?
Thankyou

A: Use unique ID's, or classes if generating elements where the same identifier will be used.
To target an element outside the current parent of the clicked element you can find the closest parent that matches a selector, and then the next element etc.
$(document).ready(function () {
   $('[class*="btnToggleDiv"]').on('click', function () {
       $(this).closest('li').next('div').slideToggle(100);
       return false;
   });
});

A: Use something like this to select the toggleThisDiv
$('#<%= toggleThisDiv.ClientID %>')

When the website is generated from your asp code, your IDs will be different than what you have given them.  This is because they are run at server.  Anytime that you are using runat server, use the format above to find the generated ID.
You should use a class inside to repeater though.


Q: create a mp3 player embedded in a facebook post The Serial podcast has this cool feature where they share their webpage on their facebook page and Facebook lets the audio be played within Facebook.  See this image:

I've created a blog post with all of the proper meta tags to match the relevant tags expected by facebook:
music:preview_url:url, the og:type is music.song, etc.
But I can't get a mp3 player to appear.
When I compare the open graph meta data in the Facebook debugger from the Serial webpage to my own webpage, the tags match up fine.  Yes, mine has a 'locale' array but that can't be the issue.
I'm thinking they must have some type of Facebook app?  Or I don't know what.  I've never built a Facebook app so if you think that is how they are doing it, where would I start looking?
This is my non-working open graph output:

This is the one from the Serial podcast.  You can see in the Share Dialog the player buttons for the MP3.  How are they getting that in there?  I would have thought just be me using the correct meta tags, Facebook would put player buttons on top of my mp3 and create the player for me.


Q: "The server could not update. Check your API credentials and internet connection and try again." - Google Sheets API, service account error I'm currently building a website/platform following using this: https://forensic-architecture.org/investigation/timemap-for-cartographic-platforms. It works by reading a Google sheet I have, and I need to press an 'update' button in order for the sheets to be read. However, rather than it updating, I get the following: "The server could not update. Check your API credentials and internet connection and try again."
I'm unsure what's going wrong, as I've followed all the steps as needed for the Google Sheets api, as outlined in the link above. I also previously had this running with a different API key locally (which I since deleted). Now, I can't even get it to work locally, though previously there was no issue. The service account has permission on the Sheet itself. I've also tried setting the sheet to publicly available online with no change. I've checked the service account and key are correct about a million times, and have created a new project with whole new key etc so see if the issue was reproduced. I also tried making a new sheet (and granting a new key etc permission) but still get the same error.
The metrics panel for Sheets API tells me "google.apps.sheets.v4.SpreadsheetsService.GetSpreadsheet" has an error rate of 100%. I'm well below my quota, and have billing enabled (two other reasons I keep seeing on Stack as possible reasons for similar errors), so I'm not sure that's the issue.
Below is also what I see in terminal when trying to run locally (rn switched to trying to fix this locally as this is the last step for me in making the platform live, and I'm wary of doing anything on my remote server that could end up causing problems elsewhere):
Enabling CORS in development...
Connected to {{My Google Sheet name}} (Google Google Sheet with ID {{Sheet ID}}).
===================
grant access to: {{my service account email}}
===================
Started on port 4040

GET /api/blueprints 200 46.784 ms - 1677

GET /api/update 404 452.498 ms - 115

The platform reads my service key credentials through my .env (which it seems to be doing fine going from what I see in terminal), and uses a config file to find the Google Sheets id (which again seems fine from above).
Please let me know if there's any extra info needed here; I'm pretty new to all of this, and so not necessarily aware when I'm relaying issues what is vital info and what is not.


Q: The model item passed into the dictionary is of type ' ', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable? After executing the application I get the "The model item passed into the dictionary is of type 'ClubStarterKit.Web.ViewData.Forum.NewMessageListViewData', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[ClubStarterKit.Web.ViewData.Forum.NewMessageListViewData]'.
In view I have the codes below

    <%if ( User.Identity.IsAuthenticated) { %>

          <%using (Ajax.AsyncForm(Website.Shared.Views.DisplayTemplates.NewForumMessageList, new AsyncFormOptions(AsyncFormType.TargetUpdate, FormMethod.Post, "newMessages", targetUpdate: "messages", elementBlockId: "message-add-block", postRequestFunction: "afterMessageUpdate")))
          {%>

Add New Message Final Test

                <%: Html.Wysiwyg("message") %>

               <%-- <input type="hidden" value="<%: Model.ThreadSlug %>" name="thread" />--%>
                <input type="hidden" value="-1" name="messageId" />
                <input type="submit" value="Add Message4 final" />
          <%}%>

          New message4 final

          <%}%>

in the controller the code is
 public virtual ActionResult Index()
    {
        ViewData.Title("New Message");
        return View(Views.List, new ClubStarterKit.Web.Infrastructure.Forum.NewMessageListAction().Execute());
    }

and in screenshot below it is :

The model item passed into the dictionary is of type 'Myapplication.Web.ViewData.application.NewMessageListViewData', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable
Please advise which area of code is the issue

A: You are passing the View a single NewMessageListViewData, but it has been strongly typed to accept only objects implementing IEnumerable<T> where T is NewMessageListViewData. For example, a List<NewMessageListViewData> would work.
As mentioned in the comments, I would start by looking at the return type of ClubStarterKit.Web.Infrastructure.Forum.NewMessageListAction.Execute(), or, if you only intend to display a single instance of NewMessageListViewData in this View, you need to set the model in the View to reflect that.


Q: Confirm dialog in Cordova I'm writing an app in javascript and html with phonegap/cordova.
I have this code in javascript:
$('#diario_delete_btn').live('tap',function(e){
    var iddb = $(this).find('a').attr('rel');
    confirm_diario_delete(iddb);
});

function diario_delete(iddb) {
    var db = window.openDatabase("Database", "1.0", "123nozze", 200000);
    db.transaction(function(tx){
        tx.executeSql('DELETE FROM AgendaItemJDO WHERE id='+iddb);
        lastChangeUpdate();
    });

    $('.diario_row[db_id="'+ iddb +'"]').remove();
    $('#popupMenuDiario').popup("close");
}

function confirm_diario_delete(iddb) {
    var r = confirm("Confermi l'eliminazione dell'elemento?");
    if (r) {
        diario_delete(iddb);
    } else {
        $('#popupMenuDiario').popup("close");
    }
}

It seems to work but if I choose "cancel button" (so r = false) n times before I press "confirm button", next time the confirm dialog is displayed 2 times, next time it is displayed 3 times, and so on. I don't know why this behaves this way. The same is if a change the code and I use the Cordova example code for confirm dialog.
Any ideas on what is the problem and how can I solve it?
Thanks!

A: You should use the native notification which Phonegap supports.
Specifically the .confirm() method taken from link above;
// process the confirmation dialog result
function onConfirm(button) {
    alert('You selected button ' + button);
}

// Show a custom confirmation dialog
//

navigator.notification.confirm(
    'You are the winner!',  // message
    onConfirm,              // callback to invoke with index of button pressed
    'Game Over',            // title
    'Restart,Exit'          // buttonLabels
);

A:    navigator.notification.confirm(
        'Are you sure you want to signup ',  // message
        onConfirm,              // callback to invoke with index of button pressed
        'SignUp',            // title
         ['yes','no']             // buttonLabels
    );

    function onConfirm(buttonIndex){
    alert('You selected button ' + buttonIndex);
    if(buttonIndex==2){
    alert('You selected button - no');
    }else{
    alert('You selected button - yes');

    }

    }


Q: How to do this type of incrementation in PHP? I am using this category script:
<?php

include("connect.php");

$nav_query = mysql_query("SELECT * FROM `categories` ORDER BY `id`");
$tree = "";
$depth = 1;
$top_level_on = 1;
$exclude = array();
array_push($exclude, 0);

while ($nav_row = mysql_fetch_array($nav_query)) {
    $goOn = 1;
    for ($x = 0; $x < count($exclude); $x++) {
        if ($exclude[$x] == $nav_row['id']) {
            $goOn = 0;
            break;
        }
    }
    if ($goOn == 1) {
        $tree .= $nav_row['name'] . "
";
        array_push($exclude, $nav_row['id']);
        if ($nav_row['id'] < 6) {
                    $top_level_on = $nav_row['id'];
                }

        $tree .= build_child($nav_row['id']);
    }
}

function build_child($oldID) {
    global $exclude, $depth;
    $child_query = mysql_query("SELECT * FROM `categories` WHERE parent_id=" . $oldID);
    while ($child = mysql_fetch_array($child_query)) {
        if ($child['id'] != $child['parent_id']) {
            for ($c=0; $c < $depth; $c++) {
                            $tempTree .= " ";
                        }
            $tempTree .= "- " . $child['name'] . "
";
            $depth++;
            $tempTree .= build_child($child['id']);
            $depth--;
            array_push($exclude, $child['id']);
        }
    }

    return $tempTree;
}

echo $tree;

?>

It relies on the following mysql database structure:
id | parent_id | name

1                Cats
2    1           Siamese Cats
3    2           Lilac Point Siamese Cats
4                Dogs

etc...

The script allows for unlimited category depth but has one major downfall. It displays the category navigation to the front end like so:
Cats
 - Siamese Cats
 - Lilac Point Siamese Cats
Dogs

How can I have it display like this:
Cats
 - Siamese Cats
   - Lilac Point Siamese Cats
Dogs

So that for each additional category depth another space with be added to the beginning indentation of the category text?

A: As you are already keep track of the depth, make use of it. E.g.
$indent = '';
for($i = 0; $i < $depth; $i++) {
     $indent .= " ";
}
$tempTree .= $indent . "- " . $child['name'] . "
";

To make it look the way you want it you might have to initialize $depth with 0.

Also note that executing SQL queries in a nested for loop is not the best approach. If possible, try to reduce the number of queries.
You could for example use classes and, get all the entries at once and then build the tree structure with objects and arrays.


Q: pass cookie and reload one frame from another frame I have main html page which have two frames frame1 and frame2. In frame1, a textbox & a button where the button click passes the value in textbox to a cookie. In frame2 this value passed through cookie is used. I need to refresh or reload the frame2 page as & when the cookie value is changed from the button click event on frame1. Any suggestions for achieving this???


Q: Docker Machine error: Hyper-V PowerShell Module is not available I've checked my Hyper-V settings and PowerShell Module is enabled. I've also found this documented issue: https://github.com/docker/machine/issues/4342 but it is not the same issue since I do not have VMware PowerCLI installed. The issue was closed with a push to the repo and is supposedly fixed in 0.14.0-rc1, build e918c74 so I tried it anyways. After replacing my docker-machine.exe, I'm still getting the error and still getting the error even if I reinstall Docker for Windows.
For some more background, this error starting happening after a reinstall because my Docker install had an error: https://github.com/docker/for-win/issues/1691, however, I'm not longer getting that issue after reinstalling.

A: For those who struggle with this issue in Windows, Follow the instruction here

A: When creating a Hyper-v VM using docker-machine on win10, an error was returned"Error with pre-create check: "Hyper-V PowerShell Module is not available"。
The solution is very simple. The reason is the version of the docker-machine program. Replace it with v0.13.0. The detailed operation is as follows:

*

*Download the 0.13.0 version of the docker-machine command. Click to download: 32-bit system or 64-bit system

*After the download is complete, rename and replace the " docker-machine.exe " file in the " C:\Program Files\Docker\Docker\resources\bin" directory. It is best to back up the original file.

A: Here is the solution
https://github.com/docker/machine/releases/download/v0.15.0/docker-machine-Windows-x86_64.exe
Save the downloaded file to your existing directory containing docker-machine.exe.
For my system this is the location for docker-machine.exe
/c/Program Files/Docker/Docker/Resources/bin/docker-machine.exe
Backup the old file and replace it file with the new one.
cp docker-machine.exe docker-machine.014.exe
Rename the downloaded filename to docker-machine.exe
mv docker-machine-Windows-x86_64.exe docker-machine.exe
Build Instructions

*

*Create virtual switch in Hyper-V manager named myswitch

*Request Docker to create a VM named myvm1
docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1
Results
docker-machine create -d hyperv --hyperv-virtual-switch "myswitch" myvm1

Running pre-create checks...
(myvm1) Image cache directory does not exist, creating it at C:\Users\Trey Brister\.docker\machine\cache...
(myvm1) No default Boot2Docker ISO found locally, downloading the latest release...
(myvm1) Latest release for github.com/boot2docker/boot2docker is v18.05.0-ce
(myvm1) Downloading C:\Users\Trey Brister\.docker\machine\cache\boot2docker.iso from https://github.com/boot2docker/boot2docker/releases/download/v18.05.0-ce/boot2docker.iso...
(myvm1) 0%....10%....20%....30%....40%....50%....60%....70%....80%....90%....100%
Creating machine...
(myvm1) Copying C:\Users\Trey Brister\.docker\machine\cache\boot2docker.iso to C:\Users\Trey Brister\.docker\machine\machines\myvm1\boot2docker.iso...
(myvm1) Creating SSH key...
(myvm1) Creating VM...
(myvm1) Using switch "myswitch"
(myvm1) Creating VHD
(myvm1) Starting VM...
(myvm1) Waiting for host to start...
Waiting for machine to be running, this may take a few minutes...
Detecting operating system of created instance...
Waiting for SSH to be available...
Detecting the provisioner...
Provisioning with boot2docker...
Copying certs to the local machine directory...
Copying certs to the remote machine...
Setting Docker configuration on the remote daemon...
Checking connection to Docker...
Docker is up and running!
To see how to connect your Docker Client to the Docker Engine running on this virtual machine, run: C:\Program Files\Docker\Docker\Resources\bin\docker-machine.exe env myvm1

A: (1),
V0.15 fixed this issue officially:
Fix issue #4424 - Pre-create check: "Hyper-V PowerShell Module is not available"
Official Introduction:
https://github.com/docker/machine/pull/4426
Address to donload V0.15
https://github.com/docker/machine/releases
(2),
I tested this, it works fine.
No need restart docker
It take effect immdiately after the "docker-machine.exe" is replaced with version 0.15
(3),
Backup the original one is a good habit

A: Just start docker desktop if you are on Windows


Q: HTTP mp4 filetransfer. IE downloads file too fast I have a web server that serves mp4 files. When I get a http request for a video that is 35mb, I use “send()” repeatedly in a loop to send 1mb each time.
Chrome and Firefox handle this well and receive no more data than needed. Only if the user has reached far enough in the webplayer, the browser requests/receives more data. IE however, receives my "send()" every two seconds, which means the entire file is downloaded in about a minute. That is not good for a user who only watched 1 min of 14 (considering data consumption/useage).
Can I do something differently?

Best regards
Arre


Q: Redirect a Page to Another Page for 10 Seconds Then Redirect Back Again to Original URL I want to temporarily redirect users to an ad page and then return them to their desired page again after 10 seconds.
I don't know how to do this because I don't have much knowledge of PHP or Java. So please provide me complete redirect code and guide me where to put that code.
I am using $_GET parameters on first page so let say my urls are as follow:
mydomain.net/games/?game=PUBG+Mobile&Rating=5
mydomain.net/games/?game=Apex+Legends&Rating=4
mydomain.net/games/?game=GTA+5&Rating=4.5

I want every url to redirect to ads.php page and then redirect back to original url after 10 seconds and never redirect again.

A: First of all: Java !== Javascript

Java and Javascript are similar like Car and Carpet are similar.

Source: https://stackoverflow.com/a/245068/3119231
-
To redirect an user to another location you may use:
// Simulate a mouse click:
setTimeout(function() { // timer
    window.location.href = url;
}, 10000); // 10000 ms = 10 seconds

// Simulate an HTTP redirect:
setTimeout(function() { // timer
    window.location.replace(url);
}, 10000); // 10000 ms = 10 seconds

Place it in the documents you like.
Source: https://www.w3schools.com/howto/howto_js_redirect_webpage.asp
Bonus (CaitLAN Jenner): You need to prevent your documents from redirecting in an infinite loop. Your visitors would get pushed from one site to another every 10 seconds.

A: @Maurice mentioned how to perform a HTTP redirect in JavaScript. If you do this on both pages, however, then you will find yourself in an infinite redirect loop, which is very bad. To expand on that answer here is some PHP to dynamically disable the second redirect from the original page through the use of a query string parameter (see https://en.wikipedia.org/wiki/Query_string).
First, you need to include the following PHP code at the top of your document. If you have other PHP code, just put the inside of this code below it. This will accept the redirect query string.
<?php

$redirect = 1

if (isset($_GET['redirect'])) {
    $redirect = htmlspecialchars($_GET["redirect"]);
}

?>

Now, later in the document (preferably at the end of body or within head) you need to dynamically generate the JavaScript using PHP as such.
<?php
if ($redirect == 1)
{
    echo "<script>";
    echo "// Simulate an HTTP redirect:";
    echo "setTimeout(function() { // timer";
    echo "window.location.replace(url);";
    echo "}, 10000); // 10000 ms = 10 seconds";
    echo "</script";
}
?>

Note that you will need to replace "url" here with the appropriate url, which may require properly escaping quotations (see https://www.php.net/manual/en/function.addslashes.php)
As a final note, you need to set the "redirect" query string appropriately on the page that redirects back to the original. You can do so with something like this:
mydomain.net/games/?game=PUBG+Mobile&Rating=5&redirect=0
UPDATE PER REQUEST
On the second page you don't need the PHP logic mentioned above. You simply need a JavaScript 10 second redirect. Something like this should work.
<script>
url = "mydomain.net/games/?game=PUBG+Mobile&Rating=5&redirect=0";

// Simulate an HTTP redirect:
setTimeout(function() { // timer
window.location.replace(url);
}, 10000); // 10000 ms = 10 seconds
</script>

Note that here I've used a static URL. If you want this URL to be dynamic you can use the exact same approach I've mentioned for solving the infinite redirect. In other words, pass the original URL as a query string parameter to the ad page, parse it on the ad page through PHP, and use PHP to dynamically create the url in the code above.


Q: "Plugin with id 'io.fabric' not found" error. after removing fabric from build.gradle in my ionic react project android version build using capacitor, i followed the steps of removing all the fabric and replacing them with crashlytics
reference: https://firebase.google.com/docs/crashlytics/upgrade-sdk?platform=android
the build command:
ionic cap copy android
ionic cap open android

now I am just getting the error when building:
Caused by: org.gradle.api.plugins.UnknownPluginException: Plugin with id 'io.fabric' not found.

here's my project build.gradle:
buildscript {

    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.1.1"
        classpath 'com.google.gms:google-services:4.3.4'
        classpath 'com.google.firebase:firebase-crashlytics-gradle:2.3.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

apply from: "variables.gradle"

ext {
    var = '4.1.1'
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and here's my app build.gradle:
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'com.google.firebase.crashlytics'

android {
    compileSdkVersion rootProject.ext.compileSdkVersion
    defaultConfig {
        applicationId "com.xxx.xxx"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            // firebaseCrashlytics {
            //     nativeSymbolUploadEnabled true
            // }
        }
    }
}

repositories {
    flatDir{
        dirs '../capacitor-cordova-android-plugins/src/main/libs', 'libs'
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "androidx.appcompat:appcompat:$androidxAppCompatVersion"
    implementation project(':capacitor-android')
    testImplementation "junit:junit:$junitVersion"
    androidTestImplementation "androidx.test.ext:junit:$androidxJunitVersion"
    androidTestImplementation "androidx.test.espresso:espresso-core:$androidxEspressoCoreVersion"
    implementation project(':capacitor-cordova-android-plugins')
    implementation platform('com.google.firebase:firebase-bom:26.0.0')
    implementation 'com.google.firebase:firebase-analytics:18.0.0'
    implementation 'com.google.firebase:firebase-crashlytics:17.2.2'
}

apply from: 'capacitor.build.gradle'

try {
    def servicesJSON = file('google-services.json')
    if (servicesJSON.text) {
        apply plugin: 'com.google.gms.google-services'
    }
} catch(Exception e) {
    logger.warn("google-services.json not found, google-services plugin not applied. Push Notifications won't work")
}

version reference:
android studio: 1.4
android gradle plugin version: 4.1.1
gradle version: 6.6

A: when installing firebase don't install "cordova-plugin-firebase" if you are using react with ionic, it will create this error! fixed after removed


Q: How to use the Symfony 2 Container in a legacy app Would like to integrate a legacy application with a Symfony 2 application - replacing more and more parts of the old application with Symfony components. The approach I would take is using the Symfony 2 container in the legacy application getting the services that are already configured for the Symfony 2 application. The first services I would like to use are the session and the security context.
Questions:

*

*Is this feasible?

*How do I get the configured service container?

More info in the legacy application: The typical PHP mess: Single PHP files, as "controllers" (checking $_GET and $_POST for different execution paths). Each page includes init.php which sets up autoloading, database connection etc. The session management has its own class (which i would like to replace), the data is retrieved through calls to static methods (!) of database objects.

A: I believe you can access the container instance from your legacy application like this
$kernel = new AppKernel('prod', true);
$kernel->loadClassCache();
$kernel->boot();
$request = Request::createFromGlobals();
$container = $kernel->getContainer();
$sc = $container->get('security.context');

A: Using Symfony's DIC as a standalone component is possible but you'd have to do many things "manually" (as you're not planning on using full Symfony Framework from the very beginning). You'll probably won't get much of using DIC with all that legacy stuff.
If you want to go this path I'd consider choosing another component first (like HttpFoundation and HttpKernel).
As @Cerad suggested you might wrap your legacy code in Symfony. Have a look at IngewikkeldWrapperBundle bundle. You can't use it as is but it might give you some ideas.
There's a third way.
You can decide to implement every new feature in a Symfony app. Than, you can make that both legacy and Symfony apps coexist. On a server level (i.e. Nginx), you might proxy legacy URLs to the legacy app and all the migrated URLs to a Symfony2 app. In my case this scenario was the best option and proved to be working. However, we were committed to abandon legacy app development (so every new feature or change had to be developed in a Symfony2 app).
Edit: here's how you could boot the Symfony kernel in a legacy app and dispatch an event (which is needed for the firewall):
$kernel = new \AppKernel('dev', true);
$kernel->boot();

$request = Request::createFromGlobals();
$request->attributes->set('is_legacy', true);
$request->server->set('SCRIPT_FILENAME', 'app.php');

$container = $kernel->getContainer();
$container->enterScope('request');
$container->get('request_stack')->push($request);
$container->set('request', $request);

$event = new GetResponseEvent($kernel, $request, HttpKernelInterface::MASTER_REQUEST);
$eventDispatcher = $container->get('event_dispatcher');
$eventDispatcher->dispatch('kernel.request', $event);


Q: virtual machine query? hi i have installed ubuntu 10.4 as guest OS on vmware and windows xp is my host.
now i want do know does vmware give a new ip address to the linux os.. if yes how do i get that ip address

A: yes it should, try running ifconfig from the console.
Hope this helps,
Jason.


Q: How to "lock" radio buttons, checkboxes, and  menus without graying them out? I have a form that I want to present in two states:
1) Normal form
2) Person can look at the form as filled out by a user but can't change anything
It's easy to handle text inputs with the readonly property, but radio buttons, checkboxes, and dropdown menus don't use it.  I can set the "disabled" property for those, but in most browsers they show up grayed out and barely visible.  What I really want is for them to look like a normal form but be unclickable the way a disabled element is.  Is there a way to override the normal "disabled" look?  Or is the solution to disable them in some roundabout way handling clicks?
I'm using jQuery for most of this stuff, if that matters...

A: well, you could try hacks like this....
$(':radio:disabled').removeAttr('disabled').click(function(){
    this.checked=false;
});

this will select all disabled radio buttons and enabled it but when click, will not be checked...
demo
and on <select>
you could do like,
$('select:disabled').removeAttr('disabled').change(function(){
    $(this).find('option').removeAttr('selected');
    // this.value = this.defaultValue; // you may also try this..
});

A: Just replace them with your own more controllable HTML/CSS construct, à la Niceforms, et al. (with disabled or readonly attribute, as appropriate, as fallback).

A: A suggestion rather an answer: you can associate an event with the state change of an element, and cancel the change.
You can do it the same way as the validate tools which allows to enter only digits or only some characters in <input type="text" /> fields. See a StackOverflow post about this.
Another solution is to put something in front of your controls. For example:

<input type="radio" />

will make your radio button unclickable. The problem is that doing so will prevent the users to copy-paste text or using hyperlinks, if the
 covers the whole page. You can "cover" each control one by one, but it may be quite difficult to do.


Q: Bootstrap Responsive - Not Working I've created a very simple landing page using Bootstrap.
As I was designing it I was working on the responsive breakpoints and in Chrome, they all looked and worked great.
Now that I've uploaded my site, I realized that the responsive isn't working. In desktop I have no issues, but in mobile the text and button sizes remain the same.
www.woodtechms.com
Thanks for your help!

A: I'm pretty sure it's due to missing meta tags inside header.
Here's Bootstrap template
I've also added img-responsive class to your logo image and then the logo scales down as it supposed to.

A: It does work but only for screen sizes more than 768 and less than 900px as written in your custom-css:
@media screen and (min-width: 768px) and (max-width: 900px) {

    /* ---- Logo Woodtech ---- */
    .logo {
        margin-top: 230px;
    }

    /* ---- Title ---- */
    h2 {
        font-size: 5.9rem;
        margin-top: 130px;
        margin-bottom: 60px;
        line-height: 70px;
    }

    /* ---- Text ---- */
    p {
        font-size: 34px;
        padding-bottom: 34px;
    }

    /* ---- Button ---- */
    .contact-button {
        width: 400px;
        font-size: 4rem;
        height: 100px;
    }
}

If you want it to change styles for other widths then you need to add more media queries like the one added in your css.
For e.g., if you want the button width to be 300px in between screen size 600px and 800px you can write the following:
@media screen and (min-width: 600px) and (max-width: 800px){
   .contact-button{
   width:300px;
}
}

And likewise you can add styles for other elements at different widths.


Q: Is it possible to use if -> where in MySQL? I have a list of templates which user creates with some data (type of data is not important). The templates are stored in a table which have field private of enum type with values 0, 1 which means false/true.
The main idea is that the each user can create a private template which can be see only by him, all other templates can see all system users. So my sql should be like this:
SELECT
    `templates`.`id`,
    `templates`.`name`,
    `templates`.`description`,
    `templates`.`datetime`,
    `users`.`username`
FROM
    (`templates`)
JOIN `users` ON `templates`.`user_id` = `users`.`id`
-- WHERE
    -- `users`.`id` <> 1 AND `templates`.`private` = 0
ORDER BY
    `templates`.`datetime` DESC
LIMIT 5

In where i say that i need all rows except private where is not my id, but it miss my own private templates...

A: There seems to be no reason to JOIN the users table. You can get all public and your own private templates with
SELECT
    `templates`.`id`,
    `templates`.`name`,
    `templates`.`description`,
    `templates`.`datetime`,
FROM
    `templates`
WHERE
    `templates`.`user_id` = 42 OR `templates`.`private` = 0

I am assuming that the id of the current user is 42, substitute this with the real value when constructing the query.


Q: Convert date formatted string to DateTime object? I need to convert a date formatted string to a datetime object so that I can use the Twig date() function on the datetime object.
Example string: '2015-06-20'
Can Twig accomplish this or perhaps could it be done with a custom Twig extension?

A: you can do this
{{ "12/14/2016"|date("Y-m-d", option_timezone_convert) }}

be aware, it will create from that string a datetime object with the default timezone, if you apply a timezone option, it will convert it.

A: PHP's DateTime object can do this as a constructor:
$date = new DateTime('2015-06-20');


Q: Finding IP Address for IPhone I am working on IPhone. I want to know how to find a ip address of a iphone through USB/3G not on wifi.
I am aware of seeing IP if it is connected through WiFI.(Going through settings and looking under Wifi)
But i need IP through USB / 3G. what i did means i used personal hotspot and i connected my iphone to PC through usb. I got an IP.
But when i added one more Iphone with same hot spot enabled and connected through USB i am getting like unidentified network.
By using whatismyip.com site i am getting an ip . but i cant do anything with it. I am unable to reach my iphone with the provided ip of that site.
So can anyone kindly provide information on how to look for IP of multiple Iphones connected to same PC.
The purpose is to communicate to muliple iphones with their IP's.
Thanks  a million in advance.

A: Unfortunately the responses are not completely correct. In a 3G/4G network every device gets an IP address, but THAT's NOT the IP address that you see when going to sites like www.whatismyip.com. That's the address that the Telco presents to the external world, not the device IP address.
Telcos such AT&t, Verizon, Telefonica and similar assign a "private" IP address that is only valid in their network. This is similar to the internal IP address that you have in your phone when connect to the house wireless, but if you check in www.whatismyip.com you get the external IP address of your wireless router (You can check that those are different addresses). What Telcos do is known as NAT or PAT. The reason is that the current version of IP has a very limited number of available IP addresses, and all those million of devices cannot get public IP addresses (like the one you see in whatismyip.com). Actually several devices share that external IP address.
Unlike Android devices where you can get the IP that the telco assigned to the device, iOS does not present that information to the user (unless you jailbreak the device or have an App).
Although the address that whatismyip presents is not your real IP, it is the one that the external world recognizes so it suffices for most purposes.

A: What you see on whatismyip.com is the IP address you get from your mobile provider, on which it depends what kind op IP you get. Very often 3G networks are NATted, meaning that you get an IP address from the range 10.0.0.0/8 which cannot be reached from outside.

A: Using www.whatismyip.com should definitely give you the correct address?
What address did you get when it came back?
How did you verify if this was your iPhone's address? I assume you don't have a firewall installed on your iPhone? Hmm, other thing is your provider is doing some kind of filtering, NAT-ing, or other tomfoolery. If you don't mind me asking, what exactly are you trying to achieve here? Are you trying to run some kind of server-style app on your iPhone? Or do you just want to get a connection between the iPhone and a server - might be easier to initiate the connection from the iPhone side.
You should check if it's at your provider's IP block range - an online whois check should tell you that (www.whois.net).
How did you test whether this was your iPhone's address?
Other option is just to have your iPhone hit a server that you control (using 3G), and check the server logs.
Or just make things easier, and use an app to tell you - e.g. iStat:
http://bjango.com/iphone/istat/
which will give you your cell (3G) IP address as well.
Cheers,
Victor

A: There are two types of IP addresses:
Private IP address (your device IP that you get it from your home Wi-Fi router or from your Teleco provider router to speak to those two routers).
Public IP address (your home Wi-Fi router and/or from your Teleco provider router which they will use it to allow you to speak to another person on the Internet).
**NOTE: Without Public IP address, you cannot speak to people who are on the Internet.
Now both (your home Wi-Fi router or your Teleco Provider router)they have something called DHCP, or Dynamic Host Configuration Protocol. This protocol is used to allocate private IP address to anyone connected to local network (either home Wi-Fi or Teleco provider).
That means both (home Wi-Fi router and Teleco provider router) have one single IP address called Public IP address to allow you to speak to outside world, but first they need to give private IP address to able you to speak with them (your home Wi-Fi router and your Teleco provider router).
If your iOS connected to your home Wi-Fi, then you will have a Private IP address:
1- Go to settings.
2- Click on Wi-Fi.
3- List of Wi-Fi networks will be appeared.
4- Click on your Wi-Fi network name (known as SSID).
5- Click on the blue circle of the exclamation mark on the right side of your Wi-Fi name.
You will see your Private IP Address there very clearly.
Now if your iOS device is not connected to any Wi-Fi network, but it connected to your Teleco provider, then you cannot see your private IP address.
I am sure there is a way to see your Private IP address that you got it from your Teleco Provider DHCP. You have to search from internet or ruin your device by jailbreak it.
For the Public IP Address (no matter if you are connected to your home Wi-Fi or your Teleco Provider), go to your internet browser (e.x. google chrome) and type: "What is my ip address". The result will be between your hand in fractions of seconds!
Now Back to your question:
If you connected two iPhones to your PC and both have hotspot enabled, that means your PC USB ports will handle two IP Private addresses because your iPhones will act as your home Wi-Fi router.
if you have windows OS in your laptop, then go to windows CMD terminal and type:
ipconfig
the CMD prompt terminal will give you number of IP address, there are your two Private IP addresses from your iPhones.
Now if unidentified network message still there, open RUN in your windows OS and type [ ncpa.cpl ], it will take you to network connection setting section, right click on one of your iPhones networks and disable it, keeping the other enabled.
I hope it is crystal clear now.

A: When the phone is the hotspot for the Telecom cellular provider it actually being used as a Router therefor if you connect laptop to that hotspot you can open network setting on the laptop to view its tcp/ip settings and see the ip of the laptop and the ip of the Router which is the IP of your Phone.
The Ip is a private one, you can ping to it or do what ever you want.
Example of connecting Iphone to Mac Xcode wirelessly:

*

*share personal hotSpot from your phone.

*connect your laptop to your phone private network using wifi, search for the ssid you set in your phone and set a correct password.

*in Mac go to System prefences->Network->wifi connected->Advanced->Tcp/Ip
copy Router Ip - this is your Iphone private Ip.

In order to connect Xcode to Iphone wirelessly you first need to connect the phone with usb, open window->device and simulators, select your phone and set checkbox "connect via network"
Now if the phone is disconnected from the Mac and the private network is shared as explained, you know the phone Ip, then you can select the phone in Xcode (it remember phones that were connected), open window->device and simulators, select your phone , click on it to get menu of options, select "connect with ip", provide the ip you saw as "Router" previously.
Thats all, hope it'll help somebody.


Q: How to resize a Python matplotlib.pyplot.figure already created I'm working with this custom Py visual in PowerBI. Unfortunately, Power BI has some Python code leading my code that pre-defines the image size (5.55555555555556,4.16666666666667).
The result is a small image surrounded by a lot of empty space:

Is there any way I can redefine the size of the image, even though I cannot modify the leading code?
Any other suggestions are welcome,
Thanks!
# Prolog - Auto Generated #
import os, uuid, matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot
import pandas

os.chdir(u'C:/Users/USER/PythonEditorWrapper_443a6d71-c4cc-4e62-ac6f-2dad3eeace3d')
dataset = pandas.read_csv('input_df_d2b6d8be-2212-4ece-902c-f85219eff22b.csv')

matplotlib.pyplot.figure(figsize=(5.55555555555556,4.16666666666667), dpi=72)
matplotlib.pyplot.show = lambda args=None,kw=None: matplotlib.pyplot.savefig(str(uuid.uuid1()))

#My code starts here, I cannot modify anything above this line.

#I wish I could add a line here to redefine figsize=(5.55555555555556,4.16666666666667)

A: from matplotlib import pyplot as plt
plt.figure(figsize=(15,20))

try this


Q: pe:keyfilter not working I need regex for primefaces keyfilter to allow input between 0-100 for percentage.
I tried lot of expression but none seems working.
I need my inputbox not to allow typing apart from 0-100.  Any suggestions


Q: File modification time gets overwritten by background cache flushing I have code that performs following steps:

*

*open file

*write data

*set file timestamps (via SetFileInformationByHandle(FileBasicInfo))

*close file

When file is stored on certain NAS devices (and accessed via share) it's modification time ends up being set to current time.
According to Process Monitor Close() in step 4 results in a Write (local cache gets flushed/pushed to NAS device) that (seemingly) updates file's mtime on server.
If I add FlushFileBuffers() (or sleep for few seconds) between steps 2 and 3 -- everything is fine.
Is this a bug in SMB implementation of this NAS device (Dell EMC Isilon) or SetFileInformationByHandle() never promised anything?
What is the best way to deal with this situation? I would really like to avoid having to call FlushFileBuffers()...
Edit: Great... :-/ It looks like for executables (and only executables) atime (last access time) gets screwed up too (in the same way). Only these are harder to reproduce -- need to run this logic few times. Could be some antivirus... I am still investigating.
Edit 2: According to procmon access time gets updated by EXPLORER.EXE -- when it sees an executable, it can't resist opening it and reading portions of it (probably extracting the icon).

A: You can't really do anything -- I guess Isilon's SMB implementation doesn't support certain things (that would've preserved timestamps).
I simply added FlushFileBuffers() before SetFileInformationByHandle() and made sure there are no related race conditions in my code.


Q: Yii2 dropDownList get selected value I have dropDownList in my view ( data from db) :
use yii\widgets\ActiveForm;
\app\assets\HelloAsset::register($this);
$form = ActiveForm::begin();
$users=\app\models\User::find()->all();
$items=\yii\helpers\ArrayHelper::map($users,'id','username');
echo $form->field($model, 'username')->dropDownList($items);
echo \yii\bootstrap\Html::submitButton('Send');
ActiveForm::end();

I want to get data from 'username' in my controller:
 $model=new Data();
    if ($model->load(\Yii::$app->request->post())){
        echo 'it is status:'.$model->username;
    }else {
        return $this->render('simple', ['model' => $model]);
    }

But data is null.
How I must get data in right?
Please, help me solve this problem.


Q: fixed-length permutations of a string I'm trying to take a seven-character string and generate all the possible 3- and 4-letter permutations of it. This seems like something that recursion would be handy for (most all permutation generators I've seen are recursive), but I keep getting stuck at how to avoid repetition. That is, if my input string is "aabcdef" I don't want any of the permutations to contain more than two "a" characters.
Any insights you can provide are greatly appreciated.

A: This can be done both iteratively and recursively. Here is a decent permutation generator. That can be adapted to your needs and made generic (to take a List<T> of elements) so it can take a list of numbers, a string (list of characters) and so on.

A: Try thinking about the characters as elements in a bag of characters.
Here's some pseudocode that should work:
permute ( bag < character > : theBag, integer : length, string : resultSoFar )
    if length <= 0 then:
       print resultSoFar
       exit
    end-if

    for each x in theBag:
        nextResult = resultSoFar + x
        nextBag = theBag - x
        permute( nextBag, length - 1, nextResult )
    end-for
end-method

Good luck!

A: make a function that takes a set of letters make it return the set of n permutations (3 or 4) that start with the letter you specify. Then run it once for each of the unique chars in your set.
The full result set will be the union of the subsets.

A: Here's a clue that might help.  If you have input "aabcdef" and you don't want permutations with two "a"s, it is easier to remove one of the "a"s from the input rather than trying to eliminate the permutations with multiple "a"s as you generate them.

A: @ Chip Uni: when I implemented your code, it generated all permutations of length x to max. So when I fed it length 3 with a bag containing 7 characters it generated all permutations of length 3 through 7. It was a simple matter to eliminate all results greater than length 4, though.
Thank you very much, y'all! I greatly appreciate your suggestions and assistance.

A: This is in Ruby, but it might help:
http://trevoke.net/blog/2009/12/17/random-constrained-permutations-in-ruby/


Q: Extracting XML data reverse XSLT? I have some XML data that resides in an XML file and I am trying to get it into datatables. I have tried putting it into a Dataset. I have tried putting it in XML nodes. However, it all seems random and just all over the place and it's not working. I have tried to include a summarized version of how the data looks below. How can I extract it into clear tables and rows and columns? Also, I am not sure if this would help or not, but this XML is created from 4 tables that are then extracted to an XML file using and XSLT file. Is there a way to do it in REVERSE to take the XSLT and XML file into the original datatables?
<obj name="TableName0">
    <int name="ANumberThatsAColumn1" val="" />
    <int name="ANumberThatsAColumn2" val="" />
    <int name="ANumberThatsAColumn3" val="" />
    <str name="ADateThatsAColumn4" val="2022-12-16T08:43:07.9870485-06:00" />
</obj>

<list name="TableName1">
    <obj href="RowOfData1/">
        <int name="ColName1" val="0" />
        <str name="ColName2" val="1" />
        <int name="ColName3" val="1" />
        <int name="ColName4" val="0" />
        <int name="ColName5" val="6" />
        <int name="ColName6" val="0" />
        <str name="ColName7" val="#3062" />
        <ref name="ColName8" href="SomeValue1" />
    </obj>

    <obj href="RowOfData2/">
        <int name="ColName1" val="0" />
        <str name="ColName2" val="1" />
        <int name="ColName3" val="1" />
        <int name="ColName4" val="0" />
        <int name="ColName5" val="6" />
        <int name="ColName6" val="0" />
        <str name="ColName7" val="#2543" />
        <ref name="ColName8" href="SomeValue2" />
        <int name="ColName9" val="0" />
        <int name="ColName10" val="0" />
        <int name="ColName11" val="0" />
    </obj>
</list>

<list name="TableName2">
    <list name="row1">
        <int name="R0" val="0" displayName="#7925" />
        <int name="R1" val="1" displayName="#7926" />
    </list>
    <list name="row2">
        <int name="R0" val="0" displayName="#21641" />
        <int name="R1" val="1" displayName="#21642" />
        <int name="R2" val="2" displayName="#21643" />
    </list>
</list>

A: Here is a conceptual example for you.
XML shredding is happening in T-SQL via two XQuery methods:

*

*.node()

*.value()
XQuery Language Reference (SQL Server)
SQL
DECLARE @xml XML =
N'<root>
    <obj name="TableName0">
        <int name="ANumberThatsAColumn1" val=""/>
        <int name="ANumberThatsAColumn2" val=""/>
        <int name="ANumberThatsAColumn3" val=""/>
        <str name="ADateThatsAColumn4" val="2022-12-16T08:43:07.9870485-06:00"/>
    </obj>
    <list name="TableName1">
        <obj href="RowOfData1/">
            <int name="ColName1" val="0"/>
            <str name="ColName2" val="1"/>
            <int name="ColName3" val="1"/>
            <int name="ColName4" val="0"/>
            <int name="ColName5" val="6"/>
            <int name="ColName6" val="0"/>
            <str name="ColName7" val="#3062"/>
            <ref name="ColName8" href="SomeValue1"/>
        </obj>
        <obj href="RowOfData2/">
            <int name="ColName1" val="0"/>
            <str name="ColName2" val="1"/>
            <int name="ColName3" val="1"/>
            <int name="ColName4" val="0"/>
            <int name="ColName5" val="6"/>
            <int name="ColName6" val="0"/>
            <str name="ColName7" val="#2543"/>
            <ref name="ColName8" href="SomeValue2"/>
            <int name="ColName9" val="0"/>
            <int name="ColName10" val="0"/>
            <int name="ColName11" val="0"/>
        </obj>
    </list>
    <list name="TableName2">
        <list name="row1">
            <int name="R0" val="0" displayName="#7925"/>
            <int name="R1" val="1" displayName="#7926"/>
        </list>
        <list name="row2">
            <int name="R0" val="0" displayName="#21641"/>
            <int name="R1" val="1" displayName="#21642"/>
            <int name="R2" val="2" displayName="#21643"/>
        </list>
    </list>
</root>';

-- INSRT INTO <targetTable>
SELECT c.value('@name', 'VARCHAR(20)') AS name
    , c.value('@val', 'INT') AS val
    , c.value('@displayName', 'VARCHAR(20)') AS displayName
FROM @xml.nodes('/root/list[@name="TableName2"]/list/int') AS t(c);

-- INSRT INTO <targetTable>
SELECT c.value('@name', 'VARCHAR(20)') AS name
    , c.value('@val', 'VARCHAR(20)') AS val
    , c.value('@href', 'VARCHAR(20)') AS href
FROM @xml.nodes('/root/list[@name="TableName1"]/obj/*') AS t(c);


Q: firefox moz, Web Transitions I have the following:
.ui-dialog-body {
    position: relative; /* Needed for sliding left, right */
    min-height:60px;
    padding: .5em 1em;
}
.ui-dialog-body.slideLeft {
    left:-500px;
    -webkit-transition: left .5s linear;
    -webkit-transition-delay: .2s;
    -moz-transition-property: left;
    -moz-transition-duration: .5s;
}

When the user clicks an item which requires loading, the class slideLeft is added which slides the div out of view. This works great in webkit (safari, chrome) but not in FireFox 4 beta.
Any ideas why that is?

A: Maybe you need left: 0 in the first style rule so that the transition is from 0px to 500px (which can be interpolated) rather than auto to 500px (which can't).
(Also, there are differences between your -webkit-* declarations and your -moz-* declarations, but I don't think there need to be.)

A: Put the declaration on the element, not the added class:
.ui-dialog-body {
    position: relative; /* Needed for sliding left, right */
    min-height:60px;
    padding: .5em 1em;
    -webkit-transition: left .5s linear;
    -moz-transition: left .5s linear;
    -ms-transition: left .5s linear;
    -o-transition: left .5s linear;
    transition: left .5s linear;
}

.ui-dialog-body.slideLeft {
    left:-500px;
}


Q: Mapping JPA native query to DTO returns column name instead of column value I'm working on a project using JPA and Spring Boot.
I have an Entity named (for example) Model:
This class is like this:
private String model_id;
private String attr1;
private String attr2:
private String attr3;

I want to query according to model_id and one of these attributes.
So I've created this query in SQL and works using MySQL:
SELECT model_id AS modelId, attr1 AS attribute FROM my_table WHERE attribute LIKE '%my_value%'

So native query is:
@Query(SELECT model_id AS modelId, :attribute AS myAttribute FROM my_table WHERE :attribute LIKE '%:filter%', nativeQuery=true)
List<MyModelDTO> doQuery(@Param("filter") String filter, @Param("attribute") String attribute)

And MyModelDTO is an interface like this:
public interface MyModelDTO{
  String getModelId();
  String getMyAttribute();
}

But the desired output doesn't contains the correct value to myAttribute field. Is the column name instad the value.
For example, using this table:
| model_id |  attr1   |  attr2   |  attr3   |
---------------------------------------------
|  "id_1"  | "value1" | "value2" | "value3" |
---------------------------------------------

If I query using filter=alue and attribute=attr2 expected result is:
{
  modelId: "id_1",
  myAttribute: "value2"
}

Because I'm looking a value that contains alue into attr2 column.
But I get:
{
  modelId: "id_1",
  myAttribute: "attr2"
}

The column name is outpouted instead of column value.
Have I missing something using nativeQuery or trying to parse into DTO object?
Thanks in advance


Q: Regex: How to include character of "if" condition I'm making a date extractor using regex in java. Problem is that date is 20-05-2014 and my program is extracting 0-5-14. In short, how can I get the character on which I'm checking the second character of date?
    int count = 0;
    String data = "HellowRoldsThisis20-05-2014. farhan_rock@gmail.comHellowRoldsThisis.farhan@gmail.com";
    String regexOfDate = "((?<=[0])[1-9]{2})|((?<=[12])[0-9])|((?<=[3])[01])\\.\\-\\_((?<=[0])[1-9])|((?<=[1])[0-2])\\.\\-\\_((?<=[2])[0-9]{4})"; \\THE PROBLEM
    String[] extractedDate = new String[1000];
    Pattern patternDate = Pattern.compile(regexOfDate);
    Matcher matcherDate = patternDate.matcher(data);

    while(matcherDate.find()){
        System.out.println("Date "+count+"Start: "+matcherDate.start());
        System.out.println("Date "+count+"End  : "+matcherDate.end());
        extractedDate[count] = data.substring(matcherDate.start(), matcherDate.end());
        System.out.println("Date Extracted: "+extractedDate[count]);
    }

A: You can try the regular expression:
// (0[1-9]|[12][0-9]|[3][01])[._-](0[1-9]|1[0-2])[._-](2[0-9]{3})
"(0[1-9]|[12][0-9]|[3][01])[._-](0[1-9]|1[0-2])[._-](2[0-9]{3})"

A: A single regex o match valid dates is awful.
I'd do:
String regexOfDate = "(?<!\\d)\\d{2}[-_.]\\d{2}[-_.]\\d{4}(?!\\d)";

to extract the potential date, then test if it is valid.


Q: Azure Function .NET Core 3.1 C# unit test case with nUnit I need to create a unit test cases in Azure Function .NET Core using C# and NUnit framework. Please share a good example with links.
Thanks in advance.

A: Your unit tests shouldn’t include the Function App entry point, just like they shouldn’t include Asp.Net controllers, or the Main method of a Console app.


Q: AJAX success response not working Rails I have a mailer that is successfully sending using AJAX, but when the submit button is clicked, it is left depressed and no success message is displayed.  Clicking the button multiple times results in multiple form submissions.  The button should reset, and (from my understanding) the AJAX:success event should generate some sort of text to show it was successful.
The AJAX Script (from rails guides)

The (UPDATED) form:
<%= form_tag("/pages/thank_you", remote: true, id: 'AJAX-form') do %>

              <%= text_field_tag :name, nil, class: 'form-control', placeholder: 'Name' %>

            @
            <%= text_field_tag :email, nil, class: 'form-control', placeholder: 'Email' %>

              <%= text_area_tag :message, nil, class: 'form-control text-area-wide', placeholder: 'Message' %>

      <%= submit_tag 'Send Message', class: 'btn btn-success' %>
  <% end %>

The controller action:
def thank_you
    @name = params[:name]
    @email = params[:email]
    @message = params[:message] || "Hello!"
    UserMailer.contact_form(@email, @name, @message).deliver
end

A: Double-check your JavaScript bindings.
$("#AJAX-form").on(...)

is looking for an element with id="AJAX-form". Your form appears to have class="AJAX-form".
Either bind to the class with
$(".AJAX-form").on(...)

or change your form id to match
<%= form_tag("/pages/thank_you", remote: true, id: 'AJAX-form') do %>

A: From 1.9 version ajaxSuccess can be attached just only on the document object.
"$(document).ajaxSucces(function(){...});"
But you can use the following code:
$('form').submit(
    function(){
        return $.ajax({
            url: $(this).attr("action"),
            data:data,
            processData: false,
            contentType: false,
            type: "POST",
            dataType : "json",
            success: function( result ) {
                $form.trigger('submit:success');
            },
            error: function( xhr, status, errorThrown ) {
                console.log( "Error: " + errorThrown );
                console.log( "Status: " + status );
                console.dir( xhr );
                $form.trigger('submit:error');
            },
            complete: function( xhr, status ) {
                $form.trigger('submit:complete');
                console.log( "The request is complete!" );
        }
    }
);

 $('form.SpecialForm').on('submit:success', myFunction1);

 $('form.OtherSpecialForm').on('submit:success', otherFunction);

 $('form.ThirdSpecialForm').on('submit:error', thirdFunction);

 $('form.OneMoreSpecialForm').on('submit:complete', oneMoreFunction);

 $('form.theLastSpecialForm').on('submit:complete', theLastFunction);


Q: How to write runnable tests of static_assert? I am writing a unit-test suite for a source code library that contains static_asserts.
I want to provide assurance these static_asserts do no more and no less than they
are desired to do, in design terms. So I would like to be able to test them.
I could of course add uncompilable unit tests of the interface that cause the static asserts
to be violated by a comprehensive variety of means, and comment or #if 0 them all out, with my personal
assurance to the user that if any of them are un-commented then they will observe
that the library does not compile.
But that would be rather ridiculous. Instead, I would like to have
some apparatus that would, in the context of the unit-test suite, replace
a static_assert with an equivalently provoked runtime exception, that the
test framework could catch and report in effect: This code would have static_asserted
in a real build.
Am I overlooking some glaring reason why this would be a daft idea?
If not, how might it be done? Macro apparatus is an obvious approach and I don't
rule it out. But maybe also, and preferably, with a template specialization or
SFINAE approach?

A: As I seem to be a lone crank in my interest in this question I have cranked
out an answer for myself, with a header file essentially like this:
exceptionalized_static_assert.h
#ifndef TEST__EXCEPTIONALIZE_STATIC_ASSERT_H
#define TEST__EXCEPTIONALIZE_STATIC_ASSERT_H

/* Conditionally compilable apparatus for replacing `static_assert`
    with a runtime exception of type `exceptionalized_static_assert`
    within (portions of) a test suite.
*/
#if TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1

#include <string>
#include <stdexcept>

namespace test {

struct exceptionalized_static_assert : std::logic_error
{
    exceptionalized_static_assert(char const *what)
    : std::logic_error(what){};
    virtual ~exceptionalized_static_assert() noexcept {}
};

template<bool Cond>
struct exceptionalize_static_assert;

template<>
struct exceptionalize_static_assert<true>
{
    explicit exceptionalize_static_assert(char const * reason) {
        (void)reason;
    }
};

template<>
struct exceptionalize_static_assert<false>
{
    explicit exceptionalize_static_assert(char const * reason) {
        std::string s("static_assert would fail with reason: ");
        s += reason;
        throw exceptionalized_static_assert(s.c_str());
    }
};

} // namespace test

// A macro redefinition of `static_assert`
#define static_assert(cond,gripe) \
    struct _1_test \
    : test::exceptionalize_static_assert<cond> \
    {   _1_test() : \
        test::exceptionalize_static_assert<cond>(gripe){}; \
    }; \
    _1_test _2_test

#endif // TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1

#endif // EOF

This header is for inclusion only in a test suite, and then it will make
visible the macro redefinition of static_assert visible only when the test suite
is built with
`-DTEST__EXCEPTIONALIZE_STATIC_ASSERT=1`

The use of this apparatus can be sketched with a toy template library:
my_template.h
#ifndef MY_TEMPLATE_H
#define MY_TEMPLATE_H

#include <type_traits>

template<typename T>
struct my_template
{
    static_assert(std::is_pod<T>::value,"T must be POD in my_template<T>");

    explicit my_template(T const & t = T())
    : _t(t){}
    // ...
    template<int U>
    static int increase(int i) {
        static_assert(U != 0,"I cannot be 0 in my_template<T>::increase<I>");
        return i + U;
    }
    template<int U>
    static constexpr int decrease(int i) {
        static_assert(U != 0,"I cannot be 0 in my_template<T>::decrease<I>");
        return i - U;
    }
    // ...
    T _t;
    // ...
};

#endif // EOF

Try to imagine that the code is sufficiently large and complex that you
cannot at the drop of a hat just survey it and pick out the static_asserts and
satisfy yourself that you know why they are there and that they fulfil
their design purposes. You put your trust in regression testing.
Here then is a toy regression test suite for my_template.h:
test.cpp
#include "exceptionalized_static_assert.h"
#include "my_template.h"
#include <iostream>

template<typename T, int I>
struct a_test_template
{
    a_test_template(){};
    my_template<T> _specimen;
    //...
    bool pass = true;
};

template<typename T, int I>
struct another_test_template
{
    another_test_template(int i) {
        my_template<T> specimen;
        auto j = specimen.template increase<I>(i);
        //...
        (void)j;
    }
    bool pass = true;
};

template<typename T, int I>
struct yet_another_test_template
{
    yet_another_test_template(int i) {
        my_template<T> specimen;
        auto j = specimen.template decrease<I>(i);
        //...
        (void)j;
    }
    bool pass = true;
};

using namespace std;

int main()
{
    unsigned tests = 0;
    unsigned passes = 0;

    cout << "Test: " << ++tests << endl;
    a_test_template<int,0> t0;
    passes += t0.pass;
    cout << "Test: " << ++tests << endl;
    another_test_template<int,1> t1(1);
    passes += t1.pass;
    cout << "Test: " << ++tests << endl;
    yet_another_test_template<int,1> t2(1);
    passes += t2.pass;
#if TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1
    try {
        // Cannot instantiate my_template<T> with non-POD T
        using type = a_test_template<int,0>;
        cout << "Test: " << ++tests << endl;
        a_test_template<type,0> specimen;

    }
    catch(test::exceptionalized_static_assert const & esa) {
        ++passes;
        cout << esa.what() << endl;
    }
    try {
        // Cannot call my_template<T>::increase<I> with I == 0
        cout << "Test: " << ++tests << endl;
        another_test_template<int,0>(1);
    }
    catch(test::exceptionalized_static_assert const & esa) {
        ++passes;
        cout << esa.what() << endl;
    }
    try {
        // Cannot call my_template<T>::decrease<I> with I == 0
        cout << "Test: " << ++tests << endl;
        yet_another_test_template<int,0>(1);
    }
    catch(test::exceptionalized_static_assert const & esa) {
        ++passes;
        cout << esa.what() << endl;
    }
#endif // TEST__EXCEPTIONALIZE_STATIC_ASSERT == 1
    cout << "Passed " << passes << " out of " << tests << " tests" << endl;
    cout << (passes == tests ? "*** Success :)" : "*** Failure :(") << endl;
    return 0;
}

// EOF

You can compile test.cpp with at least gcc 6.1, clang 3.8 and option
-std=c++14, or VC++ 19.10.24631.0 and option /std:c++latest. Do so first without defining  TEST__EXCEPTIONALIZE_STATIC_ASSERT
(or defining it = 0). Then run and the the output should be:
Test: 1
Test: 2
Test: 3
Passed 3 out of 3 tests
*** Success :)

If you then repeat, but compile with -DTEST__EXCEPTIONALIZE_STATIC_ASSERT=1,
Test: 1
Test: 2
Test: 3
Test: 4
static_assert would fail with reason: T must be POD in my_template<T>
Test: 5
static_assert would fail with reason: I cannot be 0 in my_template<T>::increase<I>
Test: 6
static_assert would fail with reason: I cannot be 0 in my_template<T>::decrease<I>
Passed 6 out of 6 tests
*** Success :)

Clearly the repetitious coding of try/catch blocks in the static-assert
test cases is tedious, but in the setting of a real and respectable
unit-test framework one would expect it to package exception-testing apparatus to generate such stuff out of your sight. In googletest, for example, you are able to write the like of:
TYPED_TEST(t_my_template,insist_non_zero_increase)
{
    ASSERT_THROW(TypeParam::template increase<0>(1),
        exceptionalized_static_assert);
}

Now I can get back to my calculations of the date of Armageddon :)


Q: XSLT loaded with AJAX, contains
A: Would it help to put the alert in a CDATA tag? So
<script type="text/javascript">
  <![CDATA[alert('Only in Firefox');]]>
</script>

I've started doing that for all javascript that I include in xslt templates


Q: How to give priority to stages in a Jenkins parallel pipeline? I have a Jenkins pipeline with some parallel stages:
pipeline {
  stages {
    stage("Parallel build") {
      parallel {
        stage("A") { /* takes 5 min */ }
        stage("B") { /* takes 5 min */ }
        stage("C") { /* takes 15 min */ }
      }
    }
  }
}

Assuming there aren't enough free executors to start all stages at once, how do I make sure stage C is among those started first? This will reduce build time from 20 minutes to 15, since A and B can run on the same executor consecutively.


Q: How to update Json object value dynamically in jquery? var jsonObj = [
     {
       "key1": "value1",
       "key2": "value2",
       "key3": "value3"
     },
     {
       "key1": "value1",
       "key2": "value2",
       "key3": "value3"
     }
    ];

I want to update all the values of all the objects. Here the keys and values are dynamic not key1 and value1. Could you help to figure it out the requirement.
I want to make each value of each object to "changedvalue". So the final result after updating the jsonObj is
[
     {
       "key1": "changedvalue",
       "key2": "changedvalue",
       "key3": "changedvalue"
     },
     {
       "key1": "changedvalue",
       "key2": "changedvalue",
       "key3": "changedvalue"
     }
];

A: jsonObj is an array thus you first have to iterate this array
jsonObj.forEach(o => {...});

o is now an object. You have to iterate the keys/values of it
for(let k in o)

k is a key in the object. You can now alter the value
o[k] = 'WhateverYouNeed'

var jsonObj = [{
       "key1": "value1",
       "key2": "value2",
       "key3": "value3"
     },
     {
       "key1": "value1",
       "key2": "value2",
       "key3": "value3"
}];

jsonObj.forEach(o => {
  for(let k in o)
    o[k] = 'ChangedValue'
});

console.log(jsonObj);

References:
As stated, your structure is an array of objects and not JSON: Javascript object Vs JSON
Now breaking you problem into parts, you need to

*

*Update property of an object: How to set a Javascript object values dynamically?

*But you need to update them all: How do I loop through or enumerate a JavaScript object?

*But these objects are inside an array: Loop through an array in JavaScript

*But why do I have different mechanism to loop for Objects and Arrays? for cannot get keys but we can use for..in over arrays. Right? No, you should not. Why is using "for...in" with array iteration a bad idea?
ReadMe links:
Please refer following link and check browser compatibility as the solution will not work in older browsers. There are other ways to loop which are highlighted in above link. Refer compatibility for them as well before using them.

*

*Arrow functions

*Array.forEach

A: You might want to use a mixture of forEach and Object.keys

const jsonObj = [
  {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
  },
  {
    "key1": "value1",
    "key2": "value2",
    "key3": "value3"
  }
];

jsonObj.forEach( obj => {
  Object.keys( obj ).forEach( key => {
    const value = obj[ key ];

    console.log( key, value );
  } );
} );

A: Here you go with a solution https://jsfiddle.net/Lha8xk34/

var jsonObj = [{
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}, {
  "key1": "value1",
  "key2": "value2",
  "key3": "value3"
}];

$.each(jsonObj, function(i) {
  $.each(jsonObj[i], function(key) {
    jsonObj[i][key] = "changed" + key;
  });
});

console.log(jsonObj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

A: Try pinch
in your Case :
var jsonObj = [
     {
       "key1": "value1",
       "key2": "value2",
       "key3": "value3"
     },
     {
       "key1": "value1",
       "key2": "value2",
       "key3": "value3"
     }
    ];

pinch(data, "/key1/", function(path, key, value) {
  return (value === "value1") ? "updatedValue" : value;
});


Q: Git rebase commit replays vs merge commits: a concrete example I have a question about how rebasing works in git, in part because whenever I ask other devs questions about it I get vague, abstract, high level "architect-y speak" that doesn't make a whole lot of sense to me.
It sounds as if rebasing "replays" commits, one after another (so sequentially) from the source branch over the changes in my working branch, is this the case? So if I have a feature branch, say, feature/xyz-123 that was cut from develop originally, and then I rebase from origin/develop, then it replays all the commits made to develop since I branched off of it. Furthermore, it does so, one develop commit at a time, until all the changes have been "replayed" into my feature branch, yes?
If anything I have said above is incorrect or misled, please begin by correcting me! But assuming I'm more or less correct, I'm not seeing how this is any different than merging in changes from develop by doing a git merge develop. Don't both methods result with all the latest changes from develop making their way into feature/xyz-123?
I'm sure this is not the case but I'm just not seeing the forest through the trees here. If someone could give a concrete example (with perhaps some mock commits and git command line invocations) I might be able to understand the difference in how rebase works versus a merge. Thanks in advance!

A: " It sounds as if rebasing "replays" commits, one after another (so sequentially) from the source branch over the changes in my working branch, is this the case? "
Yes.
" Furthermore, it does so, one develop commit at a time, until all the changes have been "replayed" into my feature branch, yes? "
No, it's the contrary. If you rebase your branch on origin/develop, all your branch's commits are to be replayed on top of origin/develop, not the other way around.
Finally, the difference between merge and rebase scenarios has been described in details everywhere, including on this site, but very broadly the merge workflow will add a merge commit to history. For that last part, take a look here for a start.

A: RomainValeri's answer covers a lot of this, but let me add a few more items:

*

*"Replaying" a commit is a matter of running git cherry-pick or doing something equivalent.  Some versions of git rebase literally do run git cherry-pick and if you want to think about how rebase works, that's the concrete piece to consider.  (If you want to get into all the side details, the other principal way to "copy" a commit is to use git format-patch and git am: this goes faster because it doesn't handle renames properly.  So the cherry-pick method is normally better.  It was not the default until relatively recently, though, except for interactive rebases and any rebases that used the interactive machinery.)

*Merge commits literally cannot be cherry-picked, so when using git rebase --rebase-merges, Git can't do that.  Instead, Git will re-perform the merges.  That is, Git figures out, at the start of the rebase operation, which commits are ordinary (single-parent) commits that can be cherry-picked, and which ones are merges with two or more parents.  It then lays out, in the interactive rebase script—this particular kind of rebase always uses the interactive machinery—the special extra commands that interactive rebase needs in order to run git merge again.  You can see these commands by adding --interactive to your rebase command.  Be careful if you edit them: they have to be run in the right order for everything to work.

*If you have merge commits that git rebase would need to "replay", and you don't use --rebase-merges, git rebase simply drops these merge commits entirely.  The result is ... often not good.  But if you did a merge that you did not mean to do, and want to do a rebase instead, it actually is good: this strips out the final merge.
The TL;DR version of this is: both are complicated.  Using git merge often makes one (1) new merge commit, that combines work.  Using git rebase copies, as if by cherry-pick, many commits, and abandons the old (and lousy?) commits for the new-and-improved copies.
When using either git cherry-pick or git merge, merge conflicts can occur.  Git 2.33 is likely to have git rerere enabled by default, so that any previous resolution for some particular merge conflict will be picked up automatically and re-used.  Currently you must enable this manually.  The way rerere works is a bit complicated; it's worth reading through this blog entry.


Q: DataGridView CellPainting drawing text with ampersand displays weirdly I have implemented a CellPainting event handler that uses TextRenderer.DrawText and it has worked great up until a cell had an ampersand in it. The cell shows the ampersand correctly while editing the cell, but when editing is done and it is drawn, it shows up as a small line (not an underscore).

using System;
using System.Drawing;
using System.Windows.Forms;

namespace StackOverFlowFormExample {
    public partial class DataGridViewImplementation : DataGridView {
        public DataGridViewImplementation() {
            InitializeComponent();
            this.ColumnCount = 1;
            this.CellPainting += DGV_CellPainting;
        }

        private void DGV_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) {
            if (!e.Handled && e.RowIndex > -1 && e.Value != null) {
                e.PaintBackground(e.CellBounds, false);
                TextRenderer.DrawText(e.Graphics, e.Value.ToString(),
                                      e.CellStyle.Font, e.CellBounds,
                                      e.CellStyle.ForeColor, TextFormatFlags.VerticalCenter);
                e.Handled = true;
            }
        }
    }
}

//creating the datagridview
public partial class MainForm : Form {
    public MainForm() {
        InitializeComponent();
        DataGridViewImplementation dgvi = new DataGridViewImplementation();
        this.Controls.Add(dgvi);
        dgvi.Rows.Add("this is a & value");
    }
}

replacing
TextRenderer.DrawText(e.Graphics, e.Value.ToString(),
                      e.CellStyle.Font, e.CellBounds,
                      e.CellStyle.ForeColor, TextFormatFlags.VerticalCenter);

with
e.PaintContent(e.ClipBounds);

shows it correctly, of course I want to be able to customize the painting of the content though.
I've also tried using
e.Graphics.DrawString(e.Value.ToString(), e.CellStyle.Font, Brushes.Black, e.CellBounds);

but it doesn't draw it the same as
e.Paint(e.ClipBounds, e.PaintParts);

I use e.Paint in my actual code when a cell is being painted that doesn't need my customized painting.
How can I get e.Graphics.DrawString to look the same as e.Paint or get TextRenderer.DrawText to display the ampersand correctly?

A: You want to use the TextRenderer version since DrawString should really only be used for printing:
TextRenderer.DrawText(e.Graphics, e.Value.ToString(),
                  e.CellStyle.Font, e.CellBounds, e.CellStyle.ForeColor,
                  TextFormatFlags.NoPrefix | TextFormatFlags.VerticalCenter);

The NoPrefix flag will show the ampersand correctly.


Q: Where am I making mistake in VHDL? So I have posted this already but I haven't got any answer so I decided to try it one more time.
The entity shall implement the following arithmetic functionality:
• Substraction I1 - I2
• Input operand 1 (I1): 12 bit, two’s complement
• Input operand 2 (I2): 8 bit, two’s complement
• Output (O): 12 bit, two’s complement
• Overflow (V) and Carry flag (C) set accordingly
• Valid flag (VALID): indicates if the computed solution is valid or not
So what I have done?
Here is it:
library IEEE;

use IEEE.std_logic_1164.all;

use IEEE.numeric_std.all;

entity arithmetic is

port( I1 :in std_logic_vector(12-1 downto 0); -- Operand 1

I2 :in std_logic_vector(8-1 downto 0); -- Operand 2

O :out std_logic_vector(12-1 downto 0); -- Output

C :out std_logic; -- Carry Flag

V :out std_logic; -- Overflow Flag

VALID :out std_logic -- Flag to indicate if the solution is valid or not

);

end arithmetic;

architecture behavior of arithmetic is

begin

process(I1,I2)

begin

if ((unsigned(I1)-unsigned(I2)) > unsigned(I1)) and
((unsigned(I1)-unsigned(I2)) > unsigned(I2)) then

C <= '1';

else

C <= '0';

end if;

if I1(11)='1' and signed(std_logic_vector(unsigned(I1)-unsigned(I2)))>0
then

V <= '1';

else

V <= '0';

end if;

if unsigned(I1) < unsigned(I2) then

VALID <= '0';

else

VALID <= '1';

end if;

O <= std_logic_vector(unsigned(I1)-unsigned(I2));

end process;

end behavior;

There is no syntax mistakes or something like that. Only mistake is
that:
Error for:
comp2,SUB
I1= 100000011110
I2= 01000001
Expected:
O= 011111011101
C= '0', V= '1', VALID= '0'
Received:
O= 011111011101
C= '0', V= '1' and VALID= '1'
If someone could help I would be really thankful.

A: If the numbers are twos complement, then signed is the correct type.
With that either:
1. Make the ports signed rather than std_logic_vector or
2. Use signed internally and cast all inputs to signed and outputs to std_logic_vector once:
signal I1_sv    : signed(11 downto 0) ;
. . .
signal result   : signed(11 downto 0) ;
. . .
I1_sv <= signed(I1) ;
. . .
O <= std_logic_vector(result) ;
. . .

All the individual type conversions (casting) you are doing in the code makes it difficult to read.


Q: Nginx filter module installation I am working on a nginx filter module. I could successfully install my module by following this - http://www.evanmiller.org/nginx-modules-guide.html tutorial. But it seems that all the other filter modules are not called now except the one which I have added. How can I debug this ?

A: I know it's a long time since the question was asked, but after spending quite a bit of time on this, here is the issue:
In the config file of your module, you need to provide this line:
HTTP_AUX_FILTER_MODULES="$HTTP_AUX_FILTER_MODULES your_module_name"

And you can remove the HTTP_MODULES line if you only have a filter.

A: before

*

*ps awx | grep nginx  to check nginx process id

*Stop Nginx server
gdb <path>  // may be ->sr/local/nginx/sbin/nginx
(gdb) set-follow-fork-mode child
set detach-on-fork  off
set logging on
set confirm off
rbreak ngx_http*  // you want to break point ..
run


Q: how to confige an abstract class with structure map is there any problem with this kinda registration via structure map??
 static public class ContainerBootstrapper
{
    static public void BootstrapDefaultContainer(bool test = false)
    {
      StructureMap.ObjectFactory.Initialize(x =>
         {
           x.Scan(p =>
             {
                 p.AssemblyContainingType<IPropertyType>();
                 p.AddAllTypesOf<IPropertyType>();
                 //                     p.AddAllTypesOf<IPropertyType>().NameBy(c => c.Name);
             });

        });
  }

 public interface IPropertyType : IIdentityObject, IPriority
{
    string PropertyName { get; set; }

    ObjectType ObjectType { get; }

    string DisplayName { get; set; }

    IEntityType EntityType { get; set; }

    IList<IPropertyRuleObject> RuleObjects { get; set; }

    void AddRuleObject(IPropertyRuleObject ruleObject);

}

 public abstract class PropertyTypeBase : PersistentObject, IPropertyType
{
    public PropertyTypeBase()
    {

    }

    public PropertyTypeBase(string propertyName, string displayName)
    {
        PropertyName = propertyName;
        DisplayName = displayName;
    }

   ....

 }

public class StringType : PropertyTypeBase
{
    private ObjectType _objectType;

    public StringType()
    {
        _objectType = new ObjectType(typeof(string));
    }

    public StringType(string propertyName, string displayName)
        : base()
    {
        PropertyName = propertyName;
        DisplayName = displayName;
    }

    public override ObjectType ObjectType
    {
        get { return _objectType; }
    }
}

when  ContainerBootstrapper.BootstrapDefaultContainer(); execute  I see this line of error:
StructureMap Exception Code:  200

Could not find an Instance named "StringType" for PluginType Azarakhsh.Domain.Core.AdaptiveObjectModel.Interface.IPropertyType
the calling code:
 public IPropertyType GetPropertyType(IIdentityObject identityObject, string name)
    {
        string[] Properties = name.Split('.');

        object Result = identityObject;

        foreach (var Property in Properties)
            Result = Result.GetType().GetProperty(Property).PropertyType.Name;

        IPropertyType propertyType = StructureMap.ObjectFactory.GetNamedInstance<IPropertyType>  (Result + "Type");
        if (propertyType==null)
            throw new Exception("Property type not found");

        return propertyType;
    }

what is the problem?

A: You are trying to get a named instance, but from what I can see of the code you have provided, you dont name your instances. The line of code that name your instances is commented out.
But even if you would just use the ObjectFactory.GetInstance<IPropertyType>(); here, you would have got an error because structuremap dont know what constructor to use. There are several solutions to theis problem.

*

*Change your design so you only have one constructor

*Mark your default constructor with the [DefaultConstructor] attribute, then it will work.

*You can register it with objectFactory manually with something like this:
x.For().Use().Ctor("propertyName").Is("someValue").Ctor("displayName").Is("someValue");

*You can write a custom registrationconvention as described here


Q: Angular2 Component is not defined I am building up an Angular2 app, but my files aren't compiled correctly.
Found some similar issues, but no solution worked to me.
I am getting Error in console:
(index):19 Error: (SystemJS) ReleasesComponent is not defined
ReferenceError: ReleasesComponent is not defined
    at eval (http://localhost:3000/app/app.component.js:21:26)
    at Object.eval (http://localhost:3000/app/app.component.js:27:2)
    at eval (http://localhost:3000/app/app.component.js:30:4)
    at eval (http://localhost:3000/app/app.component.js:31:3)
    at eval (<anonymous>)
    at Object.eval (http://localhost:3000/app/app.module.js:15:23)
    at eval (http://localhost:3000/app/app.module.js:48:4)
    at eval (http://localhost:3000/app/app.module.js:49:3)
    at eval (<anonymous>)
Evaluating http://localhost:3000/app/app.component.js
Evaluating http://localhost:3000/app/app.module.js
Evaluating http://localhost:3000/app/main.js
Error loading http://localhost:3000/app/main.js
    at eval (http://localhost:3000/app/app.component.js:21:26)
    at Object.eval (http://localhost:3000/app/app.component.js:27:2)
    at eval (http://localhost:3000/app/app.component.js:30:4)
    at eval (http://localhost:3000/app/app.component.js:31:3)
    at eval (<anonymous>)
    at Object.eval (http://localhost:3000/app/app.module.js:15:23)
    at eval (http://localhost:3000/app/app.module.js:48:4)
    at eval (http://localhost:3000/app/app.module.js:49:3)
    at eval (<anonymous>)
Evaluating http://localhost:3000/app/app.component.js
Evaluating http://localhost:3000/app/app.module.js
Evaluating http://localhost:3000/app/main.js
Error loading http://localhost:3000/app/main.js

app.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule, JsonpModule } from '@angular/http';

import { AppComponent }  from './app.component';
import { HomeComponent } from './home/home.component';
import { ReleasesComponent } from './releases/releases.component';
import { DistroComponent } from './distro/distro.component';
import { ContactsComponent } from './contacts/contacts.component';
import { routing } from './app.routes';

@NgModule({
  imports:      [
    BrowserModule,
    FormsModule,
    HttpModule,
    JsonpModule,
    routing
  ],

  declarations: [
    AppComponent,
    HomeComponent,
    ReleasesComponent,
  DistroComponent,
    ContactsComponent
  ],

   bootstrap: [ AppComponent ]
 })
export class AppModule { }

releases.component.ts
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'releases',
  templateUrl: 'app/releases/releases.component.html',
  providers: [ReleasesService]
})

export class ReleasesComponent implements OnInit {
 releases: Observable<Array<string>>;

constructor(private releasesService: ReleasesService) {
}

ngOnInit() {
  this.releases = this.releasesService.getReleases();
 }
}

tsconfig.json
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
 }
}

index.html
<!DOCTYPE html>
<html>
<head>
<base href="/">
<title>PR PR PR</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="app/assets/flex.css">
<link rel="stylesheet" href="app/assets/styles.css">

<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>

<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>

<script src="systemjs.config.js"></script>
<script>
  System.import('app').catch(function(err){ console.error(err); });
</script>
</head>

<body>
<my-app>Loading AppComponent content here ...</my-app>
</body>
</html>

app.component.ts
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { ReleasesComponent } from './releases/releases.component';
import { ReleasesService } from './releases/releases.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  directives: [ReleasesComponent],
  providers: [Http, ReleasesService]
})
export class AppComponent  { name = 'My name'; }

Folders structure

A: You are wrong with the path name. Look at the below code.
import { Component } from '@angular/core';
import { Http } from '@angular/http';
//modified the below lines
import { ReleasesComponent } from './app/releases/releases.component';
import { ReleasesService } from './app/releases/releases.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  directives: [ReleasesComponent],
  providers: [Http, ReleasesService]
})
export class AppComponent  { name = 'My name'; }

Also replace these in all the import statements where ever ReleasesComponent  and ReleasesService is needed.
Alternatively, you can also use
import { ReleasesComponent } from './../app/releases/releases.component';
import { ReleasesService } from './../app/releases/releases.service';

A: Seems NgModule reference is missing. Import NgModule and FormModue in app.module.ts
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';