Programs & Examples On #Tmp

The traditional name of directories (especially on Unix and Unix-like operating systems) used to store temporary files. Also, the filename extension of temporary files.

Changing the tmp folder of mysql

You can also set the TMPDIR environment variable.

In some situations (Docker in my case) it's more convenient to set an environment variable than to update a config file.

How to select the last column of dataframe

Just to add to @Anshul Singh Suryan's answer:

When we split the dataframe to just get the last column:

If we split like:

y = df.iloc[:,-1:] - y remains a dataframe

However, if we split like

y = df.iloc[:,-1] - y becomes a Series.

This is a notable difference that I've found in the two approaches. If you don't care about the resultant type, you can use either of the two. Otherwise you need to take care of the above findings.

This is applicable for any number of rows you want to extract and not just the last row. For example, if you want last n number of rows of a dataframe, where n is any integer less than or equal to the number of columns present in the dataframe, then you can easily do the following:

y = df.iloc[:,n:]

Replace n by the number of columns you want. Same is true for rows as well.

How do I pass along variables with XMLHTTPRequest

Manually formatting the query string is fine for simple situations. But it can become tedious when there are many parameters.

You could write a simple utility function that handles building the query formatting for you.

function formatParams( params ){
  return "?" + Object
        .keys(params)
        .map(function(key){
          return key+"="+encodeURIComponent(params[key])
        })
        .join("&")
}

And you would use it this way to build a request.

var endpoint = "https://api.example.com/endpoint"
var params = {
  a: 1, 
  b: 2,
  c: 3
}

var url = endpoint + formatParams(params)
//=> "https://api.example.com/endpoint?a=1&b=2&c=3"

There are many utility functions available for manipulating URL's. If you have JQuery in your project you could give http://api.jquery.com/jquery.param/ a try.

It is similar to the above example function, but handles recursively serializing nested objects and arrays.

Showing the same file in both columns of a Sublime Text window

I regularly work on the same file in 2 different positions. I solved this in Sublime Text 3 using origami and chain with some additional config.

My workflow is Ctrl + k + 2 splits the view of the file in two (horizontal) panes with the lower one active. Use Ctrl + k + o to toggle between the panes. When done ensure the lower pane is the active and press Ctrl + F4 to close the duplicated view and the pane.

In sublime global settings (not origami settings!) add

"origami_auto_close_empty_panes": true,

Add the following shortcuts

  { "keys": ["ctrl+k", "2"], 
    "command": "chain", 
    "args": {
      "commands": [
        ["create_pane", {"direction": "down"}],
        ["clone_file_to_pane", {"direction": "down"}],
      ],
    }
  },

  { "keys": ["ctrl+k", "o"], "command": "focus_neighboring_group" },

jQuery Combobox/select autocomplete?

[edit] The lovely chosen jQuery plugin has been bought to my attention, looks like a great alternative to me.

Or if you just want to use jQuery autocomplete, I've extended the combobox example to support defaults and remove the tooltips to give what I think is more expected behaviour. Try it out.

(function ($) {
    $.widget("ui.combobox", {
        _create: function () {
            var input,
              that = this,
              wasOpen = false,
              select = this.element.hide(),
              selected = select.children(":selected"),
              defaultValue = selected.text() || "",
              wrapper = this.wrapper = $("<span>")
                .addClass("ui-combobox")
                .insertAfter(select);

            function removeIfInvalid(element) {
                var value = $(element).val(),
                  matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(value) + "$", "i"),
                  valid = false;
                select.children("option").each(function () {
                    if ($(this).text().match(matcher)) {
                        this.selected = valid = true;
                        return false;
                    }
                });

                if (!valid) {
                    // remove invalid value, as it didn't match anything
                    $(element).val(defaultValue);
                    select.val(defaultValue);
                    input.data("ui-autocomplete").term = "";
                }
            }

            input = $("<input>")
              .appendTo(wrapper)
              .val(defaultValue)
              .attr("title", "")
              .addClass("ui-state-default ui-combobox-input")
              .width(select.width())
              .autocomplete({
                  delay: 0,
                  minLength: 0,
                  autoFocus: true,
                  source: function (request, response) {
                      var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                      response(select.children("option").map(function () {
                          var text = $(this).text();
                          if (this.value && (!request.term || matcher.test(text)))
                              return {
                                  label: text.replace(
                                    new RegExp(
                                      "(?![^&;]+;)(?!<[^<>]*)(" +
                                      $.ui.autocomplete.escapeRegex(request.term) +
                                      ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                    ), "<strong>$1</strong>"),
                                  value: text,
                                  option: this
                              };
                      }));
                  },
                  select: function (event, ui) {
                      ui.item.option.selected = true;
                      that._trigger("selected", event, {
                          item: ui.item.option
                      });
                  },
                  change: function (event, ui) {
                      if (!ui.item) {
                          removeIfInvalid(this);
                      }
                  }
              })
              .addClass("ui-widget ui-widget-content ui-corner-left");

            input.data("ui-autocomplete")._renderItem = function (ul, item) {
                return $("<li>")
                  .append("<a>" + item.label + "</a>")
                  .appendTo(ul);
            };

            $("<a>")
              .attr("tabIndex", -1)
              .appendTo(wrapper)
              .button({
                  icons: {
                      primary: "ui-icon-triangle-1-s"
                  },
                  text: false
              })
              .removeClass("ui-corner-all")
              .addClass("ui-corner-right ui-combobox-toggle")
              .mousedown(function () {
                  wasOpen = input.autocomplete("widget").is(":visible");
              })
              .click(function () {
                  input.focus();

                  // close if already visible
                  if (wasOpen) {
                      return;
                  }

                  // pass empty string as value to search for, displaying all results
                  input.autocomplete("search", "");
              });
        },

        _destroy: function () {
            this.wrapper.remove();
            this.element.show();
        }
    });
})(jQuery);

Parsing JSON from XmlHttpRequest.responseJSON

Note: I've only tested this in Chrome.

it adds a prototype function to the XMLHttpRequest .. XHR2,

in XHR 1 you probably just need to replace this.response with this.responseText

Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){
 return JSON.parse(this.response);
},writable:false,enumerable:false});

to return the json in xhr2

xhr.onload=function(){
 console.log(this.responseJSON());
}

EDIT

If you plan to use XHR with arraybuffer or other response types then you have to check if the response is a string.

in any case you have to add more checks e.g. if it's not able to parse the json.

Object.defineProperty(XMLHttpRequest.prototype,'responseJSON',{value:function(){
 return (typeof this.response==='string'?JSON.parse(this.response):this.response);
},writable:false,enumerable:false});

SQL Server datetime LIKE select?

There's no direct support for LIKE operator against DATETIME variables, but you can always cast the DATETIME to a VARCHAR:

SELECT (list of fields) FROM YourTable
WHERE CONVERT(VARCHAR(25), register_date, 126) LIKE '2009-10-10%'

Check the MSDN docs for a complete list of available "styles" in the CONVERT function.

Marc

Add a common Legend for combined ggplots

You may also use ggarrange from ggpubr package and set "common.legend = TRUE":

library(ggpubr)

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data = dsamp, colour = clarity)
p2 <- qplot(cut, price, data = dsamp, colour = clarity)
p3 <- qplot(color, price, data = dsamp, colour = clarity)
p4 <- qplot(depth, price, data = dsamp, colour = clarity) 

ggarrange(p1, p2, p3, p4, ncol=2, nrow=2, common.legend = TRUE, legend="bottom")

enter image description here

C# find highest array value and index

This is not the most glamorous way but works.

(must have using System.Linq;)

 int maxValue = anArray.Max();
 int maxIndex = anArray.ToList().IndexOf(maxValue);

How to check whether input value is integer or float?

You can use Scanner Class to find whether a given number could be read as Int or Float type.

 import java.util.Scanner;
 public class Test {
     public static void main(String args[] ) throws Exception {

     Scanner sc=new Scanner(System.in);

     if(sc.hasNextInt())
         System.out.println("This input is  of type Integer");
     else if(sc.hasNextFloat())
         System.out.println("This input is  of type Float");
     else
         System.out.println("This is something else");
     }
}

Maximum on http header values?

No, HTTP does not define any limit. However most web servers do limit size of headers they accept. For example in Apache default limit is 8KB, in IIS it's 16K. Server will return 413 Entity Too Large error if headers size exceeds that limit.

Related question: How big can a user agent string get?

Entity Framework Timeouts

This is what I've fund out. Maybe it will help to someone:

So here we go:

If You use LINQ with EF looking for some exact elements contained in the list like this:

await context.MyObject1.Include("MyObject2").Where(t => IdList.Contains(t.MyObjectId)).ToListAsync();

everything is going fine until IdList contains more than one Id.

The “timeout” problem comes out if the list contains just one Id. To resolve the issue use if condition to check number of ids in IdList.

Example:

if (IdList.Count == 1)
{
    result = await entities. MyObject1.Include("MyObject2").Where(t => IdList.FirstOrDefault()==t. MyObjectId).ToListAsync();
}
else
{
    result = await entities. MyObject1.Include("MyObject2").Where(t => IdList.Contains(t. MyObjectId)).ToListAsync();
}

Explanation:

Simply try to use Sql Profiler and check the Select statement generated by Entity frameeork. …

Update statement with inner join on Oracle

 UPDATE ( SELECT t1.value, t2.CODE
          FROM table1 t1
          INNER JOIN table2 t2 ON t1.Value = t2.DESC
          WHERE t1.UPDATETYPE='blah')
 SET t1.Value= t2.CODE

Get domain name from given url

// groovy
String hostname ={url -> url[(url.indexOf('://')+ 3)..-1]?.split('/')[0]? }

hostname('http://hello.world.com/something') // return 'hello.world.com'
hostname('docker://quay.io/skopeo/stable') // return 'quay.io'

Why does .NET foreach loop throw NullRefException when collection is null?

I think the explanation of why exception is thrown is very clear with the answers provided here. I just wish to complement with the way I usually work with these collections. Because, some times, I use the collection more then once and have to test if null every time. To avoid that, I do the following:

    var returnArray = DoSomething() ?? Enumerable.Empty<int>();

    foreach (int i in returnArray)
    {
        // do some more stuff
    }

This way we can use the collection as much as we want without fear the exception and we don't polute the code with excessive conditional statements.

Using the null check operator ?. is also a great approach. But, in case of arrays (like the example in the question), it should be transformed into List before:

    int[] returnArray = DoSomething();

    returnArray?.ToList().ForEach((i) =>
    {
        // do some more stuff
    });

How to distinguish mouse "click" and "drag"

You could do this:

_x000D_
_x000D_
var div = document.getElementById("div");
div.addEventListener("mousedown", function() {
  window.addEventListener("mousemove", drag);
  window.addEventListener("mouseup", lift);
  var didDrag = false;
  function drag() {
    //when the person drags their mouse while holding the mouse button down
    didDrag = true;
    div.innerHTML = "drag"
  }
  function lift() {
    //when the person lifts mouse
    if (!didDrag) {
      //if the person didn't drag
      div.innerHTML = "click";
    } else div.innerHTML = "drag";
    //delete event listeners so that it doesn't keep saying drag
    window.removeEventListener("mousemove", drag)
    window.removeEventListener("mouseup", this)
  }
})
_x000D_
body {
  outline: none;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  font-family: Arial, Helvetica, sans-serif;
  overflow: hidden;
}
#div {
  /* calculating -5px for each side of border in case border-box doesn't work */
  width: calc(100vw - 10px);
  height: calc(100vh - 10px);
  border: 5px solid orange;
  background-color: yellow;
  font-weight: 700;
  display: grid;
  place-items: center;
  user-select: none;
  cursor: pointer;
  padding: 0;
  margin: 0;
}
_x000D_
<html>
  <body>
    <div id="div">Click me or drag me.</div>
  </body>
</html>
_x000D_
_x000D_
_x000D_

How do I test if a recordSet is empty? isNull?

I would check the "End of File" flag:

If temp_rst1.EOF Or temp_rst2.EOF Then MsgBox "null"

Bash scripting missing ']'

You're missing a space after "p1":

if [ -s "p1" ];

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

To send mail using Gmail SMTP, need to change your account setting. Login into your gmail accout then follow the link below to change your gmail account setting to send mail using your apps and program. https://www.google.com/settings/security/lesssecureapps

Note: This setting is not available for accounts with 2-Step Verification enabled. Such accounts require an application-specific password for less secure apps access.

uppercase first character in a variable with bash

To capitalize first word only:

foo='one two three'
foo="${foo^}"
echo $foo

One two three


To capitalize every word in the variable:

foo="one two three"
foo=( $foo ) # without quotes
foo="${foo[@]^}"
echo $foo

One Two Three


(works in bash 4+)

The best node module for XML parsing

You can try xml2js. It's a simple XML to JavaScript object converter. It gets your XML converted to a JS object so that you can access its content with ease.

Here are some other options:

  1. libxmljs
  2. xml-stream
  3. xmldoc
  4. cheerio – implements a subset of core jQuery for XML (and HTML)

I have used xml2js and it has worked fine for me. The rest you might have to try out for yourself.

Android: Test Push Notification online (Google Cloud Messaging)

