Programs & Examples On #Dirent.h

header file for POSIX C containing directory-related functions and types.

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

I experienced a similar error reply while using the openssl command line interface, while having the correct binary key (-K). The option "-nopad" resolved the issue:

Example generating the error:

echo -ne "\x32\xc8\xde\x5c\x68\x19\x7e\x53\xa5\x75\xe1\x76\x1d\x20\x16\xb2\x72\xd8\x40\x87\x25\xb3\x71\x21\x89\xf6\xca\x46\x9f\xd0\x0d\x08\x65\x49\x23\x30\x1f\xe0\x38\x48\x70\xdb\x3b\xa8\x56\xb5\x4a\xc6\x09\x9e\x6c\x31\xce\x60\xee\xa2\x58\x72\xf6\xb5\x74\xa8\x9d\x0c" | openssl aes-128-cbc -d -K 31323334353637383930313233343536 -iv 79169625096006022424242424242424 | od -t x1

Result:

bad decrypt
140181876450560:error:06065064:digital envelope 
routines:EVP_DecryptFinal_ex:bad decrypt:../crypto/evp/evp_enc.c:535:
0000000 2f 2f 07 02 54 0b 00 00 00 00 00 00 04 29 00 00
0000020 00 00 04 a9 ff 01 00 00 00 00 04 a9 ff 02 00 00
0000040 00 00 04 a9 ff 03 00 00 00 00 0d 79 0a 30 36 38

Example with correct result:

echo -ne "\x32\xc8\xde\x5c\x68\x19\x7e\x53\xa5\x75\xe1\x76\x1d\x20\x16\xb2\x72\xd8\x40\x87\x25\xb3\x71\x21\x89\xf6\xca\x46\x9f\xd0\x0d\x08\x65\x49\x23\x30\x1f\xe0\x38\x48\x70\xdb\x3b\xa8\x56\xb5\x4a\xc6\x09\x9e\x6c\x31\xce\x60\xee\xa2\x58\x72\xf6\xb5\x74\xa8\x9d\x0c" | openssl aes-128-cbc -d -K 31323334353637383930313233343536 -iv 79169625096006022424242424242424 -nopad | od -t x1

Result:

0000000 2f 2f 07 02 54 0b 00 00 00 00 00 00 04 29 00 00
0000020 00 00 04 a9 ff 01 00 00 00 00 04 a9 ff 02 00 00
0000040 00 00 04 a9 ff 03 00 00 00 00 0d 79 0a 30 36 38
0000060 30 30 30 34 31 33 31 2f 2f 2f 2f 2f 2f 2f 2f 2f
0000100

How to use S_ISREG() and S_ISDIR() POSIX Macros?

[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).

#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);

int main(int argc, char *argv[]){

  DIR *dip;
  struct dirent *dit;
  struct stat statbuf;
  char currentPath[FILENAME_MAX];
  int depth = 0; /*Used to correctly space output*/

  /*Open Current Directory*/
  if((dip = opendir(".")) == NULL)
    return errno;

  /*Store Current Working Directory in currentPath*/
  if((getcwd(currentPath, FILENAME_MAX)) == NULL)
    return errno;

  /*Read all items in directory*/
  while((dit = readdir(dip)) != NULL){

    /*Skips . and ..*/
    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    /*Correctly forms the path for stat and then resets it for rest of algorithm*/
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    if(stat(currentPath, &statbuf) == -1){
      perror("stat");
      return errno;
    }
    getcwd(currentPath, FILENAME_MAX);


    /*Checks if current item is of the type file (type 8) and no command line arguments*/
    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*If a command line argument is given, checks for filename match*/
    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
      if(strcmp(dit->d_name, argv[1]) == 0)
         printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);

    /*Checks if current item is of the type directory (type 4)*/
    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);

  }
  closedir(dip);
  return 0;
}

/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf, 
        char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  if((dip = opendir(currentPath)) == NULL)
    printf("Error: Failed to open Directory ==> %s\n", currentPath);

  while((dit = readdir(dip)) != NULL){

    if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
      continue;

    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);
    stat(currentPath, &statbuf);
    getcwd(currentPath, FILENAME_MAX);

    if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
      for(i = 0; i < depth; i++)
    printf("    ");
      printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
    }

    if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
      if(strcmp(dit->d_name, argv[1]) == 0){
    for(i = 0; i < depth; i++)
      printf("    ");
    printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
      }
    }

    if(S_ISDIR(statbuf.st_mode))
      dircheck(dip, dit, statbuf, currentPath, depth, argv);
  }
  /*Changing back here is necessary because of how stat is done*/
    chdir("..");
    closedir(dip);
}