Found a very easy way to do this.

Open http://phpfiddle.org/

Paste following php script in box. In php script set API_ACCESS_KEY, set device ids separated by coma.

Press F9 or click Run.

Have fun ;)

<?php


// API access key from Google API's Console
define( 'API_ACCESS_KEY', 'YOUR-API-ACCESS-KEY-GOES-HERE' );


$registrationIds = array("YOUR DEVICE IDS WILL GO HERE" );

// prep the bundle
$msg = array
(
    'message'       => 'here is a message. message',
    'title'         => 'This is a title. title',
    'subtitle'      => 'This is a subtitle. subtitle',
    'tickerText'    => 'Ticker text here...Ticker text here...Ticker text here',
    'vibrate'   => 1,
    'sound'     => 1
);

$fields = array
(
    'registration_ids'  => $registrationIds,
    'data'              => $msg
);

$headers = array
(
    'Authorization: key=' . API_ACCESS_KEY,
    'Content-Type: application/json'
);

$ch = curl_init();
curl_setopt( $ch,CURLOPT_URL, 'https://android.googleapis.com/gcm/send' );
curl_setopt( $ch,CURLOPT_POST, true );
curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
curl_setopt( $ch,CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
$result = curl_exec($ch );
curl_close( $ch );

echo $result;
?>

For FCM, google url would be: https://fcm.googleapis.com/fcm/send

For FCM v1 google url would be: https://fcm.googleapis.com/v1/projects/YOUR_GOOGLE_CONSOLE_PROJECT_ID/messages:send

Note: While creating API Access Key on google developer console, you have to use 0.0.0.0/0 as ip address. (For testing purpose).

In case of receiving invalid Registration response from GCM server, please cross check the validity of your device token. You may check the validity of your device token using following url:

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=YOUR_DEVICE_TOKEN

Some response codes:

Following is the description of some response codes you may receive from server.

{ "message_id": "XXXX" } - success
{ "message_id": "XXXX", "registration_id": "XXXX" } - success, device registration id has been changed mainly due to app re-install
{ "error": "Unavailable" } - Server not available, resend the message
{ "error": "InvalidRegistration" } - Invalid device registration Id 
{ "error": "NotRegistered"} - Application was uninstalled from the device

Use JAXB to create Object from XML String

If you want to parse using InputStreams

public Object xmlToObject(String xmlDataString) {
        Object converted = null;
        try {
        
            JAXBContext jc = JAXBContext.newInstance(Response.class);
        
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
            
            converted = unmarshaller.unmarshal(stream);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return converted;
    }

How to fill Dataset with multiple tables?

DataSet ds = new DataSet();
using (var reader = cmd.ExecuteReader())
{
    while (!reader.IsClosed)
         {
              ds.Tables.Add().Load(reader);
         }
}
return ds;

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

“tag already exists in the remote" error after recreating the git tag

Some good answers here. Especially the one by @torek. I thought I'd add this work-around with a little explanation for those in a rush.

To summarize, what happens is that when you move a tag locally, it changes the tag from a non-Null commit value to a different value. However, because git (as a default behavior) doesn't allow changing non-Null remote tags, you can't push the change.

The work-around is to delete the tag (and tick remove all remotes). Then create the same tag and push.

How to get form input array into PHP array

I know its a bit late now, but you could do something such as this:

function AddToArray ($post_information) {
    //Create the return array
    $return = array();
    //Iterate through the array passed
    foreach ($post_information as $key => $value) {
        //Append the key and value to the array, e.g.
            //$_POST['keys'] = "values" would be in the array as "keys"=>"values"
        $return[$key] = $value;
    }
    //Return the created array
    return $return;
}

The test with:

if (isset($_POST['submit'])) {
    var_dump(AddToArray($_POST));
}

This for me produced:

array (size=1)
  0 => 
    array (size=5)
      'stake' => string '0' (length=1)
      'odds' => string '' (length=0)
      'ew' => string 'false' (length=5)
      'ew_deduction' => string '' (length=0)
      'submit' => string 'Open' (length=4)

Get list of certificates from the certificate store in C#

Yes -- the X509Store.Certificates property returns a snapshot of the X.509 certificate store.

Programmatically Lighten or Darken a hex color (or rgb, and blend colors)

I've long wanted to be able to produce tints/shades of colours, here is my JavaScript solution:

const varyHue = function (hueIn, pcIn) {
    const truncate = function (valIn) {
        if (valIn > 255) {
            valIn = 255;
        } else if (valIn < 0)  {
            valIn = 0;
        }
        return valIn;
    };

    let red   = parseInt(hueIn.substring(0, 2), 16);
    let green = parseInt(hueIn.substring(2, 4), 16);
    let blue  = parseInt(hueIn.substring(4, 6), 16);
    let pc    = parseInt(pcIn, 10);    //shade positive, tint negative
    let max   = 0;
    let dif   = 0;

    max = red;

    if (pc < 0) {    //tint: make lighter
        if (green < max) {
            max = green;
        }

        if (blue < max) {
            max = blue;
        }

        dif = parseInt(((Math.abs(pc) / 100) * (255 - max)), 10);

        return leftPad(((truncate(red + dif)).toString(16)), '0', 2)  + leftPad(((truncate(green + dif)).toString(16)), '0', 2) + leftPad(((truncate(blue + dif)).toString(16)), '0', 2);
    } else {    //shade: make darker
        if (green > max) {
            max = green;
        }

        if (blue > max) {
            max = blue;
        }

        dif = parseInt(((pc / 100) * max), 10);

        return leftPad(((truncate(red - dif)).toString(16)), '0', 2)  + leftPad(((truncate(green - dif)).toString(16)), '0', 2) + leftPad(((truncate(blue - dif)).toString(16)), '0', 2);
    }
};

Node.js connect only works on localhost

Most probably your server socket is bound to the loopback IP address 127.0.0.1 instead of the "all IP addresses" symbolic IP 0.0.0.0 (note this is NOT a netmask). To confirm this, run sudo netstat -ntlp (If you are on linux) or netstat -an -f inet -p tcp | grep LISTEN (OSX) and check which IP your process is bound to (look for the line with ":3000"). If you see "127.0.0.1", that's the problem. Fix it by passing "0.0.0.0" to the listen call:

var app = connect().use(connect.static('public')).listen(3000, "0.0.0.0");

slashes in url variables

Check out this w3schools page about "HTML URL Encoding Reference": https://www.w3schools.com/tags/ref_urlencode.asp

for / you would escape with %2F

How to receive JSON as an MVC 5 action method parameter

There are a couple issues here. First, you need to make sure to bind your JSON object back to the model in the controller. This is done by changing

data: JSON.stringify(usersRoles),

to

data: { model: JSON.stringify(usersRoles) },

Secondly, you aren't binding types correctly with your jquery call. If you remove

contentType: "application/json; charset=utf-8",

it will inherently bind back to a string.

All together, use the first ActionResult method and the following jquery ajax call:

    jQuery.ajax({
        type: "POST",
        url: "@Url.Action("AddUser")",
        dataType: "json",
        data: { model: JSON.stringify(usersRoles) },
        success: function (data) { alert(data); },
        failure: function (errMsg) {
        alert(errMsg);
        }
   });

How to handle errors with boto3?

In case you have to deal with the arguably unfriendly logs client (CloudWatch Logs put-log-events), this is what I had to do to properly catch Boto3 client exceptions:

try:
    ### Boto3 client code here...

except boto_exceptions.ClientError as error:
    Log.warning("Catched client error code %s",
                error.response['Error']['Code'])

    if error.response['Error']['Code'] in ["DataAlreadyAcceptedException",
                                           "InvalidSequenceTokenException"]:
        Log.debug(
            "Fetching sequence_token from boto error response['Error']['Message'] %s",
            error.response["Error"]["Message"])
        # NOTE: apparently there's no sequenceToken attribute in the response so we have
        # to parse response["Error"]["Message"] string
        sequence_token = error.response["Error"]["Message"].split(":")[-1].strip(" ")
        Log.debug("Setting sequence_token to %s", sequence_token)

This works both at first attempt (with empty LogStream) and subsequent ones.

Python: Figure out local timezone

Try dateutil, which has a tzlocal type that does what you need.

Terminating a Java Program

System.exit() terminates the JVM. Nothing after System.exit() is executed. Return is generally used for exiting a method. If the return type is void, then you could use return; But I don't think is a good practice to do it in the main method. You don't have to do anything for terminate a program, unless infinite loop or some strange other execution flows.

Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified

Add your dependencies like mongodb,web,jpa. Delete/clear the remainings.

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
</dependencies>

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

How to add external library in IntelliJ IDEA?

Intellij IDEA 15: File->Project Structure...->Project Settings->Libraries

Should IBOutlets be strong or weak under ARC?

The current recommended best practice from Apple is for IBOutlets to be strong unless weak is specifically needed to avoid a retain cycle. As Johannes mentioned above, this was commented on in the "Implementing UI Designs in Interface Builder" session from WWDC 2015 where an Apple Engineer said:

And the last option I want to point out is the storage type, which can either be strong or weak. In general you should make your outlet strong, especially if you are connecting an outlet to a subview or to a constraint that's not always going to be retained by the view hierarchy. The only time you really need to make an outlet weak is if you have a custom view that references something back up the view hierarchy and in general that's not recommended.

I asked about this on Twitter to an engineer on the IB team and he confirmed that strong should be the default and that the developer docs are being updated.

https://twitter.com/_danielhall/status/620716996326350848 https://twitter.com/_danielhall/status/620717252216623104

Test a weekly cron job

None of these answers fit my specific situation, which was that I wanted to run one specific cron job, just once, and run it immediately.

I'm on a Ubuntu server, and I use cPanel to setup my cron jobs.

I simply wrote down my current settings, and then edited them to be one minute from now. When I fixed another bug, I just edited it again to one minute from now. And when I was all done, I just reset the settings back to how they were before.

Example: It's 4:34pm right now, so I put 35 16 * * *, for it to run at 16:35.

It worked like a charm, and the most I ever had to wait was a little less than one minute.

I thought this was a better option than some of the other answers because I didn't want to run all of my weekly crons, and I didn't want the job to run every minute. It takes me a few minutes to fix whatever the issues were before I'm ready to test it again. Hopefully this helps someone.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

For those who use ASP.NET Identity 2.1 and have changed the primary key from the default string to either int or Guid, if you're still getting

EntityType 'xxxxUserLogin' has no key defined. Define the key for this EntityType.

EntityType 'xxxxUserRole' has no key defined. Define the key for this EntityType.

you probably just forgot to specify the new key type on IdentityDbContext:

public class AppIdentityDbContext : IdentityDbContext<
    AppUser, AppRole, int, AppUserLogin, AppUserRole, AppUserClaim>
{
    public AppIdentityDbContext()
        : base("MY_CONNECTION_STRING")
    {
    }
    ......
}

If you just have

public class AppIdentityDbContext : IdentityDbContext
{
    ......
}

or even

public class AppIdentityDbContext : IdentityDbContext<AppUser>
{
    ......
}

you will get that 'no key defined' error when you are trying to add migrations or update the database.

How to replace DOM element in place using Javascript?

I had a similar issue and found this thread. Replace didn't work for me, and going by the parent was difficult for my situation. Inner Html replaced the children, which wasn't what I wanted either. Using outerHTML got the job done. Hope this helps someone else!

currEl = <div>hello</div>
newElem = <span>Goodbye</span>
currEl.outerHTML = newElem
# currEl = <span>Goodbye</span>

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

If you want the return to trigger an action only when the user is in the textbox, you can assign the desired button the AcceptButton control, like this.

    private void textBox_Enter(object sender, EventArgs e)
    {
        ActiveForm.AcceptButton = Button1; // Button1 will be 'clicked' when user presses return
    }

    private void textBox_Leave(object sender, EventArgs e)
    {
        ActiveForm.AcceptButton = null; // remove "return" button behavior
    }

Is it possible to make input fields read-only through CSS?

You don't set the behavior of controls via CSS, only their styling.You can use jquery or simple javascript to change the property of the fields.

Fastest way to Remove Duplicate Value from a list<> by lambda

List<long> distinctlongs = longs.Distinct().OrderBy(x => x).ToList();

Mysql password expired. Can't connect

restart MySQL server with --skip-grant-tables option And then set a new root password

$ mysql -u root
mysql> USE mysql;
mysql> UPDATE user SET password=PASSWORD("NEWPASSWORD") WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> quit

Now if you need, you can update mysql.user table(field password_expired='N') not to expire the password.

How do I log a Python error with debug information?

Using exc_info options may be better, to allow you to choose the error level (if you use exception, it will always be at the error level):

try:
    # do something here
except Exception as e:
    logging.critical(e, exc_info=True)  # log exception info at CRITICAL log level

How to extract a substring using regex

You don't need regex for this.

Add apache commons lang to your project (http://commons.apache.org/proper/commons-lang/), then use:

String dataYouWant = StringUtils.substringBetween(mydata, "'");

Changes in import statement python3

Added another case to Michal Górny's answer:

Note that relative imports are based on the name of the current module. Since the name of the main module is always "__main__", modules intended for use as the main module of a Python application must always use absolute imports.

Make absolute positioned div expand parent div height

Also consider next approach:

CSS:

.parent {
  height: 100%;
}
.parent:after {
  content: '';
  display: block;
}

Also since you are trying to reposition divs consider css grid

PHP XML how to output nice format

Two different issues here:

  • Set the formatOutput and preserveWhiteSpace attributes to TRUE to generate formatted XML:

    $doc->formatOutput = TRUE;
    $doc->preserveWhiteSpace = TRUE;
    
  • Many web browsers (namely Internet Explorer and Firefox) format XML when they display it. Use either the View Source feature or a regular text editor to inspect the output.


See also xmlEncoding and encoding.

Storing a Key Value Array into a compact JSON string

For use key/value pair in json use an object and don't use array

Find name/value in array is hard but in object is easy

Ex:

_x000D_
_x000D_
var exObj = {_x000D_
  "mainData": {_x000D_
    "slide0001.html": "Looking Ahead",_x000D_
    "slide0008.html": "Forecast",_x000D_
    "slide0021.html": "Summary",_x000D_
    // another THOUSANDS KEY VALUE PAIRS_x000D_
    // ..._x000D_
  },_x000D_
  "otherdata" : { "one": "1", "two": "2", "three": "3" }_x000D_
};_x000D_
var mainData = exObj.mainData;_x000D_
// for use:_x000D_
Object.keys(mainData).forEach(function(n,i){_x000D_
  var v = mainData[n];_x000D_
  console.log('name' + i + ': ' + n + ', value' + i + ': ' + v);_x000D_
});_x000D_
_x000D_
// and string length is minimum_x000D_
console.log(JSON.stringify(exObj));_x000D_
console.log(JSON.stringify(exObj).length);
_x000D_
_x000D_
_x000D_

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

I had the same problem but got round it by setting AutoPostBack to true and in an update panel set the trigger to the dropdownlist control id and event name to SelectedIndexChanged e.g.

    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" enableViewState="true">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="ddl1" EventName="SelectedIndexChanged" />
        </Triggers>
        <ContentTemplate>
            <asp:DropDownList ID="ddl1" runat="server" ClientIDMode="Static" OnSelectedIndexChanged="ddl1_SelectedIndexChanged" AutoPostBack="true" ViewStateMode="Enabled">
                <asp:ListItem Text="--Please select a item--" Value="0" />
            </asp:DropDownList>
        </ContentTemplate>
    </asp:UpdatePanel>

Using String Format to show decimal up to 2 places or simple integer

If none of the other answers work for you, it may be because you are binding the ContentProperty of a control in the OnLoad function, which means this won't work:

private void UserControl_Load(object sender, RoutedEventArgs e)
{
  Bind.SetBindingElement(labelName, String.Format("{0:0.00}", PropertyName), Label.ContentProperty) 
}

The solution is simple: there is a ContentStringFormat property in the xaml. So when you create the label do this:

//if you want the decimal places definite
<Label Content="0" Name="labelName" ContentStringFormat="0.00"/>

Or

//if you want the decimal places to be optional
<Label Content="0" Name="labelName" ContentStringFormat="0.##"/>

Is there a way to check for both `null` and `undefined`?

In TypeScript 3.7 we have now Optional chaining and Nullish Coalescing to check null and undefined in the same time, example:

let x = foo?.bar.baz();

this code will check if foo is defined otherwise it will return undefined

old way :

if(foo != null && foo != undefined) {
   x = foo.bar.baz();
} 

this:

let x = (foo === null || foo === undefined) ? undefined : foo.bar();

if (foo && foo.bar && foo.bar.baz) { // ... }

With optional chaining will be:

let x = foo?.bar();

if (foo?.bar?.baz) { // ... }

another new feature is Nullish Coalescing, example:

let x = foo ?? bar(); // return foo if it's not null or undefined otherwise calculate bar

old way:

let x = (foo !== null && foo !== undefined) ?
foo :
bar();

BONUS enter image description here

How to disable spring security for particular url

I faced the same problem here's the solution:(Explained)

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
            .antMatchers(HttpMethod.POST,"/form").hasRole("ADMIN")  // Specific api method request based on role.
            .antMatchers("/home","/basic").permitAll()  // permited urls to guest users(without login).
            .anyRequest().authenticated()
            .and()
        .formLogin()       // not specified form page to use default login page of spring security.
            .permitAll()
             .and()
        .logout().deleteCookies("JSESSIONID")  // delete memory of browser after logout.

        .and()
        .rememberMe().key("uniqueAndSecret"); // remember me check box enabled.

    http.csrf().disable();  **// ADD THIS CODE TO DISABLE CSRF IN PROJECT.**
}

Build Android Studio app via command line

Try this (OS X only):

brew install homebrew/versions/gradle110
gradle build

You can use gradle tasks to see all tasks available for the current project. No Android Studio is needed here.

What is the most efficient way to deep clone an object in JavaScript?

There’s a library (called “clone”), that does this quite well. It provides the most complete recursive cloning/copying of arbitrary objects that I know of. It also supports circular references, which is not covered by the other answers, yet.

You can find it on npm, too. It can be used for the browser as well as Node.js.

Here is an example on how to use it:

Install it with

npm install clone

or package it with Ender.

ender build clone [...]

You can also download the source code manually.

Then you can use it in your source code.

var clone = require('clone');

var a = { foo: { bar: 'baz' } };  // inital value of a
var b = clone(a);                 // clone a -> b
a.foo.bar = 'foo';                // change a

console.log(a);                   // { foo: { bar: 'foo' } }
console.log(b);                   // { foo: { bar: 'baz' } }

(Disclaimer: I’m the author of the library.)

How to resolve "Could not find schema information for the element/attribute <xxx>"?

What fixed the "Could not find schema information for the element ..." for me was

  • Opening my app.config.
  • Right-clicking in the editor window and selecting Properties.
  • In the properties box, there is a row called Schemas, I clicked that row and selected the browse ... box that appears in the row.
  • I simply checked the use box for all the rows that had my project somewhere in them, and also for the current version of .Net I was using. For instance: DotNetConfig30.xsd.

After that everything went to working fine.

How those schema rows with my project got unchecked I'm not sure, but when I made sure they were checked, I was back in business.

Mapping a JDBC ResultSet to an object

No need of storing resultSet values into String and again setting into POJO class. Instead set at the time you are retrieving.

Or best way switch to ORM tools like hibernate instead of JDBC which maps your POJO object direct to database.

But as of now use this:

List<User> users=new ArrayList<User>();

while(rs.next()) {
   User user = new User();      
   user.setUserId(rs.getString("UserId"));
   user.setFName(rs.getString("FirstName"));
  ...
  ...
  ...


  users.add(user);
} 

How do I disable text selection with CSS or JavaScript?

You can use JavaScript to do what you want:


if (document.addEventListener !== undefined) {
  // Not IE
  document.addEventListener('click', checkSelection, false);
} else {
  // IE
  document.attachEvent('onclick', checkSelection);
}

function checkSelection() {
    var sel = {};
    if (window.getSelection) {
        // Mozilla
        sel = window.getSelection();
    } else if (document.selection) {
        // IE
        sel = document.selection.createRange();
    }

    // Mozilla
    if (sel.rangeCount) {
        sel.removeAllRanges();
        return;
    }

    // IE
    if (sel.text > '') {
        document.selection.empty();
        return;
    }
}

Soap box: You really shouldn't be screwing with the client's user agent in this manner. If the client wants to select things on the document, then they should be able to select things on the document. It doesn't matter if you don't like the highlight color, because you aren't the one viewing the document.

Easiest way to convert a Blob into a byte array

the mySql blob class has the following function :

blob.getBytes

use it like this:

//(assuming you have a ResultSet named RS)
Blob blob = rs.getBlob("SomeDatabaseField");

int blobLength = (int) blob.length();  
byte[] blobAsBytes = blob.getBytes(1, blobLength);

//release the blob and free up memory. (since JDBC 4.0)
blob.free();

Remove all stylings (border, glow) from textarea

try this:

textarea {
        border-style: none;
        border-color: Transparent;
        overflow: auto;
        outline: none;
      }

jsbin: http://jsbin.com/orozon/2/

TCP vs UDP on video stream

It depends. How critical is the content you are streaming? If critical use TCP. This may cause issues in bandwidth, video quality (you might have to use a lower quality to deal with latency), and latency. But if you need the content to guaranteed get there, use it.

Otherwise UDP should be fine if the stream is not critical and would be preferred because UDP tends to have less overhead.

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Another way

@Html.TextAreaFor(model => model.Comments[0].Comment)

And in your css do this

textarea
{
    font-family: inherit;
    width: 650px;
    height: 65px;
}

That DataType dealie allows carriage returns in the data, not everybody likes those.

Multiple values in single-value context

In case of a multi-value return function you can't refer to fields or methods of a specific value of the result when calling the function.

And if one of them is an error, it's there for a reason (which is the function might fail) and you should not bypass it because if you do, your subsequent code might also fail miserably (e.g. resulting in runtime panic).

However there might be situations where you know the code will not fail in any circumstances. In these cases you can provide a helper function (or method) which will discard the error (or raise a runtime panic if it still occurs).
This can be the case if you provide the input values for a function from code, and you know they work.
Great examples of this are the template and regexp packages: if you provide a valid template or regexp at compile time, you can be sure they can always be parsed without errors at runtime. For this reason the template package provides the Must(t *Template, err error) *Template function and the regexp package provides the MustCompile(str string) *Regexp function: they don't return errors because their intended use is where the input is guaranteed to be valid.

Examples:

// "text" is a valid template, parsing it will not fail
var t = template.Must(template.New("name").Parse("text"))

// `^[a-z]+\[[0-9]+\]$` is a valid regexp, always compiles
var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)

Back to your case

IF you can be certain Get() will not produce error for certain input values, you can create a helper Must() function which would not return the error but raise a runtime panic if it still occurs:

func Must(i Item, err error) Item {
    if err != nil {
        panic(err)
    }
    return i
}

But you should not use this in all cases, just when you're sure it succeeds. Usage:

val := Must(Get(1)).Value

Alternative / Simplification

You can even simplify it further if you incorporate the Get() call into your helper function, let's call it MustGet:

func MustGet(value int) Item {
    i, err := Get(value)
    if err != nil {
        panic(err)
    }
    return i
}

Usage:

val := MustGet(1).Value

See some interesting / related questions:

how to parse multiple returns in golang

Return map like 'ok' in Golang on normal functions

How do I tell Gradle to use specific JDK version?

So, I use IntelliJ for my Android project, and the following solved the issue in the IDE:

just cause it might save someone the few hours I wasted... IntelliJ -> Preferences -> Build, Execution, Deployment -> Build tools -> Maven -> Gradle

and set Gradle JVM to 1.8 make sure you also have JDK 8 installed...

NOTE: the project was compiling just fine from the command line

Push JSON Objects to array in localStorage

As of now, you can only store string values in localStorage. You'll need to serialize the array object and then store it in localStorage.

For example:

localStorage.setItem('session', a.join('|'));

or

localStorage.setItem('session', JSON.stringify(a));

How to disable Google asking permission to regularly check installed apps on my phone?

With the latest version of Lollipop, go into app. drawer and look for Google Settings. Scroll down to Security, tap iit to open, slide to the left the slider next to 'Improve harmful app. detection' to the left, then same for 'Scan device for security threats'. Exit out of that, and the annoying pop up will never appear again!

How do I get the Back Button to work with an AngularJS ui-router state machine?

history.back() and switch to previous state often give effect not that you want. For example, if you have form with tabs and each tab has own state, this just switched previous tab selected, not return from form. In case nested states, you usually need so think about witch of parent states you want to rollback.

This directive solves problem

angular.module('app', ['ui-router-back'])

<span ui-back='defaultState'> Go back </span>

It returns to state, that was active before button has displayed. Optional defaultState is state name that used when no previous state in memory. Also it restores scroll position

Code

class UiBackData {
    fromStateName: string;
    fromParams: any;
    fromStateScroll: number;
}

interface IRootScope1 extends ng.IScope {
    uiBackData: UiBackData;
}

class UiBackDirective implements ng.IDirective {
    uiBackDataSave: UiBackData;

    constructor(private $state: angular.ui.IStateService,
        private $rootScope: IRootScope1,
        private $timeout: ng.ITimeoutService) {
    }

    link: ng.IDirectiveLinkFn = (scope, element, attrs) => {
        this.uiBackDataSave = angular.copy(this.$rootScope.uiBackData);

        function parseStateRef(ref, current) {
            var preparsed = ref.match(/^\s*({[^}]*})\s*$/), parsed;
            if (preparsed) ref = current + '(' + preparsed[1] + ')';
            parsed = ref.replace(/\n/g, " ").match(/^([^(]+?)\s*(\((.*)\))?$/);
            if (!parsed || parsed.length !== 4)
                throw new Error("Invalid state ref '" + ref + "'");
            let paramExpr = parsed[3] || null;
            let copy = angular.copy(scope.$eval(paramExpr));
            return { state: parsed[1], paramExpr: copy };
        }

        element.on('click', (e) => {
            e.preventDefault();

            if (this.uiBackDataSave.fromStateName)
                this.$state.go(this.uiBackDataSave.fromStateName, this.uiBackDataSave.fromParams)
                    .then(state => {
                        // Override ui-router autoscroll 
                        this.$timeout(() => {
                            $(window).scrollTop(this.uiBackDataSave.fromStateScroll);
                        }, 500, false);
                    });
            else {
                var r = parseStateRef((<any>attrs).uiBack, this.$state.current);
                this.$state.go(r.state, r.paramExpr);
            }
        });
    };

    public static factory(): ng.IDirectiveFactory {
        const directive = ($state, $rootScope, $timeout) =>
            new UiBackDirective($state, $rootScope, $timeout);
        directive.$inject = ['$state', '$rootScope', '$timeout'];
        return directive;
    }
}

angular.module('ui-router-back')
    .directive('uiBack', UiBackDirective.factory())
    .run(['$rootScope',
        ($rootScope: IRootScope1) => {

            $rootScope.$on('$stateChangeSuccess',
                (event, toState, toParams, fromState, fromParams) => {
                    if ($rootScope.uiBackData == null)
                        $rootScope.uiBackData = new UiBackData();
                    $rootScope.uiBackData.fromStateName = fromState.name;
                    $rootScope.uiBackData.fromStateScroll = $(window).scrollTop();
                    $rootScope.uiBackData.fromParams = fromParams;
                });
        }]);

Using Google Translate in C#

The reason the first code sample doesn't work is because the layout of the page changed. As per the warning on that page: "The translated string is fetched by the RegEx close to the bottom. This could of course change, and you have to keep it up to date." I think this should work for now, at least until they change the page again.


public string TranslateText(string input, string languagePair)
{
    string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
    WebClient webClient = new WebClient();
    webClient.Encoding = System.Text.Encoding.UTF8;
    string result = webClient.DownloadString(url);
    result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
    result = result.Substring(result.IndexOf(">") + 1);
    result = result.Substring(0, result.IndexOf("</span>"));
    return result.Trim();
}

Duplicate headers received from server

Just put a pair of double quotes around your file name like this:

this.Response.AddHeader("Content-disposition", $"attachment; filename=\"{outputFileName}\"");

Unfortunately MyApp has stopped. How can I solve this?

You can also get this error message on its own, without any stack trace or any further error message.

In this case you need to make sure your Android manifest is configured correctly (including any manifest merging happening from a library and any activity that would come from a library), and pay particular attention to the first activity displayed in your application in your manifest files.

Use chrome as browser in C#?

Update for 2014:

I use geckofx, a healthy open source project that (as of this writing) keeps up to date pretty well with the latest Firefox releases.

To embed Chrome, you might consider another healthy looking open source project, Xilium.cefGlue, based on The Chromium Embedded Framework (CEF).

Both of these support WPF and Winforms, and both projects have support for .net and mono.

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Ruby can't find any root certificates to trust.

Take a look at this blog post for a solution: "Ruby 1.9 and the SSL error".

The solution is to install the curl-ca-bundle port which contains the same root certificates used by Firefox:

sudo port install curl-ca-bundle

and tell your https object to use it:

https.ca_file = '/opt/local/share/curl/curl-ca-bundle.crt'

Note that if you want your code to run on Ubuntu, you need to set the ca_path attribute instead, with the default certificates location /etc/ssl/certs.

How do I add space between two variables after a print in Python

You should use python Explicit Conversion Flag PEP-3101

'My name is {0!s:10} {1}'.format('Dunkin', 'Donuts')

'My name is Dunkin Donuts'

or

'My name is %-10s %s' % ('Dunkin', 'Donuts')

'My name is Dunkin Donuts'

https://www.python.org/dev/peps/pep-3101/

Failed to allocate memory: 8

What worked for me on Windows was:

1) Closing Eclipse 2) Running Avd UI 3) Closing all running processes, especially ones that are heavy in memory, like Chrome, explorer.exe, etc 4) Start the emulator 5) Win

How to create a static library with g++?

Create a .o file:

g++ -c header.cpp

add this file to a library, creating library if necessary:

ar rvs header.a header.o

use library:

g++ main.cpp header.a

Is there a way to collapse all code blocks in Eclipse?

Right click on the +/- sign and click collapse all or expand all.

How can you run a command in bash over and over until success?

You can use an infinite loop to achieve this:

while true
do
  read -p "Enter password" passwd
  case "$passwd" in
    <some good condition> ) break;;
  esac
done

Remove folder and its contents from git/GitHub's history

Complete copy&paste recipe, just adding the commands in the comments (for the copy-paste solution), after testing them:

git filter-branch --tree-filter 'rm -rf node_modules' --prune-empty HEAD
echo node_modules/ >> .gitignore
git add .gitignore
git commit -m 'Removing node_modules from git history'
git gc
git push origin master --force

After this, you can remove the line "node_modules/" from .gitignore

How to compare Boolean?

As object?

equals

public boolean equals(Object obj)

Returns true if and only if the argument is not null and is a Boolean object that represents the same boolean value as this object.

Overrides: equals in class Object

Parameters: obj - the object to compare with.

Returns: true if the Boolean objects represent the same value; false otherwise.

boolean a = true;
boolean b = false;

System.out.println("a.equals(b):" + ((Object)a).equals( ((Object)b) ));