void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf, 
          char currentPath[FILENAME_MAX], int depth, char *argv[]){
  int i = 0;

  strcat(currentPath, "/");
  strcat(currentPath, dit->d_name);

  /*If two directories exist at the same level the path
    is built wrong and needs to be corrected*/
  if((chdir(currentPath)) == -1){
    chdir("..");
    getcwd(currentPath, FILENAME_MAX);
    strcat(currentPath, "/");
    strcat(currentPath, dit->d_name);

    for(i = 0; i < depth; i++)
      printf ("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }

  else{
    for(i =0; i < depth; i++)
      printf("    ");
    printf("%s (subdirectory)\n", dit->d_name);
    chdir(currentPath);
    depth++;
    helper(dip, dit, statbuf, currentPath, depth, argv);
  }
}

Checking if a file is a directory or just a file

Yes, there is better. Check the stat or the fstat function

How do you share constants in NodeJS modules?

You can explicitly export it to the global scope with global.FOO = 5. Then you simply need to require the file, and not even save your return value.

But really, you shouldn't do that. Keeping things properly encapsulated is a good thing. You have the right idea already, so keep doing what you're doing.

Difference between ApiController and Controller in ASP.NET MVC

I love the fact that ASP.NET Core's MVC6 merged the two patterns into one because I often need to support both worlds. While it's true that you can tweak any standard MVC Controller (and/or develop your own ActionResult classes) to act & behave just like an ApiController, it can be very hard to maintain and to test: on top of that, having Controllers methods returning ActionResult mixed with others returning raw/serialized/IHttpActionResult data can be very confusing from a developer perspective, expecially if you're not working alone and need to bring other developers to speed with that hybrid approach.

The best technique I've come so far to minimize that issue in ASP.NET non-Core web applications is to import (and properly configure) the Web API package into the MVC-based Web Application, so I can have the best of both worlds: Controllers for Views, ApiControllers for data.

In order to do that, you need to do the following:

  • Install the following Web API packages using NuGet: Microsoft.AspNet.WebApi.Core and Microsoft.AspNet.WebApi.WebHost.
  • Add one or more ApiControllers to your /Controllers/ folder.
  • Add the following WebApiConfig.cs file to your /App_Config/ folder:

using System.Web.Http;

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

Finally, you'll need to register the above class to your Startup class (either Startup.cs or Global.asax.cs, depending if you're using OWIN Startup template or not).

Startup.cs

 public void Configuration(IAppBuilder app)
 {
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    ConfigureAuth(app);
    // ...
}

Global.asax.cs

protected void Application_Start()
{
    // Register Web API routing support before anything else
    GlobalConfiguration.Configure(WebApiConfig.Register);

    // The rest of your file goes there
    // ...
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
    // ...
}

This approach - together with its pros and cons - is further explained in this post I wrote on my blog.

PHP save image file

Note: you should use the accepted answer if possible. It's better than mine.

It's quite easy with the GD library.

It's built in usually, you probably have it (use phpinfo() to check)

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");

imagejpeg($image, "folder/file.jpg");

The above answer is better (faster) for most situations, but with GD you can also modify it in some form (cropping for example).

$image = imagecreatefromjpeg("http://images.websnapr.com/?size=size&key=Y64Q44QLt12u&url=http://google.com");
imagecopy($image, $image, 0, 140, 0, 0, imagesx($image), imagesy($image));
imagejpeg($image, "folder/file.jpg");

This only works if allow_url_fopen is true (it is by default)

Showing Difference between two datetime values in hours

Is there a reason you're using Nullable?

If you want to use Nullable then you can write variable.Value.TotalHours.

Or you can just write: (datevalue1 - datevalue2).TotalHours.

Duplicate Symbols for Architecture arm64

I was able to resolve this error which said "158 duplicate symbols for architecture armv7, 158 duplicate symbols for architecture arm64" --- If this is what you are getting too, then it means you are trying to compile a file which is importing or inheriting a framework or static library having references to C++ code or files. An easy way to handle this would be to change the extension of your .m file to .mm. This is how it gets handled if you are using Objective C, not sure on Swift though.

Also in your build settings - you can update the "other linker flags" to -lc++

Size-limited queue that holds last N elements in Java

Use composition not extends (yes I mean extends, as in a reference to the extends keyword in java and yes this is inheritance). Composition is superier because it completely shields your implementation, allowing you to change the implementation without impacting the users of your class.

I recommend trying something like this (I'm typing directly into this window, so buyer beware of syntax errors):

public LimitedSizeQueue implements Queue
{
  private int maxSize;
  private LinkedList storageArea;

  public LimitedSizeQueue(final int maxSize)
  {
    this.maxSize = maxSize;
    storageArea = new LinkedList();
  }

  public boolean offer(ElementType element)
  {
    if (storageArea.size() < maxSize)
    {
      storageArea.addFirst(element);
    }
    else
    {
      ... remove last element;
      storageArea.addFirst(element);
    }
  }

  ... the rest of this class

A better option (based on the answer by Asaf) might be to wrap the Apache Collections CircularFifoBuffer with a generic class. For example:

public LimitedSizeQueue<ElementType> implements Queue<ElementType>
{
    private int maxSize;
    private CircularFifoBuffer storageArea;

    public LimitedSizeQueue(final int maxSize)
    {
        if (maxSize > 0)
        {
            this.maxSize = maxSize;
            storateArea = new CircularFifoBuffer(maxSize);
        }
        else
        {
            throw new IllegalArgumentException("blah blah blah");
        }
    }

    ... implement the Queue interface using the CircularFifoBuffer class
}

What is the difference between parseInt() and Number()?

Well, they are semantically different, the Number constructor called as a function performs type conversion and parseInt performs parsing, e.g.:

// parsing:
parseInt("20px");       // 20
parseInt("10100", 2);   // 20
parseInt("2e1");        // 2

// type conversion
Number("20px");       // NaN
Number("2e1");        // 20, exponential notation

Also parseInt will ignore trailing characters that don't correspond with any digit of the currently used base.

The Number constructor doesn't detect implicit octals, but can detect the explicit octal notation:

Number("010");         // 10
Number("0o10")         // 8, explicit octal

parseInt("010");       // 8, implicit octal
parseInt("010", 10);   // 10, decimal radix used

And it can handle numbers in hexadecimal notation, just like parseInt:

Number("0xF");   // 15
parseInt("0xF"); //15

In addition, a widely used construct to perform Numeric type conversion, is the Unary + Operator (p. 72), it is equivalent to using the Number constructor as a function:

+"2e1";   // 20
+"0xF";   // 15
+"010";   // 10

C# guid and SQL uniqueidentifier

You can pass a C# Guid value directly to a SQL Stored Procedure by specifying SqlDbType.UniqueIdentifier.

Your method may look like this (provided that your only parameter is the Guid):

public static void StoreGuid(Guid guid)
{
    using (var cnx = new SqlConnection("YourDataBaseConnectionString"))
    using (var cmd = new SqlCommand {
        Connection = cnx,
        CommandType = CommandType.StoredProcedure,
        CommandText = "StoreGuid",
        Parameters = {
            new SqlParameter {
                ParameterName = "@guid",
                SqlDbType = SqlDbType.UniqueIdentifier, // right here
                Value = guid
            }
        }
    })
    {
        cnx.Open();
        cmd.ExecuteNonQuery();
    }
}

See also: SQL Server's uniqueidentifier

How can I find WPF controls by name or type?

My extensions to the code.

  • Added overloads to find one child by type, by type and criteria (predicate), find all children of type which meet the criteria
  • the FindChildren method is an iterator in addition to being an extension method for DependencyObject
  • FindChildren walks logical sub-trees also. See Josh Smith's post linked in the blog post.

Source: https://code.google.com/p/gishu-util/source/browse/#git%2FWPF%2FUtilities

Explanatory blog post : http://madcoderspeak.blogspot.com/2010/04/wpf-find-child-control-of-specific-type.html

What does character set and collation mean exactly?

A character set is a subset of all written glyphs. A character encoding specifies how those characters are mapped to numeric values. Some character encodings, like UTF-8 and UTF-16, can encode any character in the Universal Character Set. Others, like US-ASCII or ISO-8859-1 can only encode a small subset, since they use 7 and 8 bits per character, respectively. Because many standards specify both a character set and a character encoding, the term "character set" is often substituted freely for "character encoding".

A collation comprises rules that specify how characters can be compared for sorting. Collations rules can be locale-specific: the proper order of two characters varies from language to language.

Choosing a character set and collation comes down to whether your application is internationalized or not. If not, what locale are you targeting?

In order to choose what character set you want to support, you have to consider your application. If you are storing user-supplied input, it might be hard to foresee all the locales in which your software will eventually be used. To support them all, it might be best to support the UCS (Unicode) from the start. However, there is a cost to this; many western European characters will now require two bytes of storage per character instead of one.

Choosing the right collation can help performance if your database uses the collation to create an index, and later uses that index to provide sorted results. However, since collation rules are often locale-specific, that index will be worthless if you need to sort results according to the rules of another locale.

Function return value in PowerShell

Luke's description of the function results in these scenarios seems to be right on. I only wish to understand the root cause and the PowerShell product team would do something about the behavior. It seems to be quite common and has cost me too much debugging time.

To get around this issue I've been using global variables rather than returning and using the value from the function call.

Here's another question on the use of global variables: Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

How to share my Docker-Image without using the Docker-Hub?

Docker images are stored as filesystem layers. Every command in the Dockerfile creates a layer. You can also create layers by using docker commit from the command line after making some changes (via docker run probably).

These layers are stored by default under /var/lib/docker. While you could (theoretically) cherry pick files from there and install it in a different docker server, is probably a bad idea to play with the internal representation used by Docker.

When you push your image, these layers are sent to the registry (the docker hub registry, by default… unless you tag your image with another registry prefix) and stored there. When pushing, the layer id is used to check if you already have the layer locally or it needs to be downloaded. You can use docker history to peek at which layers (other images) are used (and, to some extent, which command created the layer).

As for options to share an image without pushing to the docker hub registry, your best options are:

  • docker save an image or docker export a container. This will output a tar file to standard output, so you will like to do something like docker save 'dockerizeit/agent' > dk.agent.latest.tar. Then you can use docker load or docker import in a different host.

  • Host your own private registry. - Outdated, see comments See the docker registry image. We have built an s3 backed registry which you can start and stop as needed (all state is kept on the s3 bucket of your choice) which is trivial to setup. This is also an interesting way of watching what happens when pushing to a registry

  • Use another registry like quay.io (I haven't personally tried it), although whatever concerns you have with the docker hub will probably apply here too.

How to find rows in one table that have no corresponding row in another table

I can't tell you which of these methods will be best on H2 (or even if all of them will work), but I did write an article detailing all of the (good) methods available in TSQL. You can give them a shot and see if any of them works for you:

http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=QueryBasedUponAbsenceOfData&referringTitle=Home

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

After some time and multiple online threads on the subject I managed to fix my project.

It's mainly taking into consideration the last files (could be images or layouts) that you put in. If you delete them, it will work out, and you can build your project again.

make bootstrap twitter dialog modal draggable

You can use the code below if you dont want to use jQuery UI or any third party pluggin. It's only plain jQuery.

This answer works well with Bootstrap v3.x . For version 4.x see @User comment below

_x000D_
_x000D_
$(".modal").modal("show");_x000D_
_x000D_
$(".modal-header").on("mousedown", function(mousedownEvt) {_x000D_
    var $draggable = $(this);_x000D_
    var x = mousedownEvt.pageX - $draggable.offset().left,_x000D_
        y = mousedownEvt.pageY - $draggable.offset().top;_x000D_
    $("body").on("mousemove.draggable", function(mousemoveEvt) {_x000D_
        $draggable.closest(".modal-dialog").offset({_x000D_
            "left": mousemoveEvt.pageX - x,_x000D_
            "top": mousemoveEvt.pageY - y_x000D_
        });_x000D_
    });_x000D_
    $("body").one("mouseup", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
    $draggable.closest(".modal").one("bs.modal.hide", function() {_x000D_
        $("body").off("mousemove.draggable");_x000D_
    });_x000D_
});
_x000D_
.modal-header {_x000D_
    cursor: move;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="modal fade" tabindex="-1" role="dialog">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        <p>One fine body&hellip;</p>_x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div><!-- /.modal-content -->_x000D_
  </div><!-- /.modal-dialog -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get paragraph text inside an element

change your html to the following:

<ul>
    <li onclick="myfunction()">
        <span></span>
        <p id="myParagraph">This Text</p>
    </li>
</ul>

then you can get the content of your paragraph with the following function:

function getContent() {
    return document.getElementById("myParagraph").innerHTML;
}

Execute a terminal command from a Cocoa app

kent's article gave me a new idea. this runCommand method doesn't need a script file, just runs a command by a line:

- (NSString *)runCommand:(NSString *)commandToRun
{
    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:@"/bin/sh"];

    NSArray *arguments = [NSArray arrayWithObjects:
                          @"-c" ,
                          [NSString stringWithFormat:@"%@", commandToRun],
                          nil];
    NSLog(@"run command:%@", commandToRun);
    [task setArguments:arguments];

    NSPipe *pipe = [NSPipe pipe];
    [task setStandardOutput:pipe];

    NSFileHandle *file = [pipe fileHandleForReading];

    [task launch];

    NSData *data = [file readDataToEndOfFile];

    NSString *output = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    return output;
}

You can use this method like this:

NSString *output = runCommand(@"ps -A | grep mysql");

SQL server stored procedure return a table

I do this frequently using Table Types to ensure more consistency and simplify code. You can't technically return "a table", but you can return a result set and using INSERT INTO .. EXEC ... syntax, you can clearly call a PROC and store the results into a table type. In the following example I'm actually passing a table into a PROC along with another param I need to add logic, then I'm effectively "returning a table" and can then work with that as a table variable.

/****** Check if my table type and/or proc exists and drop them ******/
IF EXISTS (SELECT * FROM sys.objects WHERE type = 'P' AND name = 'returnTableTypeData')
DROP PROCEDURE returnTableTypeData
GO
IF EXISTS (SELECT * FROM sys.types WHERE is_table_type = 1 AND name = 'myTableType')
DROP TYPE myTableType
GO

/****** Create the type that I'll pass into the proc and return from it ******/
CREATE TYPE [dbo].[myTableType] AS TABLE(
    [someInt] [int] NULL,
    [somenVarChar] [nvarchar](100) NULL
)
GO

CREATE PROC returnTableTypeData
    @someInputInt INT,
    @myInputTable myTableType READONLY --Must be readonly because
AS
BEGIN

    --Return the subset of data consistent with the type
    SELECT
        *
    FROM
        @myInputTable
    WHERE
        someInt < @someInputInt

END
GO


DECLARE @myInputTableOrig myTableType
DECLARE @myUpdatedTable myTableType

INSERT INTO @myInputTableOrig ( someInt,somenVarChar )
VALUES ( 0, N'Value 0' ), ( 1, N'Value 1' ), ( 2, N'Value 2' )

INSERT INTO @myUpdatedTable EXEC returnTableTypeData @someInputInt=1, @myInputTable=@myInputTableOrig

SELECT * FROM @myUpdatedTable


DROP PROCEDURE returnTableTypeData
GO
DROP TYPE myTableType
GO

Conditional Formatting using Excel VBA code

I think I just discovered a way to apply overlapping conditions in the expected way using VBA. After hours of trying out different approaches I found that what worked was changing the "Applies to" range for the conditional format rule, after every single one was created!

This is my working example:

Sub ResetFormatting()
' ----------------------------------------------------------------------------------------
' Written by..: Julius Getz Mørk
' Purpose.....: If conditional formatting ranges are broken it might cause a huge increase
'               in duplicated formatting rules that in turn will significantly slow down
'               the spreadsheet.
'               This macro is designed to reset all formatting rules to default.
' ---------------------------------------------------------------------------------------- 

On Error GoTo ErrHandler

' Make sure we are positioned in the correct sheet
WS_PROMO.Select

' Disable Events
Application.EnableEvents = False

' Delete all conditional formatting rules in sheet
Cells.FormatConditions.Delete

' CREATE ALL THE CONDITIONAL FORMATTING RULES:

' (1) Make negative values red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlLess, "=0")
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (2) Highlight defined good margin as green values
With Cells(1, 1).FormatConditions.add(xlCellValue, xlGreater, "=CP_HIGH_MARGIN_DEFINITION")
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (3) Make article strategy "D" red
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""D""")
    .Font.Bold = True
    .Font.Color = -16776961
    .StopIfTrue = False
End With

' (4) Make article strategy "A" blue
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""A""")
    .Font.Bold = True
    .Font.Color = -10092544
    .StopIfTrue = False
End With

' (5) Make article strategy "W" green
With Cells(1, 1).FormatConditions.add(xlCellValue, xlEqual, "=""W""")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (6) Show special cost in bold green font
With Cells(1, 1).FormatConditions.add(xlCellValue, xlNotEqual, "=0")
    .Font.Bold = True
    .Font.Color = -16744448
    .StopIfTrue = False
End With

' (7) Highlight duplicate heading names. There can be none.
With Cells(1, 1).FormatConditions.AddUniqueValues
    .DupeUnique = xlDuplicate
    .Font.Color = -16383844
    .Interior.Color = 13551615
    .StopIfTrue = False
End With

' (8) Make heading rows bold with yellow background
With Cells(1, 1).FormatConditions.add(Type:=xlExpression, Formula1:="=IF($B8=""H"";TRUE;FALSE)")
    .Font.Bold = True
    .Interior.Color = 13434879
    .StopIfTrue = False
End With

' Modify the "Applies To" ranges
Cells.FormatConditions(1).ModifyAppliesToRange Range("O8:P507")
Cells.FormatConditions(2).ModifyAppliesToRange Range("O8:O507")
Cells.FormatConditions(3).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(4).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(5).ModifyAppliesToRange Range("B8:B507")
Cells.FormatConditions(6).ModifyAppliesToRange Range("E8:E507")
Cells.FormatConditions(7).ModifyAppliesToRange Range("A7:AE7")
Cells.FormatConditions(8).ModifyAppliesToRange Range("B8:L507")


ErrHandler:
Application.EnableEvents = False

End Sub

How can I join multiple SQL tables using the IDs?

You want something more like this:

SELECT TableA.*, TableB.*, TableC.*, TableD.*
FROM TableA
    JOIN TableB
        ON TableB.aID = TableA.aID
    JOIN TableC
        ON TableC.cID = TableB.cID
    JOIN TableD
        ON TableD.dID = TableA.dID
WHERE DATE(TableC.date)=date(now()) 

In your example, you are not actually including TableD. All you have to do is perform another join just like you have done before.

A note: you will notice that I removed many of your parentheses, as they really are not necessary in most of the cases you had them, and only add confusion when trying to read the code. Proper nesting is the best way to make your code readable and separated out.

Using intents to pass data between activities

Simple.

Assuming that in your Activity-1, you did this:

String stringExtra = "Some string you want to pass";

Intent intent = new Intent(this, AndroidTabRestaurantDescSearchListView.class);

//include the string in your intent
intent.putExtra("string", stringExtra);

startActivity(intent);

And in your AndroidTabRestaurantDescSearchListView class, do this:

//fetch the string  from the intent
String extraFromAct1 = getIntent().getStringExtra("string");

Intent intent = new Intent(this, RatingDescriptionSearchActivity.class);

//attach same string and send it with the intent
intent.putExtra("string", extraFromAct1);
startActivity(intent);

Then in your RatingDescriptionSearchActivity class, do this:

String extraFromAct1 = getIntent().getStringExtra("string");

how to set select element as readonly ('disabled' doesnt pass select value on server)

You can simulate a readonly select box using the CSS pointer-events property:

select[readonly]
{
    pointer-events: none;
}

The HTML tabindex property will also prevent it from being selected by keyboard tabbing:

<select tabindex="-1">

_x000D_
_x000D_
select[readonly]_x000D_
{_x000D_
    pointer-events: none;_x000D_
}_x000D_
_x000D_
_x000D_
/* irrelevent styling */_x000D_
_x000D_
*_x000D_
{_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
*[readonly]_x000D_
{_x000D_
  background: #fafafa;_x000D_
  border: 1px solid #ccc;_x000D_
  color: #555;_x000D_
}_x000D_
_x000D_
input, select_x000D_
{_x000D_
  display:block;_x000D_
  width: 20rem;_x000D_
  padding: 0.5rem;_x000D_
  margin-bottom: 1rem;_x000D_
}
_x000D_
<form>_x000D_
  <input type="text" value="this is a normal text box">_x000D_
  <input type="text" readonly value="this is a readonly text box">_x000D_
  <select readonly tabindex="-1">_x000D_
    <option>This is a readonly select box</option>_x000D_
    <option>Option 2</option>_x000D_
  </select>_x000D_
  <select>_x000D_
    <option>This is a normal select box</option>_x000D_
    <option>Option 2</option>_x000D_
  </select>_x000D_
</form>
_x000D_
_x000D_
_x000D_

TypeLoadException says 'no implementation', but it is implemented

I had this error too, it was caused by an Any CPU exe referencing Any CPU assemblies that in turn referenced an x86 assembly.

The exception complained about a method on a class in MyApp.Implementations (Any CPU), which derived MyApp.Interfaces (Any CPU), but in fuslogvw.exe I found a hidden 'attempt to load program with an incorrect format' exception from MyApp.CommonTypes (x86) which is used by both.

How to test whether a service is running from the command line

@ECHO OFF
REM testing at cmd : sc query "MSSQLSERVER" | findstr RUNNING
REM "MSSQLSERVER" is the name of Service for sample
sc query "MSSQLSERVER" %1 | findstr RUNNING
if %ERRORLEVEL% == 2 goto trouble
if %ERRORLEVEL% == 1 goto stopped
if %ERRORLEVEL% == 0 goto started
echo unknown status
goto end
:trouble
echo Oh noooo.. trouble mas bro
goto end
:started
echo "SQL Server (MSSQLSERVER)" is started
goto end
:stopped
echo "SQL Server (MSSQLSERVER)" is stopped
echo Starting service
net start "MSSQLSERVER"
goto end
:erro
echo Error please check your command.. mas bro 
goto end

:end

Powershell equivalent of bash ampersand (&) for forking/running background processes

From PowerShell Core 6.0 you are able to write & at end of command and it will be equivalent to running you pipeline in background in current working directory.

It's not equivalent to & in bash, it's just a nicer syntax for current PowerShell jobs feature. It returns a job object so you can use all other command that you would use for jobs. For example Receive-Job:

C:\utils> ping google.com &

Id     Name            PSJobTypeName   State         HasMoreData     Location             Command
--     ----            -------------   -----         -----------     --------             -------
35     Job35           BackgroundJob   Running       True            localhost            Microsoft.PowerShell.M...


C:\utils> Receive-Job 35

Pinging google.com [172.217.16.14] with 32 bytes of data:
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=11ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55
Reply from 172.217.16.14: bytes=32 time=10ms TTL=55

Ping statistics for 172.217.16.14:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 10ms, Maximum = 11ms, Average = 10ms
C:\utils>

If you want to execute couple of statements in background you can combine & call operator, { } script block and this new & background operator like here:

& { cd .\SomeDir\; .\SomeLongRunningOperation.bat; cd ..; } &

Here's some more info from documentation pages:

from What's New in PowerShell Core 6.0:

Support backgrounding of pipelines with ampersand (&) (#3360)

Putting & at the end of a pipeline causes the pipeline to be run as a PowerShell job. When a pipeline is backgrounded, a job object is returned. Once the pipeline is running as a job, all of the standard *-Job cmdlets can be used to manage the job. Variables (ignoring process-specific variables) used in the pipeline are automatically copied to the job so Copy-Item $foo $bar & just works. The job is also run in the current directory instead of the user's home directory. For more information about PowerShell jobs, see about_Jobs.

from about_operators / Ampersand background operator &:

Ampersand background operator &

Runs the pipeline before it in a PowerShell job. The ampersand background operator acts similarly to the UNIX "ampersand operator" which famously runs the command before it as a background process. The ampersand background operator is built on top of PowerShell jobs so it shares a lot of functionality with Start-Job. The following command contains basic usage of the ampersand background operator.

Get-Process -Name pwsh &

This is functionally equivalent to the following usage of Start-Job.

Start-Job -ScriptBlock {Get-Process -Name pwsh}

Since it's functionally equivalent to using Start-Job, the ampersand background operator returns a Job object just like Start-Job does. This means that you are able to use Receive-Job and Remove-Job just as you would if you had used Start-Job to start the job.

$job = Get-Process -Name pwsh &
Receive-Job $job

Output

NPM(K)    PM(M)      WS(M)     CPU(s)      Id  SI ProcessName
------    -----      -----     ------      --  -- -----------
    0     0.00     221.16      25.90    6988 988 pwsh
    0     0.00     140.12      29.87   14845 845 pwsh
    0     0.00      85.51       0.91   19639 988 pwsh


$job = Get-Process -Name pwsh &
Remove-Job $job

For more information on PowerShell jobs, see about_Jobs.

Can I delete a git commit but keep the changes?

2020 Simple way :

git reset <commit_hash>

(The commit hash of the last commit you want to keep).

If the commit was pushed, you can then do :

git push -f

You will keep the now uncommitted changes locally

How to Call VBA Function from Excel Cells?

A Function will not work, nor is it necessary:

Sub OpenWorkbook()
    Dim r1 As Range, r2 As Range, o As Workbook
    Set r1 = ThisWorkbook.Sheets("Sheet1").Range("A1")
    Set o = Workbooks.Open(Filename:="C:\TestFolder\ABC.xlsx")
    Set r2 = ActiveWorkbook.Sheets("Sheet1").Range("B2")
    [r1] = [r2]
    o.Close
End Sub

How to open a WPF Popup when another control is clicked, using XAML markup only?

The following approach is the same as Helge Klein's, except that the popup closes automatically when you click anywhere outside the Popup (including the ToggleButton itself):

<ToggleButton x:Name="Btn" IsHitTestVisible="{Binding ElementName=Popup, Path=IsOpen, Mode=OneWay, Converter={local:BoolInverter}}">
    <TextBlock Text="Click here for popup!"/>
</ToggleButton>

<Popup IsOpen="{Binding IsChecked, ElementName=Btn}" x:Name="Popup" StaysOpen="False">
    <Border BorderBrush="Black" BorderThickness="1" Background="LightYellow">
        <CheckBox Content="This is a popup"/>
    </Border>
</Popup>

"BoolInverter" is used in the IsHitTestVisible binding so that when you click the ToggleButton again, the popup closes:

public class BoolInverter : MarkupExtension, IValueConverter
{
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is bool)
            return !(bool)value;
        return value;
    }
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Convert(value, targetType, parameter, culture);
    }
}

...which shows the handy technique of combining IValueConverter and MarkupExtension in one.

I did discover one problem with this technique: WPF is buggy when two popups are on the screen at the same time. Specifically, if your toggle button is on the "overflow popup" in a toolbar, then there will be two popups open after you click it. You may then find that the second popup (your popup) will stay open when you click anywhere else on your window. At that point, closing the popup is difficult. The user cannot click the ToggleButton again to close the popup because IsHitTestVisible is false because the popup is open! In my app I had to use a few hacks to mitigate this problem, such as the following test on the main window, which says (in the voice of Louis Black) "if the popup is open and the user clicks somewhere outside the popup, close the friggin' popup.":

PreviewMouseDown += (s, e) =>
{
    if (Popup.IsOpen)
    {
        Point p = e.GetPosition(Popup.Child);
        if (!IsInRange(p.X, 0, ((FrameworkElement)Popup.Child).ActualWidth) ||
            !IsInRange(p.Y, 0, ((FrameworkElement)Popup.Child).ActualHeight))
            Popup.IsOpen = false;
    }
};
// Elsewhere...
public static bool IsInRange(int num, int lo, int hi) => 
    num >= lo && num <= hi;

Get text of the selected option with jQuery

Change your selector to

val = j$("#select_2 option:selected").text();

You're selecting the <select> instead of the <option>

How to get single value of List<object>

You can access the fields by indexing the object array:

foreach (object[] item in selectedValues)
{
  idTextBox.Text = item[0];
  titleTextBox.Text = item[1];
  contentTextBox.Text = item[2];
}

That said, you'd be better off storing the fields in a small class of your own if the number of items is not dynamic:

public class MyObject
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

Then you can do:

foreach (MyObject item in selectedValues)
{
  idTextBox.Text = item.Id;
  titleTextBox.Text = item.Title;
  contentTextBox.Text = item.Content;
}

How to add additional libraries to Visual Studio project?

Without knowing your compiler, no one can give you specific, step by step instructions, but the basic procedure is as follows:

  1. Specify the path which should be searched in order to find the actual library (usually under Library Search Paths, Library Directories, etc. in the properties page)

  2. Under linker options, specify the actual name of the library. In VS, you would write Allegro.lib (or whatever it is), on Linux you usually just write Allegro (prefixes/suffixes are added automatically in most cases). This is usually under "Libraries->Input", just "Libraries", or something similar.

  3. Ensure that you have included the headers for the library and make sure that they can be found (similar process to that listed in step #1 and #2). If it is a static library, you should be good; if it's a DLL, you need to copy it in your project.

  4. Mash the build button.

Removing object from array in Swift 3

The correct and working one-line solution for deleting a unique object (named "objectToRemove") from an array of these objects (named "array") in Swift 3 is:

if let index = array.enumerated().filter( { $0.element === objectToRemove }).map({ $0.offset }).first {
   array.remove(at: index)
}

jQuery prevent change for select

Implement custom readonly like eventHandler

<select id='country' data-changeable=false>
  <option selected value="INDIA">India</option>
  <option value="USA">United States</option>
  <option value="UK">United Kingdom</option>
</select>

<script>
    var lastSelected = $("#country option:selected");

    $("#country").on("change", function() {
       if(!$(this).data(changeable)) {
            lastSelected.attr("selected", true);              
       }        
    });

    $("#country").on("click", function() {
       lastSelected = $("#country option:selected");
    });
</script>

Demo : https://jsfiddle.net/0mvajuay/8/

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

As of 2018, we have several new formats, better support for previous formats and some clever hacks of using videos instead of images.

For photographs

jpg - still the most widely supported image format.

webp - New format from google. Good potential, though browser support is not great.

For Icons and graphics

svg - whenever possible. It scales well in retina screens, editable in text editors and customisable via JS/CSS if loaded in DOM.

png - if it involves raster graphics (ie when created in photoshop). Supports transparency which is very essential in this use-case.

For Animations

svg - plus css animations for vector graphics. All advantages of svg + power of css animations.

gif - still the most widely supported animated image format.

mp4 - if animated images are actually short video clips. Twitter / Whatsapp converts gifs to mp4.

apng - decent browser support (i.e. no IE, Edge), but creating it is not as straightforward as gifs.

webp - close to using mp4. Poor support

This is a nice comparison of various animated image formats.

Finally, whichever be the format, make sure to optimize it - There are tools for each format (eg SVGO, Guetzli, OptiPNG etc) and can save considerable bandwidth.

mat-form-field must contain a MatFormFieldControl

I had accidentally removed the matInput directive from the input field which caused the same error.

eg.

<mat-form-field>
   <input [readOnly]="readOnly" name="amount" formControlName="amount" placeholder="Amount">
</mat-form-field>

fixed code

 <mat-form-field>
   <input matInput [readOnly]="readOnly" name="amount" formControlName="amount" placeholder="Amount">
</mat-form-field>

How to get IntPtr from byte[] in C#

You could use Marshal.UnsafeAddrOfPinnedArrayElement to get a memory pointer to the array (or to a specific element in the array). Keep in mind that the array must be pinned first as per the API documentation:

The array must be pinned using a GCHandle before it is passed to this method. For maximum performance, this method does not validate the array passed to it; this can result in unexpected behavior.

Apache and IIS side by side (both listening to port 80) on windows2003

Installing Windows 10 I had this problem: apache(ipv4) and spooler service(ipv6) listening the same 80 port.

I resolved editing apache httpd.conf file changing the line

Listen 80

to

Listen 127.0.0.1:80

Passing a variable to a powershell script via command line

Using param to name the parameters allows you to ignore the order of the parameters:

ParamEx.ps1

# Show how to handle command line parameters in Windows PowerShell
param(
  [string]$FileName,
  [string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus

ParaEx.bat

rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"

Calling another different view from the controller using ASP.NET MVC 4

To return a different view, you can specify the name of the view you want to return and model as follows:

return View("ViewName", yourModel);

if the view is in different folder under Views folder then use below absolute path:

return View("~/Views/FolderName/ViewName.aspx");

Spring Test & Security: How to mock authentication?

Short answer:

@Autowired
private WebApplicationContext webApplicationContext;

@Autowired
private Filter springSecurityFilterChain;

@Before
public void setUp() throws Exception {
    final MockHttpServletRequestBuilder defaultRequestBuilder = get("/dummy-path");
    this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext)
            .defaultRequest(defaultRequestBuilder)
            .alwaysDo(result -> setSessionBackOnRequestBuilder(defaultRequestBuilder, result.getRequest()))
            .apply(springSecurity(springSecurityFilterChain))
            .build();
}

private MockHttpServletRequest setSessionBackOnRequestBuilder(final MockHttpServletRequestBuilder requestBuilder,
                                                             final MockHttpServletRequest request) {
    requestBuilder.session((MockHttpSession) request.getSession());
    return request;
}

After perform formLogin from spring security test each of your requests will be automatically called as logged in user.

Long answer:

Check this solution (the answer is for spring 4): How to login a user with spring 3.2 new mvc testing

Returning a value from thread?

Here is a simple example using a delegate ...

void Main()
{
   DoIt d1 = Doer.DoThatThang;
   DoIt d2 = Doer.DoThatThang;

   IAsyncResult r1 = d1.BeginInvoke( 5, null, null );
   IAsyncResult r2 = d2.BeginInvoke( 10, null, null );

   Thread.Sleep( 1000 );

   var s1 = d1.EndInvoke( r1 );
   var s2 = d2.EndInvoke( r2 );

   s1.Dump(); // You told me 5
   s2.Dump(); // You told me 10
}

public delegate string DoIt( int x );

public class Doer
{
  public static string DoThatThang( int x  )
  {
    return "You told me " + x.ToString();
  }
}

There's a terrific series on threading at Threading in C#.

How to call an async method from a getter or setter?

You can always call an asynchronous method without await if you simply want to fire and forget. But it becomes tricky when you need to wait for the result and do something with the result.

I had to call an async method in a property setter in an ASP.NET Core Blazor Server Side component. I needed to get a result from that async method and do something else.

I was stuck as I could not even use the Task.Result property in Blazor context.

So, I solved the problem by calling the .ContinueWith method which worked great. Here is a sample snippet I used.

    public bool AProperty
    {
        get => _aProperty;
        set
        {
            if (_aProperty!= value)
            {
                _aProperty= value;

                myService.UpdateAReocrdAsync().ContinueWith(previousTask =>
                {
                    int numberOfRowsAffected = previousTask.Result;
                   
                    if (numberOfRowsAffected > 0)
                    {
                        toastService.ShowSuccess($"Total {numberOfRowsAffected} rows updated.");
                    }
                    else
                    {
                        toastService.ShowError("No record was updated.");
                    }
                });
            }
        }
    }

SQLAlchemy equivalent to SQL "LIKE" statement

Using PostgreSQL like (see accepted answer above) somehow didn't work for me although cases matched, but ilike (case insensisitive like) does.

Map over object preserving keys

With Underscore

Underscore provides a function _.mapObject to map the values and preserve the keys.

_.mapObject({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

// => { one: 3, two: 6, three: 9 }

DEMO


With Lodash

Lodash provides a function _.mapValues to map the values and preserve the keys.

_.mapValues({ one: 1, two: 2, three: 3 }, function (v) { return v * 3; });

// => { one: 3, two: 6, three: 9 }

DEMO

Sublime Text 2: How to delete blank/empty lines

In my case some empty lines contained the unicode character zero width space (U+200b). To rid empty lines, including the ones with this unicode character:

\s\x{200b}|^\s

How to create a directory in Java?

You can try FileUtils#forceMkdir

FileUtils.forceMkdir("/path/directory");

This library have a lot of useful functions.

What exactly is Apache Camel?

Camel helps in routing, transformation, monitoring.

It uses Routes; which can be described as :

When service bus receives particular message, it will route it through no of services/broker destinations such as queue/topics. This path is known as route.

Example: your stock application has got some input by analyst, it will be processed through the application/web component and then result will be published to all the interested/registered members for particular stock update.

Asynchronously wait for Task<T> to complete with timeout

You can use Task.WaitAny to wait the first of multiple tasks.

You could create two additional tasks (that complete after the specified timeouts) and then use WaitAny to wait for whichever completes first. If the task that completed first is your "work" task, then you're done. If the task that completed first is a timeout task, then you can react to the timeout (e.g. request cancellation).

PHP date yesterday

strtotime(), as in date("F j, Y", strtotime("yesterday"));

How can I check if a value is of type Integer?

You need to first check if it's a number. If so you can use the Math.Round method. If the result and the original value are equal then it's an integer.

PHP random string generator

There are a lot of answers to this question, but none of them leverage a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG).

The simple, secure, and correct answer is to use RandomLib and don't reinvent the wheel.

For those of you who insist on inventing your own solution, PHP 7.0.0 will provide random_int() for this purpose; if you're still on PHP 5.x, we wrote a PHP 5 polyfill for random_int() so you can use the new API even before you upgrade to PHP 7.

Safely generating random integers in PHP isn't a trivial task. You should always check with your resident StackExchange cryptography experts before you deploy a home-grown algorithm in production.

With a secure integer generator in place, generating a random string with a CSPRNG is a walk in the park.

Creating a Secure, Random String

/**
 * Generate a random string, using a cryptographically secure 
 * pseudorandom number generator (random_int)
 *
 * This function uses type hints now (PHP 7+ only), but it was originally
 * written for PHP 5 as well.
 * 
 * For PHP 7, random_int is a PHP core function
 * For PHP 5.x, depends on https://github.com/paragonie/random_compat
 * 
 * @param int $length      How many characters do we want?
 * @param string $keyspace A string of all possible characters
 *                         to select from
 * @return string
 */
function random_str(
    int $length = 64,
    string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
): string {
    if ($length < 1) {
        throw new \RangeException("Length must be a positive integer");
    }
    $pieces = [];
    $max = mb_strlen($keyspace, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $pieces []= $keyspace[random_int(0, $max)];
    }
    return implode('', $pieces);
}

Usage:

$a = random_str(32);
$b = random_str(8, 'abcdefghijklmnopqrstuvwxyz');
$c = random_str();

Demo: https://3v4l.org/IMJGF (Ignore the PHP 5 failures; it needs random_compat)

Mapping US zip code to time zone

Also note, that if you happen to be using Yahoo geocoding service you can have timezone information returned to you by setting the correct flag.

http://developer.yahoo.com/geo/placefinder/guide/requests.html#flags-parameter

How to set session timeout dynamically in Java web applications?

Instead of using a ServletContextListener, use a HttpSessionListener.

In the sessionCreated() method, you can set the session timeout programmatically:

public class MyHttpSessionListener implements HttpSessionListener {

  public void sessionCreated(HttpSessionEvent event){
      event.getSession().setMaxInactiveInterval(15 * 60); // in seconds
  }

  public void sessionDestroyed(HttpSessionEvent event) {}

}

And don't forget to define the listener in the deployment descriptor:

<webapp>
...      
  <listener>                                  
    <listener-class>com.example.MyHttpSessionListener</listener-class>
  </listener>
</webapp>

(or since Servlet version 3.0 you can use @WebListener annotation instead).


Still, I would recommend creating different web.xml files for each application and defining the session timeout there:

<webapp>
...
  <session-config>
    <session-timeout>15</session-timeout> <!-- in minutes -->
  </session-config>
</webapp>

How to concatenate two strings in C++?

Since it's C++ why not to use std::string instead of char*? Concatenation will be trivial:

std::string str = "abc";
str += "another";

Submitting a form by pressing enter without a submit button

For those who have problems with IE and for others too.

{
    float: left;
    width: 1px;
    height: 1px;
    background-color: transparent;
    border: none;
}

Prevent the keyboard from displaying on activity start

To expand upon the accepted answer by @Lucas:

Call this from your activity in one of the early life cycle events:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

Kotlin Example:

override fun onResume() {
  super.onResume()

  window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
}

How to create range in Swift?

You can use like this

let nsRange = NSRange(location: someInt, length: someInt)

as in

let myNSString = bigTOTPCode as NSString //12345678
let firstDigit = myNSString.substringWithRange(NSRange(location: 0, length: 1)) //1
let secondDigit = myNSString.substringWithRange(NSRange(location: 1, length: 1)) //2
let thirdDigit = myNSString.substringWithRange(NSRange(location: 2, length: 4)) //3456

Shortcut for changing font size

Be sure to check out the VS 2010 Beta that was just released. The new editor should have this.

Is there a difference between "throw" and "throw ex"?

It's better to use throw instead of throw ex.

throw ex reset the original stack trace and can't be found the previous stack trace.

If we use throw, we will get a full stack trace.

The Completest Cocos2d-x Tutorial & Guide List

Here you got complementaries discussions about the topic, it can be interesting.

discussion1

discussion2

How to gzip all files in all sub-directories into one compressed file in bash

there are lots of compression methods that work recursively command line and its good to know who the end audience is.

i.e. if it is to be sent to someone running windows then zip would probably be best:

zip -r file.zip folder_to_zip

unzip filenname.zip

for other linux users or your self tar is great

tar -cvzf filename.tar.gz folder

tar -cvjf filename.tar.bz2 folder  # even more compression

#change the -c to -x to above to extract

One must be careful with tar and how things are tarred up/extracted, for example if I run

cd ~
tar -cvzf passwd.tar.gz /etc/passwd
tar: Removing leading `/' from member names
/etc/passwd


pwd

/home/myusername

tar -xvzf passwd.tar.gz

this will create /home/myusername/etc/passwd

unsure if all versions of tar do this:

 Removing leading `/' from member names

How to scroll to specific item using jQuery?

Scroll element to center of container

To bring the element to the center of the container.

DEMO on CODEPEN

JS

function scrollToCenter() {
  var container = $('.container'),
    scrollTo = $('.5');

  container.animate({
    //scrolls to center
    scrollTop: scrollTo.offset().top - container.offset().top + scrollTo.scrollTop() - container.height() / 2
  });
}

HTML

<div class="container">
   <div class="1">
    1
  </div>
  <div class="2">
    2
  </div>
  <div class="3">
    3
  </div>
  <div class="4">
    4
  </div>
  <div class="5">
    5
  </div>
  <div class="6">
    6
  </div>
  <div class="7">
    7
  </div>
  <div class="8">
    8
  </div>
  <div class="9">
    9
  </div>
  <div class="10">
    10
  </div>


</div>
<br>
<br>
<button id="scroll" onclick="scrollToCenter()">
  Scroll
</button>

css

.container {
  height: 60px;
  overflow-y: scroll;
  width 60px;
  background-color: white;
}

It is not exact to the center but you will not recognice it on larger bigger elements.

Python date string to date object

If you are lazy and don't want to fight with string literals, you can just go with the parser module.

from dateutil import parser
dt = parser.parse("Jun 1 2005  1:33PM")
print(dt.year, dt.month, dt.day,dt.hour, dt.minute, dt.second)
>2005 6 1 13 33 0

Just a side note, as we are trying to match any string representation, it is 10x slower than strptime

self referential struct definition?

Another convenient method is to pre-typedef the structure with,structure tag as:

//declare new type 'Node', as same as struct tag
typedef struct Node Node;
//struct with structure tag 'Node'
struct Node
{
int data;
//pointer to structure with custom type as same as struct tag
Node *nextNode;
};
//another pointer of custom type 'Node', same as struct tag
Node *node;

Copy multiple files from one directory to another from Linux shell

I guess you are looking for brace expansion:

cp /home/ankur/folder/{file1,file2} /home/ankur/dest

take a look here, it would be helpful for you if you want to handle multiple files once :

http://www.tldp.org/LDP/abs/html/globbingref.html

tab completion with zsh...

enter image description here

How do I make Visual Studio pause after executing a console application in debug mode?

Prompt for user input.

https://www.youtube.com/watch?v=NIGhjrWLWBo

shows how to do this for C++. For Node.js, this is taken right from the docs (and it works):

'use strict';

console.log('Hello world');

const readline = require('readline');
const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});

rl.question('Press enter to continue...', (answer) => {
    rl.close(); /* discard the answer */
});

Print current call stack from a method in Python code

for those who need to print the call stack while using pdb, just do

(Pdb) where

Integer.toString(int i) vs String.valueOf(int i)

Using the method, String.valueOf() you do not have to worry about the data(whether it is int,long,char,char[],boolean,Object), you can just call :

  • static String valueOf()

using the only syntax String.valueOf() can whatever you pass as a parameter is converted to String and returned..

Otherwise, if you use Integer.toString(),Float.toString() etc.(i.e. SomeType.toString()) then you will have to check the datatype of parameter that you want to convert into string. So, its better to use String.valueOf() for such convertions.

If you are having an array of object class that contains different values like Integer,Char,Float etc. then by using String.valueOf() method you can convert the elements of such array into String form easily. On contrary, if you want to use SomeType.toString() then at first you will need to know about there their datatype classes(maybe by using "instanceOf" operator) and then only you can proceed for a typecast.

String.valueOf() method when called matches the parameter that is passed(whether its Integer,Char,Float etc.) and by using method overloading calls that "valueOf()" method whose parameter gets matched, and then inside that method their is a direct call to corresponding "toString()" method..

So, we can see how the overhead of checking datatype and then calling corresponding "toString()" method is removed.Only we need is to call String.valueOf() method, not caring about what we want to convert to String.

Conclusion: String.valueOf() method has its importance just at cost of one more call.

Convert a row of a data frame to vector

Here is a dplyr based option:

newV = df %>% slice(1) %>% unlist(use.names = FALSE)

# or slightly different:
newV = df %>% slice(1) %>% unlist() %>% unname()

React-Native: Application has not been registered error

After have read all the above, I have found that there could be another reason for this.

In my case:

react-native-cli: 2.0.1

react-native: 0.60.4

and following structure:

enter image description here

First has to be noted that index.android is not been update in Android Studio when the build run by Metro builder( react-native run-android) so it has to be done manually. Also in Android studio does not "read" the

app.json(created by default together with index.js, that renamed index.android.js):

 {
    "name": "authApp",
    "displayName": "authApp"
 }

and so this like

(in my case)

import {authApp as appName} from './app.json';

cause the fact that android studio does not know what authApp refer to. I fix for the moment referring to the app name with its string name and not using that import from app.json:

AppRegistry.registerComponent('authApp', () => MyApp);

HTML/CSS - Adding an Icon to a button

<a href="#" class="btnTest">Test</a>


.btnTest{
   background:url('images/icon.png') no-repeat left center;
   padding-left:20px;
}    

Split Spark Dataframe string column into multiple columns

pyspark.sql.functions.split() is the right approach here - you simply need to flatten the nested ArrayType column into multiple top-level columns. In this case, where each array only contains 2 items, it's very easy. You simply use Column.getItem() to retrieve each part of the array as a column itself:

split_col = pyspark.sql.functions.split(df['my_str_col'], '-')
df = df.withColumn('NAME1', split_col.getItem(0))
df = df.withColumn('NAME2', split_col.getItem(1))

The result will be:

col1 | my_str_col | NAME1 | NAME2
-----+------------+-------+------
  18 |  856-yygrm |   856 | yygrm
 201 |  777-psgdg |   777 | psgdg

I am not sure how I would solve this in a general case where the nested arrays were not the same size from Row to Row.

What is the difference between char, nchar, varchar, and nvarchar in SQL Server?

nchar and char pretty much operate in exactly the same way as each other, as do nvarchar and varchar. The only difference between them is that nchar/nvarchar store Unicode characters (essential if you require the use of extended character sets) whilst varchar does not.

Because Unicode characters require more storage, nchar/nvarchar fields take up twice as much space (so for example in earlier versions of SQL Server the maximum size of an nvarchar field is 4000).

This question is a duplicate of this one.

Converting dictionary to JSON

No need to convert it in a string by using json.dumps()

r = {'is_claimed': 'True', 'rating': 3.5}
file.write(r['is_claimed'])
file.write(str(r['rating']))

You can get the values directly from the dict object.

No assembly found containing an OwinStartupAttribute Error

Check if you have the Startup class created in your project. This is an example:

using Microsoft.Owin;
using Owin;

[assembly: OwinStartupAttribute(typeof({project_name}.Startup))]

namespace AuctionPortal
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
        }
    }
}

How to Validate Google reCaptcha on Form Submit

If you want to check if the User clicked on the I'm not a robot checkbox, you can use the .getResponse() function provided by the reCaptcha API.

It will return an empty string in case the User did not validate himself, something like this:

if (grecaptcha.getResponse() == ""){
    alert("You can't proceed!");
} else {
    alert("Thank you");
}

In case the User has validated himself, the response will be a very long string.

More about the API can be found on this page: reCaptcha Javascript API

Difference between Activity Context and Application Context

This obviously is deficiency of the API design. In the first place, Activity Context and Application context are totally different objects, so the method parameters where context is used should use ApplicationContext or Activity directly, instead of using parent class Context. In the second place, the doc should specify which context to use or not explicitly.

How to debug a Flask app

Install python-dotenv in your virtual environment.

Create a .flaskenv in your project root. By project root, I mean the folder which has your app.py file

Inside this file write the following:

FLASK_APP=myapp 
FLASK_ENV=development

Now issue the following command:

flask run

How to redirect the output of DBMS_OUTPUT.PUT_LINE to a file?

DBMS_OUTPUT is not the best tool to debug, since most environments don't use it natively. If you want to capture the output of DBMS_OUTPUT however, you would simply use the DBMS_OUTPUT.get_line procedure.

Here is a small example:

SQL> create directory tmp as '/tmp/';

Directory created

SQL> CREATE OR REPLACE PROCEDURE write_log AS
  2     l_line VARCHAR2(255);
  3     l_done NUMBER;
  4     l_file utl_file.file_type;
  5  BEGIN
  6     l_file := utl_file.fopen('TMP', 'foo.log', 'A');
  7     LOOP
  8        EXIT WHEN l_done = 1;
  9        dbms_output.get_line(l_line, l_done);
 10        utl_file.put_line(l_file, l_line);
 11     END LOOP;
 12     utl_file.fflush(l_file);
 13     utl_file.fclose(l_file);
 14  END write_log;
 15  /

Procedure created

SQL> BEGIN
  2     dbms_output.enable(100000);
  3     -- write something to DBMS_OUTPUT
  4     dbms_output.put_line('this is a test');
  5     -- write the content of the buffer to a file
  6     write_log;
  7  END;
  8  /

PL/SQL procedure successfully completed

SQL> host cat /tmp/foo.log

this is a test

How to move a git repository into another directory and make that directory a git repository?

To do this without any headache:

  1. Check out what's the current branch in the gitrepo1 with git status, let's say branch "development".
  2. Change directory to the newrepo, then git clone the project from repository.
  3. Switch branch in newrepo to the previous one: git checkout development.
  4. Syncronize newrepo with the older one, gitrepo1 using rsync, excluding .git folder: rsync -azv --exclude '.git' gitrepo1 newrepo/gitrepo1. You don't have to do this with rsync of course, but it does it so smooth.

The benefit of this approach: you are good to continue exactly where you left off: your older branch, unstaged changes, etc.

Deck of cards JAVA

There are many errors in your code, for example you are not really calling your deck by just typing deck in your Shuffle method. You can only call it by typing theCard.deck

I have changed your shuffle method:

public void Shuffle(){
    for (int i = 0; i < theCard.deck.length; i++) {
        int index = (int)(Math.random()*theCard.deck.length );
        int temp = theCard.deck[i];
        theCard.deck[i] = theCard.deck[index];
        theCard.deck[index] = temp;
        remainingCards--;
    }
}

Also, as it is said you have structural problem. You should name classes as you understand in real life, for example, when you say card, it is only one card, when you say deck it is supposed to be 52+2 cards. In this way your code would be more understandable.

Save classifier to disk in scikit-learn

Classifiers are just objects that can be pickled and dumped like any other. To continue your example:

import cPickle
# save the classifier
with open('my_dumped_classifier.pkl', 'wb') as fid:
    cPickle.dump(gnb, fid)    

# load it again
with open('my_dumped_classifier.pkl', 'rb') as fid:
    gnb_loaded = cPickle.load(fid)

Edit: if you are using a sklearn Pipeline in which you have custom transformers that cannot be serialized by pickle (nor by joblib), then using Neuraxle's custom ML Pipeline saving is a solution where you can define your own custom step savers on a per-step basis. The savers are called for each step if defined upon saving, and otherwise joblib is used as default for steps without a saver.

How can I make a countdown with NSTimer?

Swift 5 another way. Resistant to interaction with UI

I would like to show a solution that is resistant to user interaction with other UI elements during countdown. In the comments I explained what each line of code means.

 var timeToSet = 0
 var timer: Timer?

 ...

 @IBAction func btnWasPressed(_ sender: UIButton) {

      //Setting the countdown time
      timeLeft = timeToSet
      //Disabling any previous timers.
      timer?.invalidate()
      //Initialization of the Timer with interval every 1 second with the function call.
      timer = Timer(timeInterval: 1.0, target: self, selector: #selector(countDown), userInfo: nil, repeats: true)
      //Adding Timer to the current loop
      RunLoop.current.add(timer!, forMode: .common)

  }

 ...

 @objc func countDown() {

     if timeLeft > 0 {
         print(timeLeft)
         timeLeft -= 1
     } else {
         // Timer stopping
         timer?.invalidate()
     }
 }

Xcode warning: "Multiple build commands for output file"

The key was to do pod deintegrate and rm *.workspace file ! What a waste of time !

iOS - Build fails with CocoaPods cannot find header files

For me, what fixed it was the iOS deployment target for my Pods project was lower than my project itself. Once I made it the same as my project it was able to find the header file.

jQuery detect if string contains something

You get the value of the textarea, use it :

$('.type').keyup(function() {
    var v = $('.type').val(); // you'd better use this.value here
    if (v.indexOf('> <')!=-1) {
       console.log('contains > <');        
    }
});

Get Element value with minidom with Python

Probably something like this if it's the text part you want...

from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')

print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE)

The text part of a node is considered a node in itself placed as a child-node of the one you asked for. Thus you will want to go through all its children and find all child nodes that are text nodes. A node can have several text nodes; eg.

<name>
  blabla
  <somestuff>asdf</somestuff>
  znylpx
</name>

You want both 'blabla' and 'znylpx'; hence the " ".join(). You might want to replace the space with a newline or so, or perhaps by nothing.

"Parameter not valid" exception loading System.Drawing.Image

all the solutions given doesnt work.. dont concentrate only on the retrieving part. luk at the inserting of the image. i did the same mistake. I tuk an image from hard disk and saved it to database. The problem lies in the insert command. luk at my fault code..:

 public bool convertImage()
    {
        try
        {
            MemoryStream ms = new MemoryStream();
            pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
            photo = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(photo, 0, photo.Length);
            return true;
        }
        catch
        {
            MessageBox.Show("image can not be converted");
            return false;
        }
    }
    public void insertImage()
    {
       // SqlConnection con = new SqlConnection();
        try
        {
            cs.Close();
            cs.Open();
            da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = " +photo+" WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
            da.UpdateCommand.ExecuteNonQuery();
            cs.Close();
            cs.Open();
            int i = da.UpdateCommand.ExecuteNonQuery();
            if (i > 0)
            {
                MessageBox.Show("Successfully Inserted...");
            }

        }
        catch
        {
            MessageBox.Show("Error in Connection");
        }
        cs.Close();
    }

The above code shows succesfully inserted... but actualy its saving the image in the form of wrong datatype.. whereas the datatype must bt "image".. so i improved the code..

  public bool convertImage()
    {
        try
        {
            MemoryStream ms = new MemoryStream();
            pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
            photo = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(photo, 0, photo.Length);
            return true;
        }
        catch
        {
            MessageBox.Show("image can not be converted");
            return false;
        }
    }
    public void insertImage()
    {
       // SqlConnection con = new SqlConnection();
        try
        {
            cs.Close();
            cs.Open();
            //THIS WHERE THE CODE MUST BE CHANGED>>>>>>>>>>>>>>

            da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = @img WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
            da.UpdateCommand.Parameters.Add("@img", SqlDbType.Image);//CHANGED TO IMAGE DATATYPE...
            da.UpdateCommand.Parameters["@img"].Value = photo;
            da.UpdateCommand.ExecuteNonQuery();
            cs.Close();
            cs.Open();
            int i = da.UpdateCommand.ExecuteNonQuery();
            if (i > 0)
            {
                MessageBox.Show("Successfully Inserted...");
            }

        }
        catch
        {
            MessageBox.Show("Error in Connection");
        }
        cs.Close();
    }

100% gurantee that there will be no PARAMETER NOT VALID error in retrieving....SOLVED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

PHP date add 5 year to current date

Try with:

$end = date('Y-m-d', strtotime('+5 years'));

What are the ways to make an html link open a folder

Hope it will help someone someday. I was making a small POC and came across this. A button, onClick display contents of the folder. Below is the HTML,

<input type=button onClick="parent.location='file:///C:/Users/' " value='Users'>

What's the "Content-Length" field in HTTP header?

It's the number of bytes of data in the body of the request or response. The body is the part that comes after the blank line below the headers.

Could not find default endpoint element

Allow me to add one more thing to look for. (Tom Haigh's answer already alludes to it, but I want to be explicit)

My web.config file had the following defined:

<protocolMapping>
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>

I was already using basicHttpsBinding for one reference, but then I added a new reference which required basicHttpBinding (no s). All I had to do was add that to my protocolMapping as follows:

<protocolMapping>
    <add binding="basicHttpBinding" scheme="http" />
    <add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>

As L.R. correctly points out, this needs to be defined in the right places. For me, that meant one in my Unit Test project's app.config as well as one in the main service project's web.config.

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

In android studio you may see the following folder drawable xhdpi, drawable-hdpi, drawable-mdpi and more... You can put images of different dpi in these folder accordingly and android will take care which images should be draw according to the screen density of device.

NOTE: You have to put the images with the same name.

Passing variables in remote ssh command

As answered previously, you do not need to set the environment variable on the remote host. Instead, you can simply do the meta-expansion on the local host, and pass the value to the remote host.

ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'

If you really want to set the environment variable on the remote host and use it, you can use the env program

ssh [email protected] "env BUILD_NUMBER=$BUILD_NUMBER ~/tools/run_pvt.pl \$BUILD_NUMBER"

In this case this is a bit of an overkill, and note

  • env BUILD_NUMBER=$BUILD_NUMBER does the meta expansion on the local host
  • the remote BUILD_NUMBER environment variable will be used by
    the remote shell

What does "#pragma comment" mean?

I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.

Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.

Pragma Directives It includes "#pragma comment" in the table you'll see.

HTH

I suspect GCC, for example, has their own set of #pragma's.

How to add button in ActionBar(Android)?

you have to create an entry inside res/menu,override onCreateOptionsMenu and inflate it

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.yourentry, menu);
    return true;
}