Output: a.equals(b):false

Make an image responsive - the simplest way

You can try doing

<p>
  <a href="MY WEBSITE LINK" target="_blank">
    <img src="IMAGE LINK" style='width:100%;' border="0" alt="Null">
  </a>
</p>

This should scale your image if in a fluid layout.

For responsive (meaning your layout reacts to the size of the window) you can add a class to the image and use @media queries in CSS to change the width of the image.

Note that changing the height of the image will mess with the ratio.

How to activate virtualenv?

source virtualen_name/bin/activate

code

How to find sitemap.xml path on websites?

Use Google Search Operators to find it for you

search google with the below code..

inurl:domain.com filetype:xml click on this to view sitemap search example

change domain.com to the domain you want to find the sitemap. this should list all the xml files listed for the given domain.. including all sitemaps :)

Fastest method to escape HTML tags as HTML entities?

The AngularJS source code also has a version inside of angular-sanitize.js.

var SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
    // Match everything outside of normal chars and " (quote character)
    NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
/**
 * Escapes all potentially dangerous characters, so that the
 * resulting string can be safely inserted into attribute or
 * element text.
 * @param value
 * @returns {string} escaped text
 */
function encodeEntities(value) {
  return value.
    replace(/&/g, '&amp;').
    replace(SURROGATE_PAIR_REGEXP, function(value) {
      var hi = value.charCodeAt(0);
      var low = value.charCodeAt(1);
      return '&#' + (((hi - 0xD800) * 0x400) + (low - 0xDC00) + 0x10000) + ';';
    }).
    replace(NON_ALPHANUMERIC_REGEXP, function(value) {
      return '&#' + value.charCodeAt(0) + ';';
    }).
    replace(/</g, '&lt;').
    replace(/>/g, '&gt;');
}

How do I trim whitespace?

try translate

>>> import string
>>> print '\t\r\n  hello \r\n world \t\r\n'

  hello 
 world  
>>> tr = string.maketrans(string.whitespace, ' '*len(string.whitespace))
>>> '\t\r\n  hello \r\n world \t\r\n'.translate(tr)
'     hello    world    '
>>> '\t\r\n  hello \r\n world \t\r\n'.translate(tr).replace(' ', '')
'helloworld'

How to send a HTTP OPTIONS request from the command line?

The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)

OPTIONS /path

You can send an OPTIONS request with curl like this:

curl -i -X OPTIONS http://example.org/path

You may also use -v instead of -i to see more output.

OPTIONS *

To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:

curl -i --request-target "*" -X OPTIONS http://example.org

How to access parent Iframe from JavaScript

Once id of iframe is set, you can access iframe from inner document as shown below.

var iframe = parent.document.getElementById(frameElement.id);

Works well in IE, Chrome and FF.

Concatenating string and integer in python

format() method can be used to concatenate string and integer

print(s+"{}".format(i))

Send mail via CMD console

Unless you want to talk to an SMTP server directly via telnet you'd use commandline mailers like blat:

blat -to [email protected] -f [email protected] -s "mail subject" ^
  -server smtp.example.net -body "message text"

or bmail:

bmail -s smtp.example.net -t [email protected] -f [email protected] -h ^
  -a "mail subject" -b "message text"

You could also write your own mailer in VBScript or PowerShell.

Failed to serialize the response in Web API with Json

In my case I solved recreating the database. I made some changes in a model and launching Update-Database in Package Manager Console I got the following Error:

"The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Activities_dbo.Projects_ProjectId". The conflict occurred in database "TrackEmAllContext-20190530144302", table "dbo.Projects", column 'Id'."

How to get TimeZone from android mobile?

Try this code-

Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();

It will return user selected timezone.

How to change the length of a column in a SQL Server table via T-SQL

So, let's say you have this table:

CREATE TABLE YourTable(Col1 VARCHAR(10))

And you want to change Col1 to VARCHAR(20). What you need to do is this:

ALTER TABLE YourTable
ALTER COLUMN Col1 VARCHAR(20)

That'll work without problems since the length of the column got bigger. If you wanted to change it to VARCHAR(5), then you'll first gonna need to make sure that there are not values with more chars on your column, otherwise that ALTER TABLE will fail.

How to show row number in Access query like ROW_NUMBER in SQL

You can try this query:

Select A.*, (select count(*) from Table1 where A.ID>=ID) as RowNo
from Table1 as A
order by A.ID

How to use XMLReader in PHP?

Simple example:

public function productsAction()
{
    $saveFileName = 'ceneo.xml';
    $filename = $this->path . $saveFileName;
    if(file_exists($filename)) {

    $reader = new XMLReader();
    $reader->open($filename);

    $countElements = 0;

    while($reader->read()) {
        if($reader->nodeType == XMLReader::ELEMENT) {
            $nodeName = $reader->name;
        }

        if($reader->nodeType == XMLReader::TEXT && !empty($nodeName)) {
            switch ($nodeName) {
                case 'id':
                    var_dump($reader->value);
                    break;
            }
        }

        if($reader->nodeType == XMLReader::END_ELEMENT && $reader->name == 'offer') {
            $countElements++;
        }
    }
    $reader->close();
    exit(print('<pre>') . var_dump($countElements));
    }
}

.htaccess rewrite to redirect root URL to subdirectory

I have found that in order to avoid circular redirection, it is important to limit the scope of redirection to root directory. I would have used:

RewriteEngine on
RewriteCond %{REQUEST_URI} ^/$
RewriteRule (.*) http://www.example.com/store [R=301,L]

Starting a shell in the Docker Alpine container

ole@T:~$ docker run -it --rm alpine /bin/ash
(inside container) / # 

Options used above:

  • /bin/ash is Ash (Almquist Shell) provided by BusyBox
  • --rm Automatically remove the container when it exits (docker run --help)
  • -i Interactive mode (Keep STDIN open even if not attached)
  • -t Allocate a pseudo-TTY

How to create streams from string in Node.Js?

There's a module for that: https://www.npmjs.com/package/string-to-stream

var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there' 

JQuery create a form and add elements to it programmatically

var form = $("<form/>", 
                 { action:'/myaction' }
            );
form.append( 
    $("<input>", 
         { type:'text', 
           placeholder:'Keywords', 
           name:'keyword', 
           style:'width:65%' }
     )
);

form.append( 
     $("<input>", 
          { type:'submit', 
            value:'Search', 
            style:'width:30%' }
       )
);

$("#someDivId").append(form);

Importing variables from another file?

from file1 import *  

will import all objects and methods in file1

How to Serialize a list in java?

As pointed out already, most standard implementations of List are serializable. However you have to ensure that the objects referenced/contained within the list are also serializable.

Create a .txt file if doesn't exist, and if it does append a new line

using(var tw = new StreamWriter(path, File.Exists(path)))
{
    tw.WriteLine(message);
}

Git: How to find a deleted file in the project commit history?

Try using one of the viewers, such as gitk so that you can browse around the history to find that half remembered file. (use gitk --all if needed for all branches)

Java - remove last known item from ArrayList

The compiler complains that you are trying something of a list of ClientThread objects to a String. Either change the type of hey to ClientThread or clients to List<String>.

In addition: Valid indices for lists are from 0 to size()-1.

So you probably want to write

   String hey = clients.get(clients.size()-1);

Dart SDK is not configured

Downloading and Configuring the Dart SDK

If you don’t already have the Dart SDK, install it. You can get it either by itself or by downloading the Flutter SDK, which (as of Flutter 1.21) includes the full Dart SDK.

Choose one:

Here’s one way to configure Dart support:

  1. Start the IDE, and install the Dart plugin. To find the Dart plugin, from the Welcome screen choose Configure > Plugins, then click Install JetBrains plugin, and then search or scroll down until you find Dart. Once you've installed the Dart plugin, restart the IDE.

  2. Create a new Dart project:

    • From the Welcome screen, click Create New Project.
    • In the next dialog, click Dart.
  3. If you don't see a value for the Dart SDK path, enter it.

    • For example, the SDK path might be <dart installation directory>/dart/dart-sdk.

Font awesome is not showing icon

Open your font-awesome.css theres code like :

@font-face {
  font-family: 'FontAwesome';
  src: url('../fonts/fontawesome-webfont.eot?v=4.5.0');
  src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.5.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2?v=4.5.0') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.5.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.5.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.5.0#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

you must have folder like :

font awesome -> css
 -> fonts

or the easiest way :

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

How do I "decompile" Java class files?

JD-GUI is really good. You could just open a JAR file and browse through the code as if you are working on an IDE. Good stuff.

How to remove "index.php" in codeigniter's path

As an .htaccess file, a good option is to use the one provided by the Kohana Framework:

# Turn on URL rewriting
RewriteEngine On

# Installation directory
RewriteBase /

# Protect hidden files from being viewed
<Files .*>
    Order Deny,Allow
    Deny From All
</Files>

# Protect application and system files from being viewed
RewriteRule ^(?:application|system)\b.* index.php/$0 [L]

# Allow any files or directories that exist to be displayed directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# Rewrite all other URLs to index.php/URL
RewriteRule .* index.php/$0 [PT]

It's a well thought out .htaccess that just works.

overlay a smaller image on a larger image python OpenCv

A simple way to achieve what you want:

import cv2
s_img = cv2.imread("smaller_image.png")
l_img = cv2.imread("larger_image.jpg")
x_offset=y_offset=50
l_img[y_offset:y_offset+s_img.shape[0], x_offset:x_offset+s_img.shape[1]] = s_img

the result image

Update

I suppose you want to take care of the alpha channel too. Here is a quick and dirty way of doing so:

s_img = cv2.imread("smaller_image.png", -1)

y1, y2 = y_offset, y_offset + s_img.shape[0]
x1, x2 = x_offset, x_offset + s_img.shape[1]

alpha_s = s_img[:, :, 3] / 255.0
alpha_l = 1.0 - alpha_s

for c in range(0, 3):
    l_img[y1:y2, x1:x2, c] = (alpha_s * s_img[:, :, c] +
                              alpha_l * l_img[y1:y2, x1:x2, c])

result image with alpha

View stored procedure/function definition in MySQL

something like:

DELIMITER //

CREATE PROCEDURE alluser()
BEGIN
   SELECT *
   FROM users;
END //

DELIMITER ;

than:

SHOW CREATE PROCEDURE alluser

gives result:

'alluser', 'STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER', 'CREATE DEFINER=`root`@`localhost` PROCEDURE `alluser`()
BEGIN
   SELECT *
   FROM users;
END'

What are all possible pos tags of NLTK?

Just run this verbatim.

import nltk
nltk.download('tagsets')
nltk.help.upenn_tagset()

nltk.tag._POS_TAGGER won't work. It will give AttributeError: module 'nltk.tag' has no attribute '_POS_TAGGER'. It's not available in NLTK 3 anymore.

Checking for directory and file write permissions in .NET

Directory.GetAccessControl(path) does what you are asking for.

public static bool HasWritePermissionOnDir(string path)
{
    var writeAllow = false;
    var writeDeny = false;
    var accessControlList = Directory.GetAccessControl(path);
    if (accessControlList == null)
        return false;
    var accessRules = accessControlList.GetAccessRules(true, true, 
                                typeof(System.Security.Principal.SecurityIdentifier));
    if (accessRules ==null)
        return false;

    foreach (FileSystemAccessRule rule in accessRules)
    {
        if ((FileSystemRights.Write & rule.FileSystemRights) != FileSystemRights.Write) 
            continue;

        if (rule.AccessControlType == AccessControlType.Allow)
            writeAllow = true;
        else if (rule.AccessControlType == AccessControlType.Deny)
            writeDeny = true;
    }

    return writeAllow && !writeDeny;
}

(FileSystemRights.Write & rights) == FileSystemRights.Write is using something called "Flags" btw which if you don't know what it is you should really read up on :)

How to recompile with -fPIC

After the configure step you probably have a makefile. Inside this makefile look for CFLAGS (or similar). puf -fPIC at the end and run make again. In other words -fPIC is a compiler option that has to be passed to the compiler somewhere.

What's the difference between lists and tuples?

Lists are intended to be homogeneous sequences, while tuples are heterogeneous data structures.

MYSQL query between two timestamps

@Amaynut Thanks

SELECT * 
FROM eventList 
WHERE date BETWEEN UNIX_TIMESTAMP('2017-08-01') AND UNIX_TIMESTAMP('2017/08/01');

above mention, code works and my problem solved.

how to remove time from datetime

For more info refer this: SQL Server Date Formats

[MM/DD/YYYY]

SELECT CONVERT(VARCHAR(10), cast(dt_col as date), 101) from tbl

[DD/MM/YYYY]

SELECT CONVERT(VARCHAR(10), cast(dt_col as date), 103) from tbl

Live Demo

Converting java.sql.Date to java.util.Date

This function will return a converted java date from SQL date object.

public static java.util.Date convertFromSQLDateToJAVADate(
            java.sql.Date sqlDate) {
        java.util.Date javaDate = null;
        if (sqlDate != null) {
            javaDate = new Date(sqlDate.getTime());
        }
        return javaDate;
    }

What is an 'undeclared identifier' error and how do I fix it?

It is like Using the function without declaring it. header file will contain the function printf(). Include the header file in your program this is the solution for that. Some user defined functions may also through error when not declared before using it. If it is used globally no probs.

How to store and retrieve a dictionary with redis

Another way: you can use RedisWorks library.

pip install redisworks

>>> from redisworks import Root
>>> root = Root()
>>> root.something = {1:"a", "b": {2: 2}}  # saves it as Hash type in Redis
...
>>> print(root.something)  # loads it from Redis
{'b': {2: 2}, 1: 'a'}
>>> root.something['b'][2]
2

It converts python types to Redis types and vice-versa.

>>> root.sides = [10, [1, 2]]  # saves it as list in Redis.
>>> print(root.sides)  # loads it from Redis
[10, [1, 2]]
>>> type(root.sides[1])
<class 'list'>

Disclaimer: I wrote the library. Here is the code: https://github.com/seperman/redisworks

Python: How to get values of an array at certain index positions?

You can use index arrays, simply pass your ind_pos as an index argument as below:

a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])

print(a[ind_pos])
# [88,85,16]

Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).

How to display errors for my MySQLi query?

mysqli_error()

As in:

$sql = "Your SQL statement here";
$result = mysqli_query($conn, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($conn), E_USER_ERROR);

Trigger error is better than die because you can use it for development AND production, it's the permanent solution.

WPF C# button style

   <Button x:Name="mybtnSave" FlowDirection="LeftToRight"  HorizontalAlignment="Left" Margin="813,614,0,0" VerticalAlignment="Top"  Width="223" Height="53" BorderBrush="#FF2B3830" HorizontalContentAlignment="Center" VerticalContentAlignment="Center" FontFamily="B Titr" FontSize="15" FontWeight="Bold" BorderThickness="2" TabIndex="107" Click="mybtnSave_Click" >
        <Button.Background>
            <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="Black" Offset="0"/>
                <GradientStop Color="#FF080505" Offset="1"/>
                <GradientStop Color="White" Offset="0.536"/>
            </LinearGradientBrush>
        </Button.Background>
        <Button.Effect>
            <DropShadowEffect/>
        </Button.Effect>
        <StackPanel HorizontalAlignment="Stretch" Cursor="Hand" >
            <StackPanel.Background>
                <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
                    <GradientStop Color="#FF3ED82E" Offset="0"/>
                    <GradientStop Color="#FF3BF728" Offset="1"/>
                    <GradientStop Color="#FF212720" Offset="0.52"/>
                </LinearGradientBrush>
            </StackPanel.Background>
            <Image HorizontalAlignment="Left"  Source="image/Append Or Save 3.png" Height="36" Width="203" />
            <TextBlock HorizontalAlignment="Center" Width="145" Height="22" VerticalAlignment="Top" Margin="0,-31,-35,0" Text="Save Com F12" FontFamily="Tahoma" FontSize="14" Padding="0,4,0,0" Foreground="White" />
        </StackPanel>
    </Button>ente[![enter image description here][1]][1]r image description here

How to iterate over associative arrays in Bash

Welcome to input associative array 2.0!

    clear
    echo "Welcome to input associative array 2.0! (Spaces in keys and values now supported)"
    unset array
    declare -A array
    read -p 'Enter number for array size: ' num
    for (( i=0; i < num; i++ ))
        do
            echo -n "(pair $(( $i+1 )))"
            read -p ' Enter key: ' k
            read -p '         Enter value: ' v
            echo " "
            array[$k]=$v
        done
    echo " "
    echo "The keys are: " ${!array[@]}
    echo "The values are: " ${array[@]}
    echo " "
    echo "Key <-> Value"
    echo "-------------"
    for i in "${!array[@]}"; do echo $i "<->" ${array[$i]}; done
    echo " "
    echo "Thanks for using input associative array 2.0!"

Output:

Welcome to input associative array 2.0! (Spaces in keys and values now supported)
Enter number for array size: 4
(pair 1) Enter key: Key Number 1
         Enter value: Value#1

(pair 2) Enter key: Key Two
         Enter value: Value2

(pair 3) Enter key: Key3
         Enter value: Val3

(pair 4) Enter key: Key4
         Enter value: Value4


The keys are:  Key4 Key3 Key Number 1 Key Two
The values are:  Value4 Val3 Value#1 Value2

Key <-> Value
-------------
Key4 <-> Value4
Key3 <-> Val3
Key Number 1 <-> Value#1
Key Two <-> Value2

Thanks for using input associative array 2.0!

Input associative array 1.0

(keys and values that contain spaces are not supported)

    clear
    echo "Welcome to input associative array! (written by mO extraordinaire!)"
    unset array
    declare -A array
    read -p 'Enter number for array size: ' num
    for (( i=0; i < num; i++ ))
        do
            read -p 'Enter key and value separated by a space: ' k v
            array[$k]=$v
        done
    echo " "
    echo "The keys are: " ${!array[@]}
    echo "The values are: " ${array[@]}
    echo " "
    echo "Key <-> Value"
    echo "-------------"
    for i in ${!array[@]}; do echo $i "<->" ${array[$i]}; done
    echo " "
    echo "Thanks for using input associative array!"

Output:

Welcome to input associative array! (written by mO extraordinaire!)
Enter number for array size: 10
Enter key and value separated by a space: a1 10
Enter key and value separated by a space: b2 20
Enter key and value separated by a space: c3 30
Enter key and value separated by a space: d4 40
Enter key and value separated by a space: e5 50
Enter key and value separated by a space: f6 60
Enter key and value separated by a space: g7 70
Enter key and value separated by a space: h8 80
Enter key and value separated by a space: i9 90
Enter key and value separated by a space: j10 100

The keys are:  h8 a1 j10 g7 f6 e5 d4 c3 i9 b2
The values are:  80 10 100 70 60 50 40 30 90 20

Key <-> Value
-------------
h8 <-> 80
a1 <-> 10
j10 <-> 100
g7 <-> 70
f6 <-> 60
e5 <-> 50
d4 <-> 40
c3 <-> 30
i9 <-> 90
b2 <-> 20

Thanks for using input associative array!

"Faceted Project Problem (Java Version Mismatch)" error message

You have two options to fix the issue:

1- Manually make sure the two versions match.
2- Use the IDE's help as follows:
- Right mouse click on the error in the 'Problems' view
- Select the 'Quick Fix' menu item from the pop-up menu
- Select the right compiler level in the provided dialog and click 'Finish'.

Taken from Eclipse: Java compiler level and project facet mismatch

Also gives location of where you can access the Java compiler and facet version.

How can I change my Cygwin home folder after installation?

I did something quite simple. I did not want to change the windows 7 environment variable. So I directly edited the Cygwin.bat file.

@echo off
SETLOCAL
set HOME=C:\path\to\home
C:
chdir C:\apps\cygwin\bin
bash --login -i
ENDLOCAL

This just starts the local shell with this home directory; that is what I wanted. I am not going to remotely access this, so this worked for me.

How do you specify a byte literal in Java?

If you're passing literals in code, what's stopping you from simply declaring it ahead of time?

byte b = 0; //Set to desired value.
f(b);

How to write LaTeX in IPython Notebook?

Yet another solution for when you want to have control over the document preamble. Write a whole document, send it to system latex, convert the pdf to png, use IPython.display to load and display.

import tempfile
import os.path
import subprocess
from IPython.display import Image, display

with tempfile.TemporaryDirectory(prefix="texinpy_") as tmpdir:
    path = os.path.join(tmpdir, "document.tex")
    with open(path, 'w') as fp:
        fp.write(r"""
        \documentclass[12pt]{standalone}
        \begin{document}
        \LaTeX{}
        \end{document}
        """)
    subprocess.run(["lualatex", path], cwd=tmpdir)
    subprocess.run(["pdftocairo", "-singlefile", "-transp", "-r", "100", "-png", "document.pdf", "document"], cwd=tmpdir)
    im = Image(filename=os.path.join(tmpdir, "document.png"))
    display(im)

enter image description here

AngularJS routing without the hash '#'