an entry for the menu could be:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_cart"
        android:icon="@drawable/cart"
        android:orderInCategory="100"
        android:showAsAction="always"/> 
</menu>

Maven: How to change path to target directory from command line?

You should use profiles.

<profiles>
    <profile>
        <id>otherOutputDir</id>
        <build>
            <directory>yourDirectory</directory>
        </build>
    </profile>
</profiles>

And start maven with your profile

mvn compile -PotherOutputDir

If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :

<properties>
    <buildDirectory>${project.basedir}/target</buildDirectory>
</properties>

<build>
    <directory>${buildDirectory}</directory>
</build>

And compile like this :

mvn compile -DbuildDirectory=test

That's because you can't change the target directory by using -Dproject.build.directory

Combine Regexp?

If a string must not contain @, every character must be another character than @:

/^[^@]*$/

This will match any string of any length that does not contain @.

Another possible solution would be to invert the boolean result of /@/.

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

I used to meet the similar problem because 'localhost' was not available on server when it restarted network service, e.g. 'ifdown -a' but followed by only 'ifup -eo1'. Besides server is not listening to the port, you can also check 'localhost' is available or not.

ps: Post it just hope someone who has the similar problem may benefit.

Fix CSS hover on iPhone/iPad/iPod

Here is a very slight improvement to user1387483's answer using an immediate function:

(function() {
  $("*").on( 'touchstart', function() {
    $(this).trigger('hover') ;
  } ).on('touchend', function() {
    $(this).trigger('hover') ;
  } ) ;
})() ;

Also, I agree with Boz that this appears to be the "neatest, most compliant solution".

How to programmatically send a 404 response with Express/Node?

IMO the nicest way is to use the next() function:

router.get('/', function(req, res, next) {
    var err = new Error('Not found');
    err.status = 404;
    return next(err);
}

Then the error is handled by your error handler and you can style the error nicely using HTML.

Change default text in input type="file"?

You can use this approach, it works even if a lot of files inputs.

_x000D_
_x000D_
const fileBlocks = document.querySelectorAll('.file-block')_x000D_
const buttons = document.querySelectorAll('.btn-select-file')_x000D_
_x000D_
;[...buttons].forEach(function (btn) {_x000D_
  btn.onclick = function () {_x000D_
    btn.parentElement.querySelector('input[type="file"]').click()_x000D_
  }_x000D_
})_x000D_
_x000D_
;[...fileBlocks].forEach(function (block) {_x000D_
  block.querySelector('input[type="file"]').onchange = function () {_x000D_
    const filename = this.files[0].name_x000D_
_x000D_
    block.querySelector('.btn-select-file').textContent = 'File selected: ' + filename_x000D_
  }_x000D_
})
_x000D_
.btn-select-file {_x000D_
  border-radius: 20px;_x000D_
}_x000D_
_x000D_
input[type="file"] {_x000D_
  display: none;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="file-block">_x000D_
  <button class="btn-select-file">Select Image 1</button>_x000D_
  <input type="file">_x000D_
</div>_x000D_
<br>_x000D_
<div class="file-block">_x000D_
  <button class="btn-select-file">Select Image 2</button>_x000D_
  <input type="file">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Basic Python client socket example

Here is the simplest python socket example.

Server side:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break

Client Side:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')
  • First run the SocketServer.py, and make sure the server is ready to listen/receive sth
  • Then the client send info to the server;
  • After the server received sth, it terminates

Android Studio Image Asset Launcher Icon Background Color

First, create a launcher icon (Adaptive and Legacy) from Image Asset:

Select an image for background layer and resize it to 0% or 1% and In legacy tab set shape to none.

Then, delete folder res/mipmap/ic_laucher_round in the project window and Open AndroidManifest.xml and remove attribute android:roundIcon="@mipmap/ic_launcher_round" from the application element.

In the end, delete ic_launcher.xml from mipmap-anydpi-v26.

Notice that: Some devices like Nexus 5X (Android 8.1) adding a white background automatically and can't do anything.

Merge PDF files

Use Pypdf or its successor PyPDF2:

A Pure-Python library built as a PDF toolkit. It is capable of:
* splitting documents page by page,
* merging documents page by page,

(and much more)

Here's a sample program that works with both versions.

#!/usr/bin/env python
import sys
try:
    from PyPDF2 import PdfFileReader, PdfFileWriter
except ImportError:
    from pyPdf import PdfFileReader, PdfFileWriter

def pdf_cat(input_files, output_stream):
    input_streams = []
    try:
        # First open all the files, then produce the output file, and
        # finally close the input files. This is necessary because
        # the data isn't read from the input files until the write
        # operation. Thanks to
        # https://stackoverflow.com/questions/6773631/problem-with-closing-python-pypdf-writing-getting-a-valueerror-i-o-operation/6773733#6773733
        for input_file in input_files:
            input_streams.append(open(input_file, 'rb'))
        writer = PdfFileWriter()
        for reader in map(PdfFileReader, input_streams):
            for n in range(reader.getNumPages()):
                writer.addPage(reader.getPage(n))
        writer.write(output_stream)
    finally:
        for f in input_streams:
            f.close()

if __name__ == '__main__':
    if sys.platform == "win32":
        import os, msvcrt
        msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    pdf_cat(sys.argv[1:], sys.stdout)

In Powershell what is the idiomatic way of converting a string to an int?

I'd probably do something like that :

[int]::Parse("35")

But I'm not really a Powershell guy. It uses the static Parse method from System.Int32. It should throw an exception if the string can't be parsed.

installing requests module in python 2.7 windows

If you want to install requests directly you can use the "-m" (module) option available to python.

python.exe -m pip install requests

You can do this directly in PowerShell, though you may need to use the full python path (eg. C:\Python27\python.exe) instead of just python.exe.

As mentioned in the comments, if you have added Python to your path you can simply do:

python -m pip install requests

Rails raw SQL example

I know this is old... But I was having the same problem today and found a solution:

Model.find_by_sql

If you want to instantiate the results:

Client.find_by_sql("
  SELECT * FROM clients
  INNER JOIN orders ON clients.id = orders.client_id
  ORDER BY clients.created_at desc
")
# => [<Client id: 1, first_name: "Lucas" >, <Client id: 2, first_name: "Jan">...]

Model.connection.select_all('sql').to_hash

If you just want a hash of values:

Client.connection.select_all("SELECT first_name, created_at FROM clients
   WHERE id = '1'").to_hash
# => [
  {"first_name"=>"Rafael", "created_at"=>"2012-11-10 23:23:45.281189"},
  {"first_name"=>"Eileen", "created_at"=>"2013-12-09 11:22:35.221282"}
]

Result object:

select_all returns a result object. You can do magic things with it.

result = Post.connection.select_all('SELECT id, title, body FROM posts')
# Get the column names of the result:
result.columns
# => ["id", "title", "body"]

# Get the record values of the result:
result.rows
# => [[1, "title_1", "body_1"],
      [2, "title_2", "body_2"],
      ...
     ]

# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
      {"id" => 2, "title" => "title_2", "body" => "body_2"},
      ...
     ]

# ActiveRecord::Result also includes Enumerable.
result.each do |row|
  puts row['title'] + " " + row['body']
end

Sources:

  1. ActiveRecord - Findinig by SQL.
  2. Ruby on Rails - Active Record Result .

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

I faced a similar (but not identical) issue.

I had to go to to Turn Windows features on or off in Control Panel and add ASP.NET 3.5 and 4.7: enter image description here

Then it worked for me.

pros and cons between os.path.exists vs os.path.isdir

os.path.exists will also return True if there's a regular file with that name.

os.path.isdir will only return True if that path exists and is a directory, or a symbolic link to a directory.

Get the row(s) which have the max value in groups using groupby

You can sort the dataFrame by count and then remove duplicates. I think it's easier:

df.sort_values('count', ascending=False).drop_duplicates(['Sp','Mt'])

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

PowerShell Alternative

This is an old post and I read through the answers. Still, I found it a bit too painful to output multi-line large text fields unaltered from SSMS. I ended up writing a small C# program for my needs, but got to thinking it could probably be done using the command line. Turns out, it is fairly easy to do so with PowerShell.

Start by installing the SqlServer module from an administrative PowerShell.

Install-Module -Name SqlServer

Use Invoke-Sqlcmd to run your query:

$Rows = Invoke-Sqlcmd -Query "select BigColumn from SomeTable where Id = 123" `
    -As DataRows -MaxCharLength 1000000 -ConnectionString $ConnectionString

This will return an array of rows that you can output to the console as follows:

$Rows[0].BigColumn

Or output to a file as follows:

$Rows[0].BigColumn | Out-File -FilePath .\output.txt -Encoding UTF8

The result is a beautiful un-truncated text written to a file for viewing/editing. I am sure there is a similar command to save back the text to SQL Server, although that seems like a different question.

EDIT: It turns out that there was an answer by @dvlsc that described this approach as a secondary solution. I think because it was listed as a secondary answer, is the reason I missed it in the first place. I am going to leave my answer which focuses on the PowerShell approach, but wanted to at least give credit where it was due.

Carousel with Thumbnails in Bootstrap 3.0

@Skelly 's answer is correct. It won't let me add a comment (<50 rep)... but to answer your question on his answer: In the example he linked, if you add

col-xs-3 

class to each of the thumbnails, like this:

class="col-md-3 col-xs-3"

then it should stay the way you want it when sized down to phone width.

MySQL - force not to use cache for testing speed of query

Whilst some of the answers are good, there is a major caveat.

The mysql queries may be prevented from being cached, but it won't prevent your underlying O.S caching disk accesses into memory. This can be a major slowdown for some queries especially if they need to pull data from spinning disks.

So whilst it's good to use the methods above, I would also try and test with a different set of data/range each time, that's likely not been pulled from disk into disk/memory cache.

Sequelize OR condition object

Use Sequelize.or:

var condition = {
  where: Sequelize.and(
    { name: 'a project' },
    Sequelize.or(
      { id: [1,2,3] },
      { id: { lt: 10 } }
    )
  )
};

Reference (search for Sequelize.or)

Edit: Also, this has been modified and for the latest method see Morio's answer,

Learning Regular Expressions

The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.

If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.

Start simple

Conceptually, the simplest regular expressions are literal characters. The pattern N matches the character 'N'.

Regular expressions next to each other match sequences. For example, the pattern Nick matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.

If you've ever used grep on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re in grep refers to regular expressions.)

Order from the menu

Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c] matches either 'a' or 'b' or 'c'.

The pattern . is special: rather than matching a literal dot only, it matches any character†. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...].

Think of character classes as menus: pick just one.

Helpful shortcuts

Using . can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]. Digits are a frequent match target, so you could instead use the shortcut \d. Others are \s (whitespace) and \w (word characters: alphanumerics or underscore).

The uppercased variants are their complements, so \S matches any non-whitespace character, for example.

Once is not enough

From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c matches 'abc' or 'ac' because the ? quantifier makes the subpattern it modifies optional. Other quantifiers are

  • * (zero or more times)
  • + (one or more times)
  • {n} (exactly n times)
  • {n,} (at least n times)
  • {n,m} (at least n times but no more than m times)

Putting some of these blocks together, the pattern [Nn]*ick matches all of

  • ick
  • Nick
  • nick
  • Nnick
  • nNick
  • nnick
  • (and so on)

The first match demonstrates an important lesson: * always succeeds! Any pattern can match zero times.

A few other useful examples:

  • [0-9]+ (and its equivalent \d+) matches any non-negative integer
  • \d{4}-\d{2}-\d{2} matches dates formatted like 2019-01-01

Grouping

A quantifier modifies the pattern to its immediate left. You might expect 0abc+0 to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c. This means 0abc+0 matches '0abc0', '0abcc0', '0abccc0', and so on.

To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr.

Alternation

Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |, e.g., (Nick|nick).

For another example, you could equivalently write [a-c] as a|b|c, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.

Escaping

Although some characters match themselves, others have special meanings. The pattern \d+ doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+. A backslash removes the special meaning from the following character.

Greediness

Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.

For example, say the input is

"Hello," she said, "How are you?"

You might expect ".+" to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.

To switch from greedy to what you might think of as cautious, add an extra ? to the quantifier. Now you understand how \((.+?)\), the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.

If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.

(As to your confusion, I don't know of any regular-expression dialect where ((.+?)) would do the same thing. I suspect something got lost in transmission somewhere along the way.)

Anchors

Use the special pattern ^ to match only at the beginning of your input and $ to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.

Say you want to match comments of the form

-- This is a comment --

you'd write ^--\s+(.+)\s+--$.

Build your own

Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.

Tools for writing and debugging regexes:

Books

Free resources

Footnote

†: The statement above that . matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n", but in practice you rarely expect a pattern such as .+ to cross a newline boundary. Perl regexes have a /s switch and Java Pattern.DOTALL, for example, to make . match any character at all. For languages that don't have such a feature, you can use something like [\s\S] to match "any whitespace or any non-whitespace", in other words anything.

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

How to convert a plain object into an ES6 Map?

The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:

Converting an Object to a Map

The new Map() constructor accepts an iterable of entries. With Object.entries, you can easily convert from Object to Map:

const obj = { foo: 'bar', baz: 42 }; 
const map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baz: 42 }

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

Well this is because ArrayList resulting from Arrays.asList() is not of the type java.util.ArrayList . Arrays.asList() creates an ArrayList of type java.util.Arrays$ArrayList which does not extend java.util.ArrayList but only extends java.util.AbstractList

Word wrapping in phpstorm

You have to enable Soft Wraps. Find that option through this path.

View > Active Editor > Use Soft Wraps

wrap words in PhpStorm

Declare multiple module.exports in Node.js

If the files are written using ES6 export, you can write:

module.exports = {
  ...require('./foo'),
  ...require('./bar'),
};

Materialize CSS - Select Doesn't Seem to Render

Only this worked for me:

$(document).ready(function(){
    $('select').not('.disabled').formSelect();
});

Is there a 'box-shadow-color' property?

Maybe this is new (I am also pretty crap at css3), but I have a page that uses exactly what you suggest:

-moz-box-shadow: 10px 10px 5px #384e69;
-webkit-box-shadow: 10px 10px 5px #384e69;
box-shadow: 10px 10px 5px #384e69;}

.. and it works fine for me (in Chrome at least).

GROUP_CONCAT ORDER BY

Try

SELECT li.clientid, group_concat(li.views ORDER BY li.views) AS views,
       group_concat(li.percentage ORDER BY li.percentage) 
FROM table_views li 
GROUP BY client_id

http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function%5Fgroup-concat

jQuery selector for id starts with specific text

Add a common class to all the div. For example add foo to all the divs.

$('.foo').each(function () {
   $(this).dialog({
    autoOpen: false,
    show: {
      effect: "blind",
      duration: 1000
    },
    hide: {
      effect: "explode",
      duration: 1000
    }
  });
});

python mpl_toolkits installation issue

It is not on PyPI and you should not be installing it via pip. If you have matplotlib installed, you should be able to import mpl_toolkits directly:

$ pip install --upgrade matplotlib
...

$ python
>>> import mpl_toolkits
>>> 

Differences between .NET 4.0 and .NET 4.5 in High level in .NET

Here is a great resource from Microsoft which includes a high level features overview for each .NET release since 1.0 up to the present day. It also include information about the associated Visual Studio release and Windows version compatibility.

.NET Framework Versions and Dependencies

Regex to match only uppercase "words" with some exceptions

For the first case you propose you can use: '[[:blank:]]+[A-Z0-9]+[[:blank:]]+', for example:

echo "The thing P1 must connect to the J236 thing in the Foo position" | grep -oE '[[:blank:]]+[A-Z0-9]+[[:blank:]]+'

In the second case maybe you need to use something else and not a regex, maybe a script with a dictionary of technical words...

Cheers, Fernando

How do I run a VBScript in 32-bit mode on a 64-bit machine?

In the launcher script you can force it, it permits to keep the same script and same launcher for both architecture

:: For 32 bits architecture, this line is sufficent (32bits is the only cscript available)
set CSCRIPT="cscript.exe"
:: Detect windows 64bits and use the expected cscript (SysWOW64 contains 32bits executable)
if exist "C:\Windows\SysWOW64\cscript.exe" set CSCRIPT="C:\Windows\SysWOW64\cscript.exe"
%CSCRIPT% yourscript.vbs

Transform char array into String

Three years later, I ran into the same problem. Here's my solution, everybody feel free to cut-n-paste. The simplest things keep us up all night! Running on an ATMega, and Adafruit Feather M0:

void setup() {
  // turn on Serial so we can see...
  Serial.begin(9600);

  // the culprit:
  uint8_t my_str[6];    // an array big enough for a 5 character string

  // give it something so we can see what it's doing
  my_str[0] = 'H';
  my_str[1] = 'e';
  my_str[2] = 'l';
  my_str[3] = 'l';
  my_str[4] = 'o';
  my_str[5] = 0;  // be sure to set the null terminator!!!

  // can we see it?
  Serial.println((char*)my_str);

  // can we do logical operations with it as-is?
  Serial.println((char*)my_str == 'Hello');

  // okay, it can't; wrong data type (and no terminator!), so let's do this:
  String str((char*)my_str);

  // can we see it now?
  Serial.println(str);

  // make comparisons
  Serial.println(str == 'Hello');

  // one more time just because
  Serial.println(str == "Hello");

  // one last thing...!
  Serial.println(sizeof(str));
}

void loop() {
  // nothing
}

And we get:

Hello    // as expected
0        // no surprise; wrong data type and no terminator in comparison value
Hello    // also, as expected
1        // YAY!
1        // YAY!
6        // as expected

Hope this helps someone!

laravel Eloquent ORM delete() method

Before delete , there are several methods in laravel.

User::find(1) and User::first() return an instance.

User::where('id',1)->get and User::all() return a collection of instance.

call delete on an model instance will returns true/false

$user=User::find(1);
$user->delete(); //returns true/false

call delete on a collection of instance will returns a number which represents the number of the records had been deleted

//assume you have 10 users, id from 1 to 10;
$result=User::where('id','<',11)->delete(); //returns 11 (the number of the records had been deleted)

//lets call delete again
$result2=User::where('id','<',11)->delete(); //returns 0 (we have already delete the id<11 users, so this time we delete nothing, the result should be the number of the records had been deleted(0)  ) 

Also there are other delete methods, you can call destroy as a model static method like below

$result=User::destroy(1,2,3);
$result=User::destroy([1,2,3]);
$result=User::destroy(collect([1, 2, 3]));
//these 3 statement do the same thing, delete id =1,2,3 users, returns the number of the records had been deleted

One more thing ,if you are new to laravel ,you can use php artisan tinker to see the result, which is more efficient and then dd($result) , print_r($result);

Python datetime strptime() and strftime(): how to preserve the timezone information

Unfortunately, strptime() can only handle the timezone configured by your OS, and then only as a time offset, really. From the documentation:

Support for the %Z directive is based on the values contained in tzname and whether daylight is true. Because of this, it is platform-specific except for recognizing UTC and GMT which are always known (and are considered to be non-daylight savings timezones).

strftime() doesn't officially support %z.

You are stuck with python-dateutil to support timezone parsing, I am afraid.

Swift Beta performance: sorting arrays

func partition(inout list : [Int], low: Int, high : Int) -> Int {
    let pivot = list[high]
    var j = low
    var i = j - 1
    while j < high {
        if list[j] <= pivot{
            i += 1
            (list[i], list[j]) = (list[j], list[i])
        }
        j += 1
    }
    (list[i+1], list[high]) = (list[high], list[i+1])
    return i+1
}

func quikcSort(inout list : [Int] , low : Int , high : Int) {

    if low < high {
        let pIndex = partition(&list, low: low, high: high)
        quikcSort(&list, low: low, high: pIndex-1)
        quikcSort(&list, low: pIndex + 1, high: high)
    }
}

var list = [7,3,15,10,0,8,2,4]
quikcSort(&list, low: 0, high: list.count-1)

var list2 = [ 10, 0, 3, 9, 2, 14, 26, 27, 1, 5, 8, -1, 8 ]
quikcSort(&list2, low: 0, high: list2.count-1)

var list3 = [1,3,9,8,2,7,5]
quikcSort(&list3, low: 0, high: list3.count-1) 

This is my Blog about Quick Sort- Github sample Quick-Sort

You can take a look at Lomuto's partitioning algorithm in Partitioning the list. Written in Swift.

Angular: date filter adds timezone, how to output UTC?

Since version 1.3.0 AngularJS introduced extra filter parameter timezone, like following:

{{ date_expression | date : format : timezone}}

But in versions 1.3.x only supported timezone is UTC, which can be used as following:

{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}

Since version 1.4.0-rc.0 AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):

{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}

Here you can find documentation of AngularJS date filters.

NOTE: this is working only with Angular 1.x

Here's working example

Determine if variable is defined in Python

I think it's better to avoid the situation. It's cleaner and clearer to write:

a = None
if condition:
    a = 42

APR based Apache Tomcat Native library was not found on the java.library.path?

I resolve this (On Eclipse IDE) by delete my old server and create the same again. This error is because you don't proper terminate Tomcat server and close Eclipse.

How can I scan barcodes on iOS?

with Swift 5 it's Simple and Super fast!!

You just need to add cocoa pods "BarcodeScanner" here is the full code

source 'https://github.com/CocoaPods/Specs.git' 
platform :ios, '12.0' 
target 'Simple BarcodeScanner' 
do   
pod 'BarcodeScanner' 
end

Make sure add Camera permission in your .plist file

<key>NSCameraUsageDescription</key>
<string>Camera usage description</string>

And add Scanner and handle result in your ViewController this way

import UIKit
import BarcodeScanner

class ViewController: UIViewController, BarcodeScannerCodeDelegate, BarcodeScannerErrorDelegate, BarcodeScannerDismissalDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let viewController = BarcodeScannerViewController()
        viewController.codeDelegate = self
        viewController.errorDelegate = self
        viewController.dismissalDelegate = self

        present(viewController, animated: true, completion: nil)
    }

    func scanner(_ controller: BarcodeScannerViewController, didCaptureCode code: String, type: String) {
        print("Product's Bar code is :", code)
        controller.dismiss(animated: true, completion: nil)
    }

    func scanner(_ controller: BarcodeScannerViewController, didReceiveError error: Error) {
        print(error)
    }

    func scannerDidDismiss(_ controller: BarcodeScannerViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
}

Still and any question or challenges, please check sample application here with full source code

Showing which files have changed between two revisions

Note that git makes it easy to just try out the merge and back away from any problems if you don't like the result. It might be easier than looking for potential problems in advance.

How to create timer in angular2

Set Timer and auto call service after certain time
// Initialize from ngInit
ngOnInit(): void {this.getNotifications();}

getNotifications() {
    setInterval(() => {this.getNewNotifications();
    }, 60000);  // 60000 milliseconds interval 
}
getNewNotifications() {
    this.notifyService.getNewNotifications().subscribe(
        data => { // call back },
        error => { },
    );
}

Find records from one table which don't exist in another

Alternatively,

select id from call
minus
select id from phone_number

Populating a database in a Laravel migration file

Don't put the DB::insert() inside of the Schema::create(), because the create method has to finish making the table before you can insert stuff. Try this instead:

public function up()
{
    // Create the table
    Schema::create('users', function($table){
        $table->increments('id');
        $table->string('email', 255);
        $table->string('password', 64);
        $table->boolean('verified');
        $table->string('token', 255);
        $table->timestamps();
    });

    // Insert some stuff
    DB::table('users')->insert(
        array(
            'email' => '[email protected]',
            'verified' => true
        )
    );
}

How to restart remote MySQL server running on Ubuntu linux?

sudo service mysql stop;
sudo service mysql start;

If the above process will not work let's check one the given code above you can stop Mysql server and again start server

TypeError: $(...).DataTable is not a function

if some reason two versions of jQuery are loaded (which is not recommended), calling $.noConflict(true) from the second version will return the globally scoped jQuery variables to those of the first version.

Sometimes it could be issue with older version (or not stable) of JQuery files

Solution use $.noConflict();

<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.js" type="text/javascript"></script>
<script>
$.noConflict();
jQuery( document ).ready(function( $ ) {
    $('#myTable').DataTable();
});
// Code that uses other library's $ can follow here.
</script>

How to capitalize first letter of each word, like a 2-word city?

The JavaScript function:

String.prototype.capitalize = function(){
       return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
      };

To use this function:

capitalizedString = someString.toLowerCase().capitalize();

Also, this would work on multiple words string.

To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddle example and compare the alert message vs the styled output.

Python - How to convert JSON File to Dataframe

There are 2 inputs you might have and you can also convert between them.

  1. input: listOfDictionaries --> use @VikashSingh solution

example: [{"":{"...

The pd.DataFrame() needs a listOfDictionaries as input.

  1. input: jsonStr --> use @JustinMalinchak solution

example: '{"":{"...

If you have jsonStr, you need an extra step to listOfDictionaries first. This is obvious as it is generated like:

jsonStr = json.dumps(listOfDictionaries)

Thus, switch back from jsonStr to listOfDictionaries first:

listOfDictionaries = json.loads(jsonStr)

Initialize array of strings

This example program illustrates initialization of an array of C strings.

#include <stdio.h>

const char * array[] = {
    "First entry",
    "Second entry",
    "Third entry",
};

#define n_array (sizeof (array) / sizeof (const char *))

int main ()
{
    int i;

    for (i = 0; i < n_array; i++) {
        printf ("%d: %s\n", i, array[i]);
    }
    return 0;
}

It prints out the following:

0: First entry
1: Second entry
2: Third entry

mongoError: Topology was destroyed

In my case, this error was caused by an identical server instance already running background.

The weird thing is when I started my server without notice there's one running already, the console didn't show anything like 'something is using port xxx'. I could even upload something to the server. So, it took me quite long to locate this problem.

What's more, after closing all the applications I can imagine, I still could not find the process which is using this port in my Mac's activity monitor. I have to use lsof to trace. The culprit was not surprising - it's a node process. However, with the PID shown in the terminal, I found the port number in the monitor is different from the one used by my server.

All in all, kill all the node processes may solve this problem directly.

How to check the presence of php and apache on ubuntu server through ssh

You could inspect the available apache2 modules:

$ ls /usr/lib/apache2/modules/

Or try to enable the php module, if you have the appropriate access:

$ a2enmod
Which module would you like to enable?
Your choices are: actions alias asis ...
... php5 proxy_ajp proxy_balancer proxy_connect ..

Add Variables to Tuple

In Python 3, you can use * to create a new tuple of elements from the original tuple along with the new element.

>>> tuple1 = ("foo", "bar")
>>> tuple2 = (*tuple1, "baz")
>>> tuple2
('foo', 'bar', 'baz')

The byte code is almost the same as tuple1 + ("baz",)

Python 3.7.5 (default, Oct 22 2019, 10:35:10) 
[Clang 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def f():
...     tuple1 = ("foo", "bar")
...     tuple2 = (*tuple1, "baz")
...     return tuple2
... 
>>> def g():
...     tuple1 = ("foo", "bar")
...     tuple2 = tuple1 + ("baz",)
...     return tuple2
... 
>>> from dis import dis
>>> dis(f)
  2           0 LOAD_CONST               1 (('foo', 'bar'))
              2 STORE_FAST               0 (tuple1)

  3           4 LOAD_FAST                0 (tuple1)
              6 LOAD_CONST               3 (('baz',))
              8 BUILD_TUPLE_UNPACK       2
             10 STORE_FAST               1 (tuple2)

  4          12 LOAD_FAST                1 (tuple2)
             14 RETURN_VALUE
>>> dis(g)
  2           0 LOAD_CONST               1 (('foo', 'bar'))
              2 STORE_FAST               0 (tuple1)

  3           4 LOAD_FAST                0 (tuple1)
              6 LOAD_CONST               2 (('baz',))
              8 BINARY_ADD
             10 STORE_FAST               1 (tuple2)

  4          12 LOAD_FAST                1 (tuple2)
             14 RETURN_VALUE

The only difference is BUILD_TUPLE_UNPACK vs BINARY_ADD. The exact performance depends on the Python interpreter implementation, but it's natural to implement BUILD_TUPLE_UNPACK faster than BINARY_ADD because BINARY_ADD is a polymorphic operator, requiring additional type calculation and implicit conversion.

How can I make my layout scroll both horizontally and vertically?

its too late but i hope your issue will be solve quickly with this code. nothing to do more just put your code in below scrollview.

<HorizontalScrollView
        android:id="@+id/scrollView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent">

      <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            //xml code
      </ScrollView>
</HorizontalScrollView>

How to add custom validation to an AngularJS form?

You can use ng-required for your validation scenario ("if these 3 fields are filled in, then this field is required":

<div ng-app>
    <input type="text" ng-model="field1" placeholder="Field1">
    <input type="text" ng-model="field2" placeholder="Field2">
    <input type="text" ng-model="field3" placeholder="Field3">
    <input type="text" ng-model="dependentField" placeholder="Custom validation"
        ng-required="field1 && field2 && field3">
</div>

How can I enable the MySQLi extension in PHP 7?

For all docker users, just run docker-php-ext-install mysqli from inside your php container.

Update: More information on https://hub.docker.com/_/php in the section "How to install more PHP extensions".

How can I select rows with most recent timestamp for each key value?

I had mostly the same problem and ended up a a different solution that makes this type of problem trivial to query.

I have a table of sensor data (1 minute data from about 30 sensors)

SensorReadings->(timestamp,value,idSensor)

and I have a sensor table that has lots of mostly static stuff about the sensor but the relevant fields are these:

Sensors->(idSensor,Description,tvLastUpdate,tvLastValue,...)

The tvLastupdate and tvLastValue are set in a trigger on inserts to the SensorReadings table. I always have direct access to these values without needing to do any expensive queries. This does denormalize slightly. The query is trivial:

SELECT idSensor,Description,tvLastUpdate,tvLastValue 
FROM Sensors

I use this method for data that is queried often. In my case I have a sensor table, and a large event table, that have data coming in at the minute level AND dozens of machines are updating dashboards and graphs with that data. With my data scenario the trigger-and-cache method works well.

UILabel with text of two different colors

Having a UIWebView or more than one UILabel could be considered overkill for this situation.

My suggestion would be to use TTTAttributedLabel which is a drop-in replacement for UILabel that supports NSAttributedString. This means you can very easily apply differents styles to different ranges in a string.

Fixed positioning in Mobile Safari

Our web app requires a fixed header. We are fortunate in that we only have to support the latest browsers, but Safari's behavior in this area caused us a real problem.

The best fix, as others have pointed out, is to write our own scrolling code. However, we can't justify that effort to fix a problem that occurs only on iOS. It makes more sense to hope that Apple may fix this problem, especially since, as QuirksMode suggests, Apple now stands alone in their interpretation of "position:fixed".

http://www.quirksmode.org/blog/archives/2013/12/position_fixed_1.html

What worked for us is to toggle between "position:fixed" and "position:absolute" depending on whether the user has zoomed. This replaces our "floating" header with predictable behavior, which is important for usability. When zoomed, the behavior is not what we want, but the user can easily work around this by reversing the zoom.

// On iOS, "position: fixed;" is not supported when zoomed, so toggle "position: absolute;".
header = document.createElement( "HEADER" );
document.body.appendChild( header );
if( navigator.userAgent.match( /iPad/i ) || navigator.userAgent.match( /iPhone/i )) {
    addEventListener( document.body, function( event ) {
        var zoomLevel = (( Math.abs( window.orientation ) === 90 ) ? screen.height : screen.width ) / window.innerWidth;
        header.style.position = ( zoomLevel > 1 ) ? "absolute" : "fixed";
    });
}

How to emit an event from parent to child?

Using RxJs, you can declare a Subject in your parent component and pass it as Observable to child component, child component just need to subscribe to this Observable.

Parent-Component

eventsSubject: Subject<void> = new Subject<void>();

emitEventToChild() {
  this.eventsSubject.next();
}

Parent-HTML

<child [events]="eventsSubject.asObservable()"> </child>    

Child-Component

private eventsSubscription: Subscription;

@Input() events: Observable<void>;

ngOnInit(){
  this.eventsSubscription = this.events.subscribe(() => doSomething());
}

ngOnDestroy() {
  this.eventsSubscription.unsubscribe();
}

How do you return the column names of a table?

Not sure if there is an easier way in 2008 version.

USE [Database Name]
SELECT COLUMN_NAME,* 
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'YourTableName' AND TABLE_SCHEMA='YourSchemaName'

What does the @ symbol before a variable name mean in C#?

The @ symbol allows you to use reserved word. For example:

int @class = 15;

The above works, when the below wouldn't:

int class = 15;

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

Fastest way to determine if record exists

Nothing can beat -

SELECT TOP 1 1 FROM products WHERE id = 'some value';

You don't need to count to know if there is a data in table. And don't use alias when not necessary.

How to run Conda?

Edit ~/.bash_profile, add this to it.

PATH=$PATH:$HOME/anaconda/bin

then run

source ~/.bash_profile

Hope can help you.

Catching access violation exceptions?

A violation like that means that there's something seriously wrong with the code, and it's unreliable. I can see that a program might want to try to save the user's data in a way that one hopes won't write over previous data, in the hope that the user's data isn't already corrupted, but there is by definition no standard method of dealing with undefined behavior.

How do I get some variable from another class in Java?

You never call varsObject.setNum();

On npm install: Unhandled rejection Error: EACCES: permission denied

This one works for me:

sudo chown -R $(whoami) ~/.npm

I did not use the -g because I am the only user. I used a MacBook Air.

Zabbix server is not running: the information displayed may not be current

i had similar problem and my gui reported problem with cache, i change it zabbix-server.conf to 32M and now is ok, zabbix is an intelligent tool, please if it possible check problems in gui first. I had to much hosts ... for default cache.

(unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape

You can just put r in front of the string with your actual path, which denotes a raw string. For example:

data = open(r"C:\Users\miche\Documents\school\jaar2\MIK\2.6\vektis_agb_zorgverlener")

Insertion Sort vs. Selection Sort

The choice of these 2 sorting algorithms comes down to the data structure used.

When you are using arrays, use selection sort (although why, when you can use qsort?). When you are using linked lists, use insertion sort.

This is because:

  • Linked list traversal is more expensive than arrays.
  • Linked list insertion is far cheaper than arrays.

Insertion sort injects the new value into the middle of the sorted segment. Hence, data needs to be "pushed back". However, when you are using a linked list, by twisting 2 pointers, you have effectively pushed the entire list back. In an array, you must perform n - i swaps to push the values back, which can be very expensive.

Selection sort always appends to the end, so it doesn't have this problem when using arrays. Hence, data does not need to be "pushed back".

Shortcut to create properties in Visual Studio?

Using VsVim the code snippets seem to work a little funny. The shortcut I was looking for when I ended up here is much simpler: after a member name type {g;s;

I have delimiter auto-closing turned on, so the closing brace appears on {, and typing a semicolon triggers an autocomplete for get and set.

It works on VS2013 and VS2015, and VS2012 just lacks the automatic brace matching.

Is there any use for unique_ptr with array?

There are tradeoffs, and you pick the solution which matches what you want. Off the top of my head:

Initial size

  • vector and unique_ptr<T[]> allow the size to be specified at run-time
  • array only allows the size to be specified at compile time

Resizing

  • array and unique_ptr<T[]> do not allow resizing
  • vector does

Storage

  • vector and unique_ptr<T[]> store the data outside the object (typically on the heap)
  • array stores the data directly in the object

Copying

  • array and vector allow copying
  • unique_ptr<T[]> does not allow copying

Swap/move

  • vector and unique_ptr<T[]> have O(1) time swap and move operations
  • array has O(n) time swap and move operations, where n is the number of elements in the array

Pointer/reference/iterator invalidation

  • array ensures pointers, references and iterators will never be invalidated while the object is live, even on swap()
  • unique_ptr<T[]> has no iterators; pointers and references are only invalidated by swap() while the object is live. (After swapping, pointers point into to the array that you swapped with, so they're still "valid" in that sense.)
  • vector may invalidate pointers, references and iterators on any reallocation (and provides some guarantees that reallocation can only happen on certain operations).

Compatibility with concepts and algorithms

  • array and vector are both Containers
  • unique_ptr<T[]> is not a Container

I do have to admit, this looks like an opportunity for some refactoring with policy-based design.

Could not find main class HelloWorld

You are not setting a classpath that includes your compiled class! java can't find any classes if you don't tell it where to look.

java -cp [compiler outpur dir] HelloWorld

Incidentally you do not need to set CLASSPATH the way you have done.

How to use index in select statement?

Generally, when you create an index on a table, database will automatically use that index while searching for data in that table. You don't need to do anything about that.

However, in MSSQL, you can specify an index hint which can specify that a particular index should be used to execute this query. More information about this can be found here.

Index hint is also seems to be available for MySQL. Thanks to Tudor Constantine.

How can I pass some data from one controller to another peer controller

In one controller, you can do:

$rootScope.$broadcast('eventName', data);

and listen to the event in another:

$scope.$on('eventName', function (event, data) {...});

How can I calculate the difference between two dates?

You can find the difference by converting the date in seconds and take time interval since 1970 for this and then you can find the difference between two dates.

Convert between UIImage and Base64 string

Swift 5, Xcode 10.

_x000D_
_x000D_
 let imageData = UIImage(named:"imagename").pngData()?.base64EncodedString(options: .lineLength64Characters)_x000D_
_x000D_
print(imageData)
_x000D_
_x000D_
_x000D_

How to write a file or data to an S3 object using boto3

In boto 3, the 'Key.set_contents_from_' methods were replaced by

For example:

import boto3

some_binary_data = b'Here we have some data'
more_binary_data = b'Here we have some more data'

# Method 1: Object.put()
s3 = boto3.resource('s3')
object = s3.Object('my_bucket_name', 'my/key/including/filename.txt')
object.put(Body=some_binary_data)

# Method 2: Client.put_object()
client = boto3.client('s3')
client.put_object(Body=more_binary_data, Bucket='my_bucket_name', Key='my/key/including/anotherfilename.txt')

Alternatively, the binary data can come from reading a file, as described in the official docs comparing boto 2 and boto 3:

Storing Data

Storing data from a file, stream, or string is easy:

# Boto 2.x
from boto.s3.key import Key
key = Key('hello.txt')
key.set_contents_from_file('/tmp/hello.txt')

# Boto 3
s3.Object('mybucket', 'hello.txt').put(Body=open('/tmp/hello.txt', 'rb'))

Output an Image in PHP

(Expanding on the accepted answer...)

I needed to:

  1. log views of a jpg image and an animated gif, and,
  2. ensure that the images are never cached (so every view is logged), and,
  3. also retain the original file extensions.

I accomplished this by creating a "secondary" .htaccess file in the sub-folder where the images are located.
The file contains only one line:

AddHandler application/x-httpd-lsphp .jpg .jpeg .gif

In the same folder, I placed the two 'original' image files (we'll call them orig.jpg and orig.gif), as well as two variations of the [simplified] script below (saved as myimage.jpg and myimage.gif)...

<?php 
  error_reporting(0); //hide errors (displaying one would break the image)

  //get user IP and the pseudo-image's URL
  if(isset($_SERVER['REMOTE_ADDR'])) {$ip =$_SERVER['REMOTE_ADDR'];}else{$ip= '(unknown)';}
  if(isset($_SERVER['REQUEST_URI'])) {$url=$_SERVER['REQUEST_URI'];}else{$url='(unknown)';}

  //log the visit
  require_once('connect.php');            //file with db connection info
  $conn = new mysqli($servername, $username, $password, $dbname);
  if (!$conn->connect_error) {         //if connected then save mySQL record
   $conn->query("INSERT INTO imageclicks (image, ip) VALUES ('$url', '$ip');");
     $conn->close();  //(datetime is auto-added to table with default of 'now')
  } 

  //display the image
  $imgfile='orig.jpg';                             // or 'orig.gif'
  header('Content-Type: image/jpeg');              // or 'image/gif'
  header('Content-Length: '.filesize($imgfile));
  header('Cache-Control: no-cache');
  readfile($imgfile);
?>

The images render (or animate) normally and can be called in any of the normal ways for images (like an <img> tag), and will save a record of the visiting IP, while invisible to the user.

Angular cli generate a service and include the provider in one step

run the below code in Terminal

makesure You are inside your project folder in terminal

ng g s servicename --module=app.module

CSS - center two images in css side by side

I've just done this for a project, and achieved it by using the h6 tag which I wasn't using for anything else:

in html code:

<h6><img alt="small drawing" src="../Images/image1.jpg" width="50%"/> <img alt="small drawing" src="../Images/image2.jpg" width="50%"/><br/>Optional caption text</h6>

The space between the image tags puts a vertical gap between the images. The width argument in each img tag is optional, but it neatly sizes the images to fill the width of the page. Notice that each image must be set to take up only 50% of the width. (Or 33% if you're using 3 images.) The width argument must come after the alt and src arguments or it won't work.

in css code:

/* h6: set presentation of images */
h6
  {
  font-family: "Franklin Gothic Demi", serif;
  font-size: 1.0em;
  font-weight: normal;
  line-height: 1.25em;
  text-align: center;
  }

The text items set the look of the caption text, and the text-align property centers both the images and the caption text.

JSchException: Algorithm negotiation fail

FWIW, I had this same error message under JSch 0.1.50. Upgrading to 0.1.52 solved the problem.

how does Array.prototype.slice.call() work?

The arguments object is not actually an instance of an Array, and does not have any of the Array methods. So, arguments.slice(...) will not work because the arguments object does not have the slice method.

Arrays do have this method, and because the arguments object is very similar to an array, the two are compatible. This means that we can use array methods with the arguments object. And since array methods were built with arrays in mind, they will return arrays rather than other argument objects.

So why use Array.prototype? The Array is the object which we create new arrays from (new Array()), and these new arrays are passed methods and properties, like slice. These methods are stored in the [Class].prototype object. So, for efficiency sake, instead of accessing the slice method by (new Array()).slice.call() or [].slice.call(), we just get it straight from the prototype. This is so we don't have to initialise a new array.

But why do we have to do this in the first place? Well, as you said, it converts an arguments object into an Array instance. The reason why we use slice, however, is more of a "hack" than anything. The slice method will take a, you guessed it, slice of an array and return that slice as a new array. Passing no arguments to it (besides the arguments object as its context) causes the slice method to take a complete chunk of the passed "array" (in this case, the arguments object) and return it as a new array.

Regarding 'main(int argc, char *argv[])'

With argc (argument count) and argv (argument vector) you can get the number and the values of passed arguments when your application has been launched.

This way you can use parameters (such as -version) when your application is started to act a different way.

But you can also use int main(void) as a prototype in C.

There is a third (less known and nonstandard) prototype with a third argument which is envp. It contains environment variables.


Resources:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

By reading your exception , It's sure that you forgot to autowire customerService

You should autowire your customerservice .

make following changes in your controller class

@Controller
public class CustomerController{

    @Autowired
    private Customerservice customerservice;
......other code......

}

Again your service implementation class

write

@Service
public class CustomerServiceImpl implements CustomerService {
    @Autowired
    private CustomerDAO customerDAO;
......other code......

.....add transactional methods
}

If you are using hibernate make necessary changes in your applicationcontext xml file(configuration of session factory is needed).

you should autowire sessionFactory set method in your DAO mplementation

please find samle application context :

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <context:annotation-config />
    <context:component-scan base-package="com.sparkle" />
    <!-- Configures the @Controller programming model -->
    <mvc:annotation-driven />

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
            p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" p:order="0" />

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>
    <!-- <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" /> -->

     <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">         
        <list>
            <value>/WEB-INF/jdbc.properties</value>          

        </list>    
    </property>     
    </bean>




    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc.driverClassName}"
        p:url="${jdbc.databaseurl}" p:username="${jdbc.username}"
        p:password="${jdbc.password}" />


    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven />


   <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"
          p:sessionFactory-ref="sessionFactory"/>


</beans>

note that i am using jdbc.properties file for jdbc url and driver specification

Turning a Comma Separated string into individual rows

Function

CREATE FUNCTION dbo.SplitToRows (@column varchar(100), @separator varchar(10))
RETURNS @rtnTable TABLE
  (
  ID int identity(1,1),
  ColumnA varchar(max)
  )
 AS
BEGIN
    DECLARE @position int = 0
    DECLARE @endAt int = 0
    DECLARE @tempString varchar(100)

    set @column = ltrim(rtrim(@column))

    WHILE @position<=len(@column)
    BEGIN       
        set @endAt = CHARINDEX(@separator,@column,@position)
            if(@endAt=0)
            begin
            Insert into @rtnTable(ColumnA) Select substring(@column,@position,len(@column)-@position)
            break;
            end
        set @tempString = substring(ltrim(rtrim(@column)),@position,@endAt-@position)

        Insert into @rtnTable(ColumnA) select @tempString
        set @position=@endAt+1;
    END
    return
END

Use case

select * from dbo.SplitToRows('T14; p226.0001; eee; 3554;', ';')

Or just a select with multiple result set

DECLARE @column varchar(max)= '1234; 4748;abcde; 324432'
DECLARE @separator varchar(10) = ';'
DECLARE @position int = 0
DECLARE @endAt int = 0
DECLARE @tempString varchar(100)

set @column = ltrim(rtrim(@column))

WHILE @position<=len(@column)
BEGIN       
    set @endAt = CHARINDEX(@separator,@column,@position)
        if(@endAt=0)
        begin
        Select substring(@column,@position,len(@column)-@position)
        break;
        end
    set @tempString = substring(ltrim(rtrim(@column)),@position,@endAt-@position)

    select @tempString
    set @position=@endAt+1;
END

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

Use a Page Viewer webpart and switch from Web Page to Folder. You can the specify the folder you want to display in the Link.

How can I get the name of an html page in Javascript?

Use window.location.pathname to get the path of the current page's URL.

How to center a "position: absolute" element

enter image description here

I'm not sure what you want to accomplish, but in this case just adding width: 100%; to your ul#slideshow li will do the trick.

Explanation

The img tags are inline-block elements. This means that they flow inline like text, but also have a width and height like block elements. In your css there are two text-align: center; rules applied to the <body> and to the #slideshowWrapper (which is redundant btw) this makes all inline and inline-block child elements to be centered in their closest block elements, in your code these are li tags. All block elements have width: 100% if they are the static flow (position: static;), which is default. The problem is that when you tell li tags to be position: absolute;, you take them out of normal static flow, and this causes them to shrink their size to just fit their inner content, in other words they kind of "lose" their width: 100% property.

Cannot enqueue Handshake after invoking quit

I had the same problem and Google led me here. I agree with @Ata that it's not right to just remove end(). After further Googling, I think using pooling is a better way.

node-mysql doc about pooling

It's like this:

var mysql = require('mysql');
var pool  = mysql.createPool(...);

pool.getConnection(function(err, connection) {
    connection.query( 'bla bla', function(err, rows) {
        connection.release();
    });
});

Apache error: _default_ virtualhost overlap on port 443

On a vanilla Apache2 install in CentOS, when you install mod_ssl it will automatically add a configuration file in:

{apache_dir}/conf.d/ssl.conf

This configuration file contains a default virtual host definition for port 443, named default:443. If you also have your own virtual host definition for 443 (i.e. in httpd.conf) then you will have a confict. Since the conf.d files are included first, they will win over yours.

To solve the conflict you can either remove the virtual host definition from conf.d/ssl.conf or update it to your own settings.

How should I pass multiple parameters to an ASP.Net Web API GET?

I think the easiest way is to simply use AttributeRouting.

It's obvious within your controller, why would you want this in your Global WebApiConfig file?

Example:

    [Route("api/YOURCONTROLLER/{paramOne}/{paramTwo}")]
    public string Get(int paramOne, int paramTwo)
    {
        return "The [Route] with multiple params worked";
    }

The {} names need to match your parameters.

Simple as that, now you have a separate GET that handles multiple params in this instance.

How can I convert my Java program to an .exe file?

If you need to convert your entire application to native code, i.e. an EXE plus DLLs, there is ExcelsiorJET. I found it works well and provided an alternative to bundling a JRE.

EDIT: This was posted in 2010 - the product is no longer available.

Unable to specify the compiler with CMake

Never try to set the compiler in the CMakeLists.txt file.

See the CMake FAQ about how to use a different compiler:

https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

(Note that you are attempting method #3 and the FAQ says "(avoid)"...)

We recommend avoiding the "in the CMakeLists" technique because there are problems with it when a different compiler was used for a first configure, and then the CMakeLists file changes to try setting a different compiler... And because the intent of a CMakeLists file should be to work with multiple compilers, according to the preference of the developer running CMake.

The best method is to set the environment variables CC and CXX before calling CMake for the very first time in a build tree.

After CMake detects what compilers to use, it saves them in the CMakeCache.txt file so that it can still generate proper build systems even if those variables disappear from the environment...

If you ever need to change compilers, you need to start with a fresh build tree.

Pass object to javascript function

The "braces" are making an object literal, i.e. they create an object. It is one argument.

Example:

function someFunc(arg) {
    alert(arg.foo);
    alert(arg.bar);
}

someFunc({foo: "This", bar: "works!"});

the object can be created beforehand as well:

var someObject = {
    foo: "This", 
    bar: "works!"
};

someFunc(someObject);

I recommend to read the MDN JavaScript Guide - Working with Objects.

How to read connection string in .NET Core?

See link for more info: https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-strings

JSON

    {
      "ConnectionStrings": {
        "BloggingDatabase": "Server=(localdb)\\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;"
      },
    }

C# Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("BloggingDatabase")));
}

EDIT: aspnetcore, starting 3.1: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1

Android view layout_width - how to change programmatically?

Or simply:

view.getLayoutParams().width = 400;
view.requestLayout();