If you enabled html5mode as others have said, and create an .htaccess file with the following contents (adjust for your needs):

RewriteEngine   On
RewriteBase     /
RewriteCond     %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_FILENAME} !-d
RewriteRule     ./index.html [L]

Users will be directed to the your app when they enter a proper route, and your app will read the route and bring them to the correct "page" within it.

EDIT: Just make sure not to have any file or directory names conflict with your routes.

How to change font size in html?

You can't do it in HTML. You can in CSS. Create a new CSS file and write:

p {
 font-size: (some number);
}

If that doesn't work make sure you don't have any "pre" tags, which make your code a bit smaller.

How to set an image as a background for Frame in Swing GUI of java?

This is easily done by replacing the frame's content pane with a JPanel which draws your image:

try {
    final Image backgroundImage = javax.imageio.ImageIO.read(new File(...));
    setContentPane(new JPanel(new BorderLayout()) {
        @Override public void paintComponent(Graphics g) {
            g.drawImage(backgroundImage, 0, 0, null);
        }
    });
} catch (IOException e) {
    throw new RuntimeException(e);
}

This example also sets the panel's layout to BorderLayout to match the default content pane layout.

(If you have any trouble seeing the image, you might need to call setOpaque(false) on some other components so that you can see through to the background.)

Disable JavaScript error in WebBrowser control

This disables the script errors and also disables other windows.. such as the NTLM login window or the client certificate accept window. The below will suppress only javascript errors.

// Hides script errors without hiding other dialog boxes.
private void SuppressScriptErrorsOnly(WebBrowser browser)
{
    // Ensure that ScriptErrorsSuppressed is set to false.
    browser.ScriptErrorsSuppressed = false;

    // Handle DocumentCompleted to gain access to the Document object.
    browser.DocumentCompleted +=
        new WebBrowserDocumentCompletedEventHandler(
            browser_DocumentCompleted);
}

private void browser_DocumentCompleted(object sender, 
    WebBrowserDocumentCompletedEventArgs e)
{
    ((WebBrowser)sender).Document.Window.Error += 
        new HtmlElementErrorEventHandler(Window_Error);
}

private void Window_Error(object sender, 
    HtmlElementErrorEventArgs e)
{
    // Ignore the error and suppress the error dialog box. 
    e.Handled = true;
}

What's the difference between abstraction and encapsulation?

Its Simple!

Take example of television - it is Encapsulation, because:

  1. Television is loaded with different functionalies that i don't know because they are completely hidden.

  2. Hidden things like music, video etc everything bundled in a capsule that what we call a TV

Now, Abstraction is When we know a little about something and which can help us to manipulate something for which we don't know how it works internally.

For eg: A remote-control for TV is abstraction, because

  1. With remote we know that pressing the number keys will change the channels. We are not aware as to what actually happens internally. We can manipulate the hidden thing but we don't know how it is being done internally.

Programmatically, when we can acess the hidden data somehow and know something.. is Abstraction .. And when we know nothing about the internals its Encapsulation.

Without remote we can't change anything on TV we have to see what it shows coz all controls are hidden.

Replace multiple strings at once

You could use the replace method of the String object with a function in the second parameter:

First Method (using a find and replace Object)

var findreplace = {"<" : "&lt;", ">" : "&gt;", "\n" : "<br/>"};

textarea = textarea.replace(new RegExp("(" + Object.keys(findreplace).map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return findreplace[s]});

jsfiddle

Second method (using two arrays, find and replace)

var find = ["<", ">", "\n"];
var replace = ["&lt;", "&gt;", "<br/>"];

textarea = textarea.replace(new RegExp("(" + find.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return replace[find.indexOf(s)]});

jsfiddle

Desired function:

function str_replace($f, $r, $s){
   return $s.replace(new RegExp("(" + $f.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|") + ")", "g"), function(s){ return $r[$f.indexOf(s)]});
}

$textarea = str_replace($find, $replace, $textarea);

EDIT

This function admits a String or an Array as parameters:

function str_replace($f, $r, $s){
    return $s.replace(new RegExp("(" + (typeof($f) === "string" ? $f.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&") : $f.map(function(i){return i.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&")}).join("|")) + ")", "g"), typeof($r) === "string" ? $r : typeof($f) === "string" ? $r[0] : function(i){ return $r[$f.indexOf(i)]});
}

How to sanity check a date in Java

Assuming that both of those are Strings (otherwise they'd already be valid Dates), here's one way:

package cruft;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateValidator
{
    private static final DateFormat DEFAULT_FORMATTER;

    static
    {
        DEFAULT_FORMATTER = new SimpleDateFormat("dd-MM-yyyy");
        DEFAULT_FORMATTER.setLenient(false);
    }

    public static void main(String[] args)
    {
        for (String dateString : args)
        {
            try
            {
                System.out.println("arg: " + dateString + " date: " + convertDateString(dateString));
            }
            catch (ParseException e)
            {
                System.out.println("could not parse " + dateString);
            }
        }
    }

    public static Date convertDateString(String dateString) throws ParseException
    {
        return DEFAULT_FORMATTER.parse(dateString);
    }
}

Here's the output I get:

java cruft.DateValidator 32-11-2010 31-02-2010 04-01-2011
could not parse 32-11-2010
could not parse 31-02-2010
arg: 04-01-2011 date: Tue Jan 04 00:00:00 EST 2011

Process finished with exit code 0

As you can see, it does handle both of your cases nicely.

Heroku: How to push different local Git branches to Heroku/master

I think it should be

push = refs/heads/*:refs/heads/*

instead...

Is it possible to do a sparse checkout without checking out the whole repository first?

Git clone has an option (--no-checkout or -n) that does what you want.

In your list of commands, just change:

git clone <path>

To this:

git clone --no-checkout <path>

You can then use the sparse checkout as stated in the question.

Removing u in list

[u'{email:[email protected],gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test,gem:0}', u'{email:test1,gem:0}']

'u' denotes unicode characters. We can easily remove this with map function on the final list element

map(str, test)

Another way is when you are appending it to the list

test.append(str(a))

How to do a batch insert in MySQL

Most of the time, you are not working in a MySQL client and you should batch inserts together using the appropriate API.

E.g. in JDBC:

connection con.setAutoCommit(false); 
PreparedStatement prepStmt = con.prepareStatement("UPDATE DEPT SET MGRNO=? WHERE DEPTNO=?");
prepStmt.setString(1,mgrnum1);                 
prepStmt.setString(2,deptnum1);
prepStmt.addBatch();

prepStmt.setString(1,mgrnum2);                        
prepStmt.setString(2,deptnum2);
prepStmt.addBatch();

int [] numUpdates=prepStmt.executeBatch();

http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/ad/tjvbtupd.htm

BOOLEAN or TINYINT confusion

The Newest MySQL Versions have the new BIT data type in which you can specify the number of bits in the field, for example BIT(1) to use as Boolean type, because it can be only 0 or 1.

Failed to build gem native extension (installing Compass)

Try this, then try to install compass again

apt-get install ruby-dev

Escape double quote in VB string

Escaping quotes in VB6 or VBScript strings is simple in theory although often frightening when viewed. You escape a double quote with another double quote.

An example:

"c:\program files\my app\app.exe"

If I want to escape the double quotes so I could pass this to the shell execute function listed by Joe or the VB6 Shell function I would write it:

escapedString = """c:\program files\my app\app.exe"""

How does this work? The first and last quotes wrap the string and let VB know this is a string. Then each quote that is displayed literally in the string has another double quote added in front of it to escape it.

It gets crazier when you are trying to pass a string with multiple quoted sections. Remember, every quote you want to pass has to be escaped.

If I want to pass these two quoted phrases as a single string separated by a space (which is not uncommon):

"c:\program files\my app\app.exe" "c:\documents and settings\steve"

I would enter this:

escapedQuoteHell = """c:\program files\my app\app.exe"" ""c:\documents and settings\steve"""

I've helped my sysadmins with some VBScripts that have had even more quotes.

It's not pretty, but that's how it works.

Jenkins fails when running "service start jenkins"

Similar problem on Ubuntu 16.04.

Setting up jenkins (2.72) ...
Job for jenkins.service failed because the control process exited with error code. See "systemctl status jenkins.service" and "journalctl -xe" for details.
invoke-rc.d: initscript jenkins, action "start" failed.
? jenkins.service - LSB: Start Jenkins at boot time
Loaded: loaded (/etc/init.d/jenkins; bad; vendor preset: enabled)
Active: failed (Result: exit-code) since Tue 2017-08-01 05:39:06 UTC; 7ms ago
Docs: man:systemd-sysv-generator(8)
Process: 3700 ExecStart=/etc/init.d/jenkins start (code=exited, status=1/FAILURE)

Aug 01 05:39:06 ip-0 systemd[1]: Starting LSB: Start Jenkins ....
Aug 01 05:39:06 ip-0 jenkins[3700]: ERROR: No Java executable ...
Aug 01 05:39:06 ip-0 jenkins[3700]: If you actually have java ...
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Control pro...1
Aug 01 05:39:06 ip-0 systemd[1]: Failed to start LSB: Start J....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Unit entere....
Aug 01 05:39:06 ip-0 systemd[1]: jenkins.service: Failed with....

To fix the issue manually install Java Runtime Environment:

JDK version 9:

sudo apt install openjdk-9-jre

JDK version 8:

sudo apt install openjdk-8-jre

Open Jenkins configuration file:

sudo vi /etc/init.d/jenkins

Finally, append path to the new java executable (line 16):

PATH=/bin:/usr/bin:/sbin:/usr/sbin:/usr/lib/jvm/java-8-openjdk-amd64/bin/

CROSS JOIN vs INNER JOIN in SQL

Cross join does not combine the rows, if you have 100 rows in each table with 1 to 1 match, you get 10.000 results, Innerjoin will only return 100 rows in the same situation.

These 2 examples will return the same result:

Cross join

select * from table1 cross join table2 where table1.id = table2.fk_id

Inner join

select * from table1 join table2 on table1.id = table2.fk_id

Use the last method

Is there a way to detach matplotlib plots so that the computation can continue?

If you want to open multiple figures, while keeping them all opened, this code worked for me:

show(block=False)
draw()

Add JsonArray to JsonObject

Just try below a simple solution:

JsonObject body=new JsonObject();
body.add("orders", (JsonElement) orders);

whenever my JSON request is like:

{
      "role": "RT",
      "orders": [
        {
          "order_id": "ORDER201908aPq9Gs",
          "cart_id": 164444,
          "affiliate_id": 0,
          "orm_order_status": 9,
          "status_comments": "IC DUE - Auto moved to Instruction Call Due after 48hrs",
          "status_date": "2020-04-15",
        }
      ]
    }

$ is not a function - jQuery error

When jQuery is not present you get $ is undefined and not your message.

Did you check if you don't have a variable called $ somewhere before your code?
Inspect the value of $ in firebug to see what it is.

Slightly out of the question, but I can't resist to write a shorter code to your class assignment:

    var i = 1;
    $("ol li").each(function(){
        $(this).addClass('olli' + i++);
    });

Location of my.cnf file on macOS

In mysql 5.6.22, which I installed it from Homebrew, the path of my.cnf is

/usr/local/opt/mysql/my.cnf 

Multiple contexts with the same path error running web service in Eclipse using Tomcat

  1. In your project's Properties, choose "Web Project Settings".
  2. Change "Context root".
  3. Clean your server
  4. now you can restart your server

Expand and collapse with angular js

See http://angular-ui.github.io/bootstrap/#/collapse

function CollapseDemoCtrl($scope) {
  $scope.isCollapsed = false;
}



<div ng-controller="CollapseDemoCtrl">
    <button class="btn" ng-click="isCollapsed = !isCollapsed">Toggle collapse</button>
    <hr>
    <div collapse="isCollapsed">
        <div class="well well-large">Some content</div> 
    </div>
</div>

how to create a login page when username and password is equal in html

Doing password checks on client side is unsafe especially when the password is hard coded.

The safest way is password checking on server side, but even then the password should not be transmitted plain text.

Checking the password client side is possible in a "secure way":

  • The password needs to be hashed
  • The hashed password is used as part of a new url

Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).

How to do paging in AngularJS?

This is a pure javascript solution that I've wrapped as an Angular service to implement pagination logic like in google search results.

Working demo on CodePen at http://codepen.io/cornflourblue/pen/KVeaQL/

Details and explanation at this blog post

function PagerService() {
    // service definition
    var service = {};

    service.GetPager = GetPager;

    return service;

    // service implementation
    function GetPager(totalItems, currentPage, pageSize) {
        // default to first page
        currentPage = currentPage || 1;

        // default page size is 10
        pageSize = pageSize || 10;

        // calculate total pages
        var totalPages = Math.ceil(totalItems / pageSize);

        var startPage, endPage;
        if (totalPages <= 10) {
            // less than 10 total pages so show all
            startPage = 1;
            endPage = totalPages;
        } else {
            // more than 10 total pages so calculate start and end pages
            if (currentPage <= 6) {
                startPage = 1;
                endPage = 10;
            } else if (currentPage + 4 >= totalPages) {
                startPage = totalPages - 9;
                endPage = totalPages;
            } else {
                startPage = currentPage - 5;
                endPage = currentPage + 4;
            }
        }

        // calculate start and end item indexes
        var startIndex = (currentPage - 1) * pageSize;
        var endIndex = startIndex + pageSize;

        // create an array of pages to ng-repeat in the pager control
        var pages = _.range(startPage, endPage + 1);

        // return object with all pager properties required by the view
        return {
            totalItems: totalItems,
            currentPage: currentPage,
            pageSize: pageSize,
            totalPages: totalPages,
            startPage: startPage,
            endPage: endPage,
            startIndex: startIndex,
            endIndex: endIndex,
            pages: pages
        };
    }
}

JavaScript seconds to time string with format hh:mm:ss

Here is yet another version, which handles days also:

function FormatSecondsAsDurationString( seconds )
{
    var s = "";

    var days = Math.floor( ( seconds / 3600 ) / 24 );
    if ( days >= 1 )
    {
        s += days.toString() + " day" + ( ( days == 1 ) ? "" : "s" ) + " + ";
        seconds -= days * 24 * 3600;
    }

    var hours = Math.floor( seconds / 3600 );
    s += GetPaddedIntString( hours.toString(), 2 ) + ":";
    seconds -= hours * 3600;

    var minutes = Math.floor( seconds / 60 );
    s += GetPaddedIntString( minutes.toString(), 2 ) + ":";
    seconds -= minutes * 60;

    s += GetPaddedIntString( Math.floor( seconds ).toString(), 2 );

    return s;
}

function GetPaddedIntString( n, numDigits )
{
    var nPadded = n;
    for ( ; nPadded.length < numDigits ; )
    {
        nPadded = "0" + nPadded;
    }

    return nPadded;
}

How to tell which disk Windows Used to Boot

You type diskpart, list disk and check disks for boot.
Ex:

dispart 
list disk 
select disk 0 
detail disk

The disk with Boot volume is disk with windows installed:

enter image description here

Python - Move and overwrite files and folders

Since none of the above worked for me, so I wrote my own recursive function. Call Function copyTree(dir1, dir2) to merge directories. Run on multi-platforms Linux and Windows.

def forceMergeFlatDir(srcDir, dstDir):
    if not os.path.exists(dstDir):
        os.makedirs(dstDir)
    for item in os.listdir(srcDir):
        srcFile = os.path.join(srcDir, item)
        dstFile = os.path.join(dstDir, item)
        forceCopyFile(srcFile, dstFile)

def forceCopyFile (sfile, dfile):
    if os.path.isfile(sfile):
        shutil.copy2(sfile, dfile)

def isAFlatDir(sDir):
    for item in os.listdir(sDir):
        sItem = os.path.join(sDir, item)
        if os.path.isdir(sItem):
            return False
    return True


def copyTree(src, dst):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.isfile(s):
            if not os.path.exists(dst):
                os.makedirs(dst)
            forceCopyFile(s,d)
        if os.path.isdir(s):
            isRecursive = not isAFlatDir(s)
            if isRecursive:
                copyTree(s, d)
            else:
                forceMergeFlatDir(s, d)

Use Robocopy to copy only changed files?

To answer all your questions:

Can I use ROBOCOPY for this?

Yes, RC should fit your requirements (simplicity, only copy what needed)


What exactly does it mean to exclude?

It will exclude copying - RC calls it skipping


Would the /XO option copy only newer files, not files of the same age?

Yes, RC will only copy newer files. Files of the same age will be skipped.

(the correct command would be robocopy C:\SourceFolder D:\DestinationFolder ABC.dll /XO)


Maybe in your case using the /MIR option could be useful. In general RC is rather targeted at directories and directory trees than single files.

How to use paths in tsconfig.json?

Check this similar solutions with asterisk

  "baseUrl": ".",
  "paths": {
    "*": [
      "node_modules/*",
      "src/types/*"
    ]
  },

How to select data from 30 days?

Short version for easy use:

SELECT * 
FROM [TableName] t
WHERE t.[DateColumnName] >= DATEADD(month, -1, GETDATE())

DATEADD and GETDATE are available in SQL Server starting with 2008 version. MSDN documentation: GETDATE and DATEADD.

LINQ: combining join and group by

We did it like this:

from p in Products                         
join bp in BaseProducts on p.BaseProductId equals bp.Id                    
where !string.IsNullOrEmpty(p.SomeId) && p.LastPublished >= lastDate                         
group new { p, bp } by new { p.SomeId } into pg    
let firstproductgroup = pg.FirstOrDefault()
let product = firstproductgroup.p
let baseproduct = firstproductgroup.bp
let minprice = pg.Min(m => m.p.Price)
let maxprice = pg.Max(m => m.p.Price)
select new ProductPriceMinMax
{
SomeId = product.SomeId,
BaseProductName = baseproduct.Name,
CountryCode = product.CountryCode,
MinPrice = minprice, 
MaxPrice = maxprice
};

EDIT: we used the version of AakashM, because it has better performance

Angular2 : Can't bind to 'formGroup' since it isn't a known property of 'form'

Try to add ReactiveFormsModule in your component as well.

import { FormGroup, FormArray, FormBuilder,
          Validators,ReactiveFormsModule  } from '@angular/forms';

How to make a JTable non-editable

create new DefaultCellEditor class :

public static class Editor_name extends DefaultCellEditor {
  public Editor_name(JCheckBox checkBox) {
   super(checkBox);
  }
  @Override
  public boolean isCellEditable(EventObject anEvent) {
    return false;
  }
}

and use setCellEditor :

JTable table = new JTable();
table.getColumn("columnName").setCellEditor(new Editor_name(new JCheckBox()));

C# Lambda expressions: Why should I use them?

A lambda expression is like an anonymous method written in place of a delegate instance.

delegate int MyDelagate (int i);
MyDelagate delSquareFunction = x => x * x;

Consider the lambda expression x => x * x;

The input parameter value is x (on the left side of =>)

The function logic is x * x (on the right side of =>)

A lambda expression's code can be a statement block instead of an expression.

x => {return x * x;};

Example

Note: Func is a predefined generic delegate.

    Console.WriteLine(MyMethod(x => "Hi " + x));

    public static string MyMethod(Func<string, string> strategy)
    {
        return strategy("Lijo").ToString();
    }

References

  1. How can a delegate & interface be used interchangeably?

LOAD DATA INFILE Error Code : 13

I too have struggled with this problem over the past few days and I too turned to stack overflow for answers.

However, no one seems to mention the simplest way to import data into MySQL is actually through their very own import data wizard tool!!

Just right-click on the table and it comes up there.

just right click on the table and it comes up there

None of the above answers helped me, so just use this if you're stuck! :)

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

Move it to the Trusted Sites zone by either adding it to a Trusted Sites list or local setting. This will move it out of Intranet Zone and will not be rendered in Compat. View.

how to console.log result of this ajax call?

Ajax call error handler will be triggered if the call itself fails.

You are probably trying to get the error from server in case login credentials do not go through. In that case, you need to inspect the server response json object and display appropriate message.

e.preventDefault();
$.ajax(
{
    type: 'POST',
    url: requestURI,
    data: $(formLogin).serialize(),
    dataType: 'json',
    success: function(result){
        if(result.hasError == true)
        {
            if(result.error_code == 'AUTH_FAILURE')
            {
                //wrong password
                console.log('Recieved authentication error');
                $('#login_errors_auth').fadeIn();
            }
            else
            {
                //generic error here
                $('#login_errors_unknown').fadeIn();
            }
        }
    }
});

Here, "result" is the json object returned form the server which could have a structure like:

$return = array(
        'hasError' => !$validPassword,
        'error_code' => 'AUTH_FAILURE'
);
die(jsonEncode($return));

How to get address location from latitude and longitude in Google Map.?

You have to make one ajax call to get the required result, in this case you can use Google API to get the same

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false

Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level

How to find the process id of a running Java process on Windows? And how to kill the process alone?

The solution I found is very simple. Use Window's WMIC & Java's Runtime to locate & kill the process.

Part 1: You need to put some sort of identifier into your app's startup command line. E.g. something like:

String id = "com.domain.app";

Part 2: When you run your app, make sure to include the string. Let's say you start it from within Java, do the following:

Runtime.getRuntime().exec(
   "C:\...\javaw.exe -cp ... -Dwhatever=" + id + " com.domain.app.Main"
);

Part 3: To kill the process, use Window's WMIC. Just make sure you app was started containing your id from above:

Runtime.getRuntime().exec(
  "wmic process Where \"CommandLine Like '%" + id + "%'\" Call Terminate"
);

JQuery confirm dialog

You can use jQuery UI and do something like this

Html:

<button id="callConfirm">Confirm!</button>

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>?

Javascript:

$("#dialog").dialog({
   autoOpen: false,
   modal: true,
   buttons : {
        "Confirm" : function() {
            alert("You have confirmed!");            
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

$("#callConfirm").on("click", function(e) {
    e.preventDefault();
    $("#dialog").dialog("open");
});

?

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

Responsively change div size keeping aspect ratio

<style>
#aspectRatio
{
  position:fixed;
  left:0px;
  top:0px;
  width:60vw;
  height:40vw;
  border:1px solid;
  font-size:10vw;
}
</style>
<body>
<div id="aspectRatio">Aspect Ratio?</div>
</body>

The key thing to note here is vw = viewport width, and vh = viewport height

How can I get the executing assembly version?

Two options... regardless of application type you can always invoke:

Assembly.GetExecutingAssembly().GetName().Version

If a Windows Forms application, you can always access via application if looking specifically for product version.

Application.ProductVersion

Using GetExecutingAssembly for an assembly reference is not always an option. As such, I personally find it useful to create a static helper class in projects where I may need to reference the underlying assembly or assembly version:

// A sample assembly reference class that would exist in the `Core` project.
public static class CoreAssembly
{
    public static readonly Assembly Reference = typeof(CoreAssembly).Assembly;
    public static readonly Version Version = Reference.GetName().Version;
}

Then I can cleanly reference CoreAssembly.Version in my code as required.

How to add a “readonly” attribute to an <input>?

Use $.prop()

$("#descrip").prop("readonly",true);

$("#descrip").prop("readonly",false);

Insert multiple rows into single column

If your DBMS supports the notation, you need a separate set of parentheses for each row:

INSERT INTO Data(Col1) VALUES ('Hello'), ('World');

The cross-referenced question shows examples for inserting into two columns.

Alternatively, every SQL DBMS supports the notation using separate statements, one for each row to be inserted:

INSERT INTO Data (Col1) VALUES ('Hello');
INSERT INTO Data (Col1) VALUES ('World');

regex string replace

Just change + to -:

str = str.replace(/[^a-z0-9-]/g, "");

You can read it as:

  1. [^ ]: match NOT from the set
  2. [^a-z0-9-]: match if not a-z, 0-9 or -
  3. / /g: do global match

More information:

How to scroll to top of a div using jQuery?

This is my solution to scroll to the top on a button click.

$(".btn").click(function () {
if ($(this).text() == "Show options") {
$(".tabs").animate(
  {
    scrollTop: $(window).scrollTop(0)
  },
  "slow"
 );
 }
});

How to use executeReader() method to retrieve the value of just one cell

It is not recommended to use DataReader and Command.ExecuteReader to get just one value from the database. Instead, you should use Command.ExecuteScalar as following:

String sql = "SELECT ColumnNumber FROM learer WHERE learer.id = " + index;
SqlCommand cmd = new SqlCommand(sql,conn);
learerLabel.Text = (String) cmd.ExecuteScalar();

Here is more information about Connecting to database and managing data.

How to get the real path of Java application at runtime?

It isn't clear what you're asking for. I don't know what 'with respect to the web application we are using' means if getServletContext().getRealPath() isn't the answer, but:

  • The current user's current working directory is given by System.getProperty("user.dir")
  • The current user's home directory is given by System.getProperty("user.home")
  • The location of the JAR file from which the current class was loaded is given by this.getClass().getProtectionDomain().getCodeSource().getLocation().

Converting array to list in Java

If this helps: I've had the same problem and simply wrote a generic function that takes an array and returns an ArrayList of the same type with the same contents:

public static <T> ArrayList<T> ArrayToArrayList(T[] array) {
    ArrayList<T> list = new ArrayList<T>();
    for(T elmt : array) list.add(elmt);
    return list;
}

Center Triangle at Bottom of Div

You can use following css to make an element middle aligned styled with position: absolute:

.element {
  transform: translateX(-50%);
  position: absolute;
  left: 50%;
}

With CSS having only left: 50% we will have following effect:

Image with left: 50% property only

While combining left: 50% with transform: translate(-50%) we will have following:

Image with transform: translate(-50%) as well

_x000D_
_x000D_
.hero {  _x000D_
  background-color: #e15915;_x000D_
  position: relative;_x000D_
  height: 320px;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
_x000D_
.hero:after {_x000D_
  border-right: solid 50px transparent;_x000D_
  border-left: solid 50px transparent;_x000D_
  border-top: solid 50px #e15915;_x000D_
  transform: translateX(-50%);_x000D_
  position: absolute;_x000D_
  z-index: -1;_x000D_
  content: '';_x000D_
  top: 100%;_x000D_
  left: 50%;_x000D_
  height: 0;_x000D_
  width: 0;_x000D_
}
_x000D_
<div class="hero">_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

jquery - return value using ajax result on success

Although all the approaches regarding the use of async: false are not good because of its deprecation and stuck the page untill the request comes back. Thus here are 2 ways to do it:

1st: Return whole ajax response in a function and then make use of done function to capture the response when the request is completed.(RECOMMENDED, THE BEST WAY)

function getAjax(url, data){
    return $.ajax({
        type: 'POST',
        url : url,              
        data: data,
        dataType: 'JSON',
        //async: true,  //NOT NEEDED
        success: function(response) {
            //Data = response;
        }
    });
 }

CALL THE ABOVE LIKE SO:

getAjax(youUrl, yourData).done(function(response){
    console.log(response);
});

FOR MULTIPLE AJAX CALLS MAKE USE OF $.when :

$.when( getAjax(youUrl, yourData), getAjax2(yourUrl2, yourData2) ).done(function(response){
    console.log(response);
});

2nd: Store the response in a cookie and then outside of the ajax call get that cookie value.(NOT RECOMMENDED)

        $.ajax({
            type: 'POST',
            url : url,              
            data: data,
            //async: false,    // No need to use this
            success: function(response) {
                Cookies.set(name, response);
            }
        });

        // Outside of the ajax call
        var response = Cookies.get(name);

NOTE: In the exmple above jquery cookies library is used.It is quite lightweight and works as snappy. Here is the link https://github.com/js-cookie/js-cookie

How to join a slice of strings into a single string?

The title of your question is:

How to join a slice of strings into a single string?

but in fact, reg is not a slice, but a length-three array. [...]string is just syntactic sugar for (in this case) [3]string.

To get an actual slice, you should write:

reg := []string {"a","b","c"}

(Try it out: https://play.golang.org/p/vqU5VtDilJ.)

Incidentally, if you ever really do need to join an array of strings into a single string, you can get a slice from the array by adding [:], like so:

fmt.Println(strings.Join(reg[:], ","))

(Try it out: https://play.golang.org/p/zy8KyC8OTuJ.)

How to return a table from a Stored Procedure?

In SQL Server 2008 you can use

http://www.sommarskog.se/share_data.html#tableparam

or else simple and same as common execution

CREATE PROCEDURE OrderSummary @MaxQuantity INT OUTPUT AS

SELECT Ord.EmployeeID, SummSales = SUM(OrDet.UnitPrice * OrDet.Quantity)
FROM Orders AS Ord
     JOIN [Order Details] AS OrDet ON (Ord.OrderID = OrDet.OrderID)
GROUP BY Ord.EmployeeID
ORDER BY Ord.EmployeeID

SELECT @MaxQuantity = MAX(Quantity) FROM [Order Details]

RETURN (SELECT SUM(Quantity) FROM [Order Details])
GO

I hopes its help to you

How to install MinGW-w64 and MSYS2?

MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw and cygwin fork package.

To install the MinGW-w64 toolchain (Reference):

  1. Open MSYS2 shell from start menu
  2. Run pacman -Sy pacman to update the package database
  3. Re-open the shell, run pacman -Syu to update the package database and core system packages
  4. Re-open the shell, run pacman -Su to update the rest
  5. Install compiler:
    • For 32-bit target, run pacman -S mingw-w64-i686-toolchain
    • For 64-bit target, run pacman -S mingw-w64-x86_64-toolchain
  6. Select which package to install, default is all
  7. You may also need make, run pacman -S make

subtract two times in python

Use:

from datetime import datetime, date

duration = datetime.combine(date.min, end) - datetime.combine(date.min, beginning)

Using date.min is a bit more concise and works even at midnight.

This might not be the case with date.today() that might return unexpected results if the first call happens at 23:59:59 and the next one at 00:00:00.

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

Just add remove_button_css as class to your button tag. You can verify the code for Link 1

.remove_button_css { 
  outline: none;
  padding: 5px; 
  border: 0px; 
  box-sizing: none; 
  background-color: transparent; 
}

enter image description here

Extra Styles Edit

Add color: #337ab7; and :hover and :focus to match OOTB (bootstrap3)

.remove_button_css:focus,
.remove_button_css:hover {
    color: #23527c;
    text-decoration: underline;
}

Replace all particular values in a data frame

If you want to replace multiple values in a data frame, looping through all columns might help.

Say you want to replace "" and 100:

na_codes <- c(100, "")
for (i in seq_along(df)) {
    df[[i]][df[[i]] %in% na_codes] <- NA
}

Python sys.argv lists and indexes

So if I wanted to return a first name and last name like: Hello Fred Gerbig I would use the code below, this code works but is it actually the most correct way to do it?

import sys
def main():
  if len(sys.argv) >= 2:
    fname = sys.argv[1]
    lname = sys.argv[2]
  else:
    name = 'World'
  print 'Hello', fname, lname
if __name__ == '__main__':
  main()

Edit: Found that the above code works with 2 arguments but crashes with 1. Tried to set len to 3 but that did nothing, still crashes (re-read the other answers and now understand why the 3 did nothing). How do I bypass the arguments if only one is entered? Or how would error checking look that returned "You must enter 2 arguments"?

Edit 2: Got it figured out:

import sys
def main():
  if len(sys.argv) >= 2:
    name = sys.argv[1] + " " + sys.argv[2]
  else:
    name = 'World'
  print 'Hello', name
if __name__ == '__main__':
  main()

Laravel - Model Class not found

In your router.php file, you should use the model class like this

 use App\Post;

and use the model class like this.

Route::get('/posts', function() {

        $results = Post::all();
        return $results; });

whitespaces in the path of windows filepath

There is no problem with whitespaces in the path since you're not using the "shell" to open the file. Here is a session from the windows console to prove the point. You're doing something else wrong

Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on wi
32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> os.makedirs("C:/ABC/SEM 2/testfiles")
>>> open("C:/ABC/SEM 2/testfiles/all.txt","w")
<open file 'C:/ABC/SEM 2/testfiles/all.txt', mode 'w' at 0x0000000001D95420>
>>> exit()

C:\Users\Gnibbler>dir "C:\ABC\SEM 2\testfiles"
 Volume in drive C has no label.
 Volume Serial Number is 46A0-BB64

 Directory of c:\ABC\SEM 2\testfiles

13/02/2013  10:20 PM    <DIR>          .
13/02/2013  10:20 PM    <DIR>          ..
13/02/2013  10:20 PM                 0 all.txt
               1 File(s)              0 bytes
               2 Dir(s)  78,929,309,696 bytes free

C:\Users\Gnibbler>

Force overwrite of local file with what's in origin repo?

Simplest version, assuming you're working on the same branch that the file you want is on:

git checkout path/to/file.

I do this so often that I've got an alias set to gc='git checkout'.

jQuery UI Sortable Position

Use update instead of stop

http://api.jqueryui.com/sortable/

update( event, ui )

Type: sortupdate

This event is triggered when the user stopped sorting and the DOM position has changed.

.

stop( event, ui )

Type: sortstop

This event is triggered when sorting has stopped. event Type: Event

Piece of code:

http://jsfiddle.net/7a1836ce/

<script type="text/javascript">

var sortable    = new Object();
sortable.s1     = new Array(1, 2, 3, 4, 5);
sortable.s2     = new Array(1, 2, 3, 4, 5);
sortable.s3     = new Array(1, 2, 3, 4, 5);
sortable.s4     = new Array(1, 2, 3, 4, 5);
sortable.s5     = new Array(1, 2, 3, 4, 5);

sortingExample();

function sortingExample()
{
    // Init vars

    var tDiv    = $('<div></div>');
    var tSel    = '';

    // ul
    for (var tName in sortable)
    {

        // Creating ul list
        tDiv.append(createUl(sortable[tName], tName));
        // Add selector id
        tSel += '#' + tName + ',';

    }

    $('body').append('<div id="divArrayInfo"></div>');
    $('body').append(tDiv);

    // ul sortable params

    $(tSel).sortable({connectWith:tSel,
       start: function(event, ui) 
       {
            ui.item.startPos = ui.item.index();
       },
        update: function(event, ui)
        {
            var a   = ui.item.startPos;
            var b   = ui.item.index();
            var id = this.id;

            // If element moved to another Ul then 'update' will be called twice
            // 1st from sender list
            // 2nd from receiver list
            // Skip call from sender. Just check is element removed or not

            if($('#' + id + ' li').length < sortable[id].length)
            {
                return;
            }

            if(ui.sender === null)
            {
                sortArray(a, b, this.id, this.id);
            }
            else
            {
                sortArray(a, b, $(ui.sender).attr('id'), this.id);
            }

            printArrayInfo();

        }
    }).disableSelection();;

// Add styles

    $('<style>')
    .attr('type', 'text/css')
    .html(' body {background:black; color:white; padding:50px;} .sortableClass { clear:both; display: block; overflow: hidden; list-style-type: none; } .sortableClass li { border: 1px solid grey; float:left; clear:none; padding:20px; }')
    .appendTo('head');


    printArrayInfo();

}

function printArrayInfo()
{

    var tStr = '';

    for ( tName in sortable)
    {

        tStr += tName + ': ';

        for(var i=0; i < sortable[tName].length; i++)
        {

            // console.log(sortable[tName][i]);
            tStr += sortable[tName][i] + ', ';

        }

        tStr += '<br>';

    }

    $('#divArrayInfo').html(tStr);

}


function createUl(tArray, tId)
{

    var tUl = $('<ul>', {id:tId, class:'sortableClass'})

    for(var i=0; i < tArray.length; i++)
    {

        // Create Li element
        var tLi = $('<li>' + tArray[i] + '</li>');
        tUl.append(tLi);

    }

    return tUl;
}

function sortArray(a, b, idA, idB)
{
    var c;

    c = sortable[idA].splice(a, 1);
    sortable[idB].splice(b, 0, c);      

}
</script>

Delete all rows in a table based on another table

PostgreSQL implementation would be:

DELETE FROM t1
USING t2
WHERE t1.id = t2.id;

ActionBarActivity cannot resolve a symbol

If the same error occurs in ADT/Eclipse

Add Action Bar Sherlock library in your project.

Now, to remove the "import The import android.support.v7 cannot be resolved" error download a jar file named as android-support-v7-appcompat.jar and add it in your project lib folder.

This will surely removes your both errors.

Authenticate Jenkins CI for Github private repository

An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.

(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)

How to change color of Toolbar back button in Android?

You don't have to change style for it. After setting up your toolbar as actionbar, You can code like this

android.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
android.getSupportActionBar().setHomeAsUpIndicator(R.drawable.back);
//here back is your drawable image

But You cannot change color of back arrow by this method

Split large string in n-size chunks in JavaScript

I would use a regex...

var chunkStr = function(str, chunkLength) {
    return str.match(new RegExp('[\\s\\S]{1,' + +chunkLength + '}', 'g'));
}

Set Date in a single line

Calendar has a set() method that can set the year, month, and day-of-month in one call:

myCal.set( theYear, theMonth, theDay );

Check if null Boolean is true results in exception

If you don't like extra null checks:

if (Boolean.TRUE.equals(value)) {...}

How to decode jwt token in javascript without using a library?

Here is a more feature-rich solution I just made after studying this question:

const parseJwt = (token) => {
    try {
        if (!token) {
            throw new Error('parseJwt# Token is required.');
        }

        const base64Payload = token.split('.')[1];
        let payload = new Uint8Array();

        try {
            payload = Buffer.from(base64Payload, 'base64');
        } catch (err) {
            throw new Error(`parseJwt# Malformed token: ${err}`);
        }

        return {
            decodedToken: JSON.parse(payload),
        };
    } catch (err) {
        console.log(`Bonus logging: ${err}`);

        return {
            error: 'Unable to decode token.',
        };
    }
};

Here's some usage samples:

const unhappy_path1 = parseJwt('sk4u7vgbis4ewku7gvtybrose4ui7gvtmalformedtoken');
console.log('unhappy_path1', unhappy_path1);

const unhappy_path2 = parseJwt('sk4u7vgbis4ewku7gvtybrose4ui7gvt.malformedtoken');
console.log('unhappy_path2', unhappy_path2);

const unhappy_path3 = parseJwt();
console.log('unhappy_path3', unhappy_path3);

const { error, decodedToken } = parseJwt('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c');
if (!decodedToken.exp) {
    console.log('almost_happy_path: token has illegal claims (missing expires_at timestamp)', decodedToken);
    // note: exp, iat, iss, jti, nbf, prv, sub
}

I wasn't able to make that runnable in StackOverflow code snippet tool, but here's approximately what you would see if you ran that code:

enter image description here

I made the parseJwt function always return an object (to some degree for static-typing reasons).

This allows you to utilize syntax such as:

const { decodedToken, error } = parseJwt(token);

Then you can test at run-time for specific types of errors and avoid any naming collision.

If anyone can think of any low effort, high value changes to this code, feel free to edit my answer for the benefit of next(person).

WPF binding to Listbox selectedItem

For me, I usually use DataContext together in order to bind two-depth property such as this question.

<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />

Or, I prefer to use ElementName because it achieves bindings only with view controls.

<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />