Programs & Examples On #Ole automation

OLE-Automation is a Microsoft COM based technology that allows one application to control another via an exposed public interface.

What does the Excel range.Rows property really do?

Range.Rows, Range.Columns and Range.Cells are Excel.Range objects, according to the VBA Type() functions:

?TypeName(Selection.rows)
Range
However, that's not the whole story: those returned objects are extended types that inherit every property and method from Excel::Range - but .Columns and .Rows have a special For... Each iterator, and a special .Count property that aren't quite the same as the parent Range object's iterator and count.

So .Cells is iterated and counted as a collection of single-cell ranges, just like the default iterator of the parent range.

But .Columns is iterated and counted as a collection of vertical subranges, each of them a single column wide;

...And .Rows is iterated and counted as a collection of horizontal subranges, each of them a single row high.

The easiest way to understand this is to step through this code and watch what's selected:

Public Sub Test() 
Dim SubRange As Range Dim ParentRange As Range
Set ParentRange = ActiveSheet.Range("B2:E5")

For Each SubRange In ParentRange.Cells SubRange.Select Next
For Each SubRange In ParentRange.Rows SubRange.Select Next
For Each SubRange In ParentRange.Columns SubRange.Select Next
For Each SubRange In ParentRange SubRange.Select Next
End Sub
Enjoy. And try it with a couple of merged cells in there, just to see how odd merged ranges can be.

Split string with delimiters in C

Explode & implode - initial string remains intact, dynamic memory allocation

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

typedef struct
{
    uintptr_t   ptr;
    int         size;
} token_t;

int explode(char *str, int slen, const char *delimiter, token_t **tokens)
{
    int i = 0, c1 = 0, c2 = 0;

    for(i = 0; i <= slen; i++)
    {
            if(str[i] == *delimiter)
            {
                c1++;
            }
    }

    if(c1 == 0)
    {
            return -1;
    }

    *tokens = (token_t*)calloc((c1 + 1), sizeof(token_t));
    ((*tokens)[c2]).ptr = (uintptr_t)str;

    i = 0; 
    while(i <= slen)
    {
        if((str[i] == *delimiter) || (i == slen))
        {
                ((*tokens)[c2]).size = (int)((uintptr_t)&(str[i]) - (uintptr_t)(((*tokens)[c2]).ptr));
                if(i < slen)
                {
                    c2++;
                    ((*tokens)[c2]).ptr = (uintptr_t)&(str[i + 1]);
                }
        }
        i++;
    }
    return (c1 + 1);
}

char* implode(token_t *tokens, int size, const char *delimiter)
{
    int     i, len = 0;
    char    *str;

    for(i = 0; i < len; i++)
    {
        len += tokens[i].size + 1;
    }

    str = (char*)calloc(len, sizeof(char));

    len = 0;
    for(i = 0; i < size; i++)
    {
        memcpy((void*)&str[len], (void*)tokens[i].ptr, tokens[i].size);
        len += tokens[i].size;
        str[(len++)] = *delimiter;
    }

    str[len - 1] = '\0';

    return str;
}

Usage:

int main(int argc, char **argv)
{
    int         i, c;
    char        *exp = "JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC";
    token_t     *tokens;
    char        *imp;

    printf("%s\n", exp);

    if((c = explode(exp, strlen(exp), ",", &tokens)) > 0)
    {
        imp = implode(tokens, c, ",");
        printf("%s\n", imp);

        for(i = 0; i < c; i++)
        {
            printf("%.*s, %d\n", tokens[i].size, (char*)tokens[i].ptr, tokens[i].size);
        }
    }

    free((void*)tokens);
    free((void*)imp);
    return 0;
}

What are the main performance differences between varchar and nvarchar SQL Server data types?

Since your application is small, there is essentially no appreciable cost increase to using nvarchar over varchar, and you save yourself potential headaches down the road if you have a need to store unicode data.

When should I really use noexcept?

As I keep repeating these days: semantics first.

Adding noexcept, noexcept(true) and noexcept(false) is first and foremost about semantics. It only incidentally condition a number of possible optimizations.

As a programmer reading code, the presence of noexcept is akin to that of const: it helps me better grok what may or may not happen. Therefore, it is worthwhile spending some time thinking about whether or not you know if the function will throw. For a reminder, any kind of dynamic memory allocation may throw.


Okay, now on to the possible optimizations.

The most obvious optimizations are actually performed in the libraries. C++11 provides a number of traits that allows knowing whether a function is noexcept or not, and the Standard Library implementation themselves will use those traits to favor noexcept operations on the user-defined objects they manipulate, if possible. Such as move semantics.

The compiler may only shave a bit of fat (perhaps) from the exception handling data, because it has to take into account the fact that you may have lied. If a function marked noexcept does throw, then std::terminate is called.

These semantics were chosen for two reasons:

  • immediately benefiting from noexcept even when dependencies do not use it already (backward compatibility)
  • allowing the specification of noexcept when calling functions that may theoretically throw, but are not expected to for the given arguments

C default arguments

Yes, with features of C99 you may do this. This works without defining new data structures or so and without the function having to decide at runtime how it was called, and without any computational overhead.

For a detailed explanation see my post at

http://gustedt.wordpress.com/2010/06/03/default-arguments-for-c99/

Jens

How do I install command line MySQL client on mac?

Mysql has a client-only set of utilities:

Mysql client shell https://dev.mysql.com/downloads/shell/

Other command line utilities https://dev.mysql.com/downloads/utilities/

Mac OSX version available.

Android REST client, Sample?

Disclaimer: I am involved in the rest2mobile open source project

Another alternative as a REST client is to use rest2mobile.

The approach is slightly different as it uses concrete rest examples to generate the client code for the REST service. The code replaces the REST URL and JSON payloads with native java methods and POJOs. It also automatically handles server connections, asynchronous invocations and POJO to/from JSON conversions.

Note that this tool comes in different flavors (cli, plugins, android/ios/js support) and you can use the android studio plugin to generate the API directly into your app.

All the code can be found on github here.

How to start color picker on Mac OS?

You can call up the color picker from any Cocoa application (TextEdit, Mail, Keynote, Pages, etc.) by hitting Shift-Command-C

The following article explains more about using Mac OS's Color Picker.

http://www.macworld.com/article/46746/2005/09/colorpickersecrets.html

Mockito - NullpointerException when stubbing Method

faced the same issue, the solution that worked for me:

Instead of mocking the service interface, I used @InjectMocks to mock the service implementation:

@InjectMocks
private exampleServiceImpl exampleServiceMock;

instead of :

@Mock
private exampleService exampleServiceMock;

How to save SELECT sql query results in an array in C# Asp.net

Normally i use a class for this:

public class ClassName
{
    public string Col1 { get; set; }
    public int Col2 { get; set; }
}

Now you can use a loop to fill a list and ToArray if you really need an array:

ClassName[] allRecords = null;
string sql = @"SELECT col1,col2
               FROM  some table";
using (var command = new SqlCommand(sql, con))
{
    con.Open();
    using (var reader = command.ExecuteReader())
    {
        var list = new List<ClassName>();
        while (reader.Read())
            list.Add(new ClassName { Col1 = reader.GetString(0), Col2 = reader.GetInt32(1) });
        allRecords = list.ToArray();
    }
}

Note that i've presumed that the first column is a string and the second an integer. Just to demonstrate that C# is typesafe and how you use the DataReader.GetXY methods.

Can I have multiple Xcode versions installed?

Can I have multiple Xcode versions installed?

Solution:
Actually as many of the above answers says, it is possible. Even according to the following Oracle Mobile Platform Blog, you can install more than one XCodes in the same Mac. The reason why you need to do that may vary according to you.

Scenario:
You might have installed only one version of XCode for now. Mostly the one release behind the latest XCode version which is available through App Store (mine I've Xcode 6.3.2 and I needed to keep it and also install Xcode 7 which is available through App Store).

For Ex:-

You have already installed XCode 6.x, and App Store has XCode 7 already given by App Store. For any reason you need to keep that Older XCode 6.x(as you know it is stable for some time now) and also you need to install and try out new XCode 7

So number one question might be, How and Where could you download the Mac OS X installable DMG file for XCode 7 (or may be if you wanna try out an older XCode version)? Ok, here is the direct link apple downloads (you might have to log into Apple Developer account before viewing this link correctly), or else following is a StackOverflow Q&A link which gives the answer to where to download DMG files for XCode IDEs.

So now let's assume that you have obtained any of the DMG file for the XCode version you require to install as secondarily?

Steps:
Follow the steps given bellow which I got from the above given first link of Oracles Mobile Platform Blog.

  1. Close Xcode if running
  2. Rename /Applications/Xcode.app to /Applications/Xcode_6.x.app
  3. Enter the admin password when prompted
  4. Double click the DMG file of your required, pre-downloaded Xcode and install it
  5. Once installed it, before running it, change the new /Applications/Xcode.app that was just installed to (according to my above given example) /Application/Xcode_7.app

Note*:

[Please patiently read this section until the next Note] When you have two versions of Xcode installed, your workstation has two versions of Command Line Tool (xcodebuild) installed too. The question is what your Terminal and Xcode build command will use to when you are building your iOS App. Because along with the Command Line Tool, iOS SDK which is being used to build your app also depends on.

My experience was I've had two Xcode versions. Xcode 10 (Old one with iOS12.0 - iphoneos12.0), and Xcode 10.1 (New one with iOS 12.1 - iphoneos12.1). So obviously the settings for Command Line Tool was selected to use xcodebuild tool from the Old app. I had to manually select it in Xcode preference window.

Where to set Command Line Tool in Xcode Preference Window?

  • Select the Locations tab and there, you can select all the installed versions of Command Line Tools (which is xcodebuild).

How to figure out which version of iOS SDK is being used to build your iOS App?

  • On your Terminal issue following command: $> xcodebuild -showsdks
  • Above command should print out all the SDK details which your current Xcode configuration uses to build your Apps. And by seeing the results you will understand that your iOS/iphoneos SDK version depends on changing Command Line Tool (xcodebuild) setting on your Xcode.

Note**:
Above given Apple Downloads link and Oracles MPF blog post links might change and/or unavailable in the future.

So I hope that my this answer might be helpful to somebody else out there!
Cheers!

lvalue required as left operand of assignment

You cannot assign an rvalue to an rvalue.

if (strcmp("hello", "hello") = 0)

is wrong. Suggestions:

if (strcmp("hello", "hello") == 0)
                              ^

= is the assign operator.
== is the equal to operator.
I know many new programmers are confused with this fact.

What is Join() in jQuery?

The practical use of this construct? It is a javascript replaceAll() on strings.

var s = 'stackoverflow_is_cool';  
s = s.split('_').join(' ');  
console.log(s);

will output:

stackoverflow is cool

Android "hello world" pushnotification example

Overview of gcm: You send a request to google server from your android phone. You receive a registration id as a response. You will then have to send this registration id to the server from where you wish to send notifications to the mobile. Using this registration id you can then send notification to the device.

Answer:

  1. To send a notification you send the data(message) with the registration id of the device to https://android.googleapis.com/gcm/send. (use curl in php).
  2. To receive notification and registration etc, thats all you will be requiring.
  3. You will have to store the registration id on the device as well as on server. If you use GCM.jar the registration id is stored in preferences. If you wish you can save it in your local database as well.

Equivalent to AssemblyInfo in dotnet core/csproj

Those settings has moved into the .csproj file.

By default they don't show up but you can discover them from Visual Studio 2017 in the project properties Package tab.

Project properties, tab Package

Once saved those values can be found in MyProject.csproj

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net461</TargetFramework>
    <Version>1.2.3.4</Version>
    <Authors>Author 1</Authors>
    <Company>Company XYZ</Company>
    <Product>Product 2</Product>
    <PackageId>MyApp</PackageId>
    <AssemblyVersion>2.0.0.0</AssemblyVersion>
    <FileVersion>3.0.0.0</FileVersion>
    <NeutralLanguage>en</NeutralLanguage>
    <Description>Description here</Description>
    <Copyright>Copyright</Copyright>
    <PackageLicenseUrl>License URL</PackageLicenseUrl>
    <PackageProjectUrl>Project URL</PackageProjectUrl>
    <PackageIconUrl>Icon URL</PackageIconUrl>
    <RepositoryUrl>Repo URL</RepositoryUrl>
    <RepositoryType>Repo type</RepositoryType>
    <PackageTags>Tags</PackageTags>
    <PackageReleaseNotes>Release</PackageReleaseNotes>
  </PropertyGroup>

In the file explorer properties information tab, FileVersion is shown as "File Version" and Version is shown as "Product version"

Verify ImageMagick installation

To test only the IMagick PHP extension (not the full ImageMagick suite), save the following as a PHP file (testImagick.php) and then run it from console: php testImagick.php

<?php
$image = new Imagick();
$image->newImage(1, 1, new ImagickPixel('#ffffff'));
$image->setImageFormat('png');
$pngData = $image->getImagesBlob();
echo strpos($pngData, "\x89PNG\r\n\x1a\n") === 0 ? 'Ok' : 'Failed';
echo "\n";

credit: https://mlocati.github.io/articles/php-windows-imagick.html

UPDATE and REPLACE part of a string

To make the query run faster in big tables where not every line needs to be updated, you can also choose to only update rows that will be modified:

UPDATE dbo.xxx
SET Value = REPLACE(Value, '123', '')
WHERE ID <= 4
AND Value LIKE '%123%'

find index of an int in a list

It's even easier if you consider that the Generic List in C# is indexed from 0 like an array. This means you can just use something like:

int index = 0; int i = accounts[index];

How to hide close button in WPF window?

So, pretty much here is your problem. The close button on the upper right of a window frame is not part of the WPF window, but it belongs to the part of the window frame that is controled by your OS. This means you will have to use Win32 interop to do it.

alternativly, you can use the noframe and either provide your own "frame" or have no frame at all.

LaTeX: Multiple authors in a two-column article

I put together a little test here:

\documentclass[10pt,twocolumn]{article}

\title{Article Title}
\author{
    First Author\\
    Department\\
    school\\
    email@edu
  \and
    Second Author\\
    Department\\
    school\\
    email@edu
    \and
    Third Author\\
    Department\\
    school\\
    email@edu
    \and
    Fourth Author\\
    Department\\
    school\\
    email@edu
}
\date{\today}

\begin{document}

\maketitle

\begin{abstract}
\ldots
\end{abstract}

\section{Introduction}
\ldots

\end{document}

Things to note, the title, author and date fields are declared before \begin{document}. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn in the document class.

This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}. Here's a more detailed article on \LaTeX font sizes:

https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont

To italicize you can use {\it First Name} or \textit{First Name}.

Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.

How to create a multiline UITextfield?

Besides from the multiple line behaviour, the main difference between UITextView and UITextField is that the UITextView does not propose a placeholder. To bypass this limitation, you can use a UITextView with a "fake placeholder."

See this SO question for details: Placeholder in UITextView.

What is the difference between max-device-width and max-width for mobile web?

max-device-width is the device rendering width

@media all and (max-device-width: 400px) {
    /* styles for devices with a maximum width of 400px and less
       Changes only on device orientation */
}

@media all and (max-width: 400px) {
    /* styles for target area with a maximum width of 400px and less
       Changes on device orientation , browser resize */
}

The max-width is the width of the target display area means the current size of browser.

How to export plots from matplotlib with transparent background?

Use the matplotlib savefig function with the keyword argument transparent=True to save the image as a png file.

In [30]: x = np.linspace(0,6,31)

In [31]: y = np.exp(-0.5*x) * np.sin(x)

In [32]: plot(x, y, 'bo-')
Out[32]: [<matplotlib.lines.Line2D at 0x3f29750>]            

In [33]: savefig('demo.png', transparent=True)

Result: demo.png

Of course, that plot doesn't demonstrate the transparency. Here's a screenshot of the PNG file displayed using the ImageMagick display command. The checkerboard pattern is the background that is visible through the transparent parts of the PNG file.

display screenshot

How to pass arguments to addEventListener listener function?

Probably not optimal, but simple enough for those not super js savvy. Put the function that calls addEventListener into its own function. That way any function values passed into it maintain their own scope and you can iterate over that function as much as you want.

Example I worked out with file reading as I needed to capture and render a preview of the image and filename. It took me awhile to avoid asynchronous issues when utilizing a multiple file upload type. I would accidentally see the same 'name' on all renders despite uploading different files.

Originally, all the readFile() function was within the readFiles() function. This caused asynchronous scoping issues.

    function readFiles(input) {
      if (input.files) {
        for(i=0;i<input.files.length;i++) {

          var filename = input.files[i].name;

          if ( /\.(jpe?g|jpg|png|gif|svg|bmp)$/i.test(filename) ) {
            readFile(input.files[i],filename);
          }
       }
      }
    } //end readFiles



    function readFile(file,filename) {
            var reader = new FileReader();

            reader.addEventListener("load", function() { alert(filename);}, false);

            reader.readAsDataURL(file);

    } //end readFile

How to check if an app is installed from a web-page on an iPhone?

iOS Safari has a feature that allows you to add a "smart" banner to your webpage that will link either to your app, if it is installed, or to the App Store.

You do this by adding a meta tag to the page. You can even specify a detailed app URL if you want the app to do something special when it loads.

Details are at Apple's Promoting Apps with Smart App Banners page.

The mechanism has the advantages of being easy and presenting a standardized banner. The downside is that you don't have much control over the look or location. Also, all bets are off if the page is viewed in a browser other than Safari.

Search and get a line in Python

items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:

you can also get the line if there are other characters before token

items=re.findall("^.*token.*$",s,re.MULTILINE)

The above works like grep token on unix and keyword 'in' or .contains in python and C#

s='''
qwertyuiop
asdfghjkl

zxcvbnm
token qwerty

asdfghjklñ
'''

http://pythex.org/ matches the following 2 lines

....
....
token qwerty

Preloading images with JavaScript

I can confirm that the approach in the question is sufficient to trigger the images to be downloaded and cached (unless you have forbidden the browser from doing so via your response headers) in, at least:

  • Chrome 74
  • Safari 12
  • Firefox 66
  • Edge 17

To test this, I made a small webapp with several endpoints that each sleep for 10 seconds before serving a picture of a kitten. Then I added two webpages, one of which contained a <script> tag in which each of the kittens is preloaded using the preloadImage function from the question, and the other of which includes all the kittens on the page using <img> tags.

In all the browsers above, I found that if I visited the preloader page first, waited a while, and then went to the page with the <img> tags, my kittens rendered instantly. This demonstrates that the preloader successfully loaded the kittens into the cache in all browsers tested.

You can see or try out the application I used to test this at https://github.com/ExplodingCabbage/preloadImage-test.

Note in particular that this technique works in the browsers above even if the number of images being looped over exceeds the number of parallel requests that the browser is willing to make at a time, contrary to what Robin's answer suggests. The rate at which your images preload will of course be limited by how many parallel requests the browser is willing to send, but it will eventually request each image URL you call preloadImage() on.

How do I use CREATE OR REPLACE?

So I've been using this and it has worked very well: - it works more like a DROP IF EXISTS but gets the job done

DECLARE
       VE_TABLENOTEXISTS EXCEPTION;
PRAGMA EXCEPTION_INIT(VE_TABLENOTEXISTS, -942);


    PROCEDURE DROPTABLE(PIS_TABLENAME IN VARCHAR2) IS
              VS_DYNAMICDROPTABLESQL VARCHAR2(1024);
                    BEGIN
                       VS_DYNAMICDROPTABLESQL := 'DROP TABLE ' || PIS_TABLENAME;  
                    EXECUTE IMMEDIATE VS_DYNAMICDROPTABLESQL;

                    EXCEPTION
                        WHEN VE_TABLENOTEXISTS THEN
                             DBMS_OUTPUT.PUT_LINE(PIS_TABLENAME || ' NOT EXIST, SKIPPING....');
                        WHEN OTHERS THEN
                             DBMS_OUTPUT.PUT_LINE(SQLERRM);
                    RAISE;
                    END DROPTABLE;

    BEGIN
      DROPTABLE('YOUR_TABLE_HERE');
END DROPTABLE;
/   

Hope this helps Also reference: PLS-00103 Error in PL/SQL Developer

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

    public ActionResult ActionName(string ReqParam1, string ReqParam2, string ReqParam3, string ReqParam4)
    {
        this.ControllerContext.HttpContext.Response.Headers.Add("Access-Control-Allow-Origin","*");
         /*
                --Your code goes here --
         */
        return Json(new { ReturnData= "Data to be returned", Success=true }, JsonRequestBehavior.AllowGet);
    }

How can I select from list of values in SQL Server

PostgreSQL gives you 2 ways of doing this:

SELECT DISTINCT * FROM (VALUES('a'),('b'),('a'),('v')) AS tbl(col1)

or

SELECT DISTINCT * FROM (select unnest(array['a','b', 'a','v'])) AS tbl(col1)

using array approach you can also do something like this:

SELECT DISTINCT * FROM (select unnest(string_to_array('a;b;c;d;e;f;a;b;d', ';'))) AS tbl(col1)

How to "pull" from a local branch into another one?

What you are looking for is merging.

git merge master

With pull you fetch changes from a remote repository and merge them into the current branch.

String comparison in Python: is vs. ==

I would like to show a little example on how is and == are involved in immutable types. Try that:

a = 19998989890
b = 19998989889 +1
>>> a is b
False
>>> a == b
True

is compares two objects in memory, == compares their values. For example, you can see that small integers are cached by Python:

c = 1
b = 1
>>> b is c
True

You should use == when comparing values and is when comparing identities. (Also, from an English point of view, "equals" is different from "is".)

Entity Framework: There is already an open DataReader associated with this Command

In my case the issue had nothing to do with MARS connection string but with json serialization. After upgrading my project from NetCore2 to 3 i got this error.

More information can be found here

Filter Excel pivot table using VBA

Latest versions of Excel has a new tool called Slicers. Using slicers in VBA is actually more reliable that .CurrentPage (there have been reports of bugs while looping through numerous filter options). Here is a simple example of how you can select a slicer item (remember to deselect all the non-relevant slicer values):

Sub Step_Thru_SlicerItems2()
Dim slItem As SlicerItem
Dim i As Long
Dim searchName as string

Application.ScreenUpdating = False
searchName="Value1"

    For Each slItem In .VisibleSlicerItems
        If slItem.Name <> .SlicerItems(1).Name Then _
            slItem.Selected = False
        Else
            slItem.Selected = True
        End if
    Next slItem
End Sub

There are also services like SmartKato that would help you out with setting up your dashboards or reports and/or fix your code.

Creating stored procedure with declare and set variables

I assume you want to pass the Order ID in. So:

CREATE PROCEDURE [dbo].[Procedure_Name]
(
    @OrderID INT
) AS
BEGIN
    Declare @OrderItemID AS INT
    DECLARE @AppointmentID AS INT
    DECLARE @PurchaseOrderID AS INT
    DECLARE @PurchaseOrderItemID AS INT
    DECLARE @SalesOrderID AS INT
    DECLARE @SalesOrderItemID AS INT

    SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
    SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
    SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END

Why can't I make a vector of references?

By their very nature, references can only be set at the time they are created; i.e., the following two lines have very different effects:

int & A = B;   // makes A an alias for B
A = C;         // assigns value of C to B.

Futher, this is illegal:

int & D;       // must be set to a int variable.

However, when you create a vector, there is no way to assign values to it's items at creation. You are essentially just making a whole bunch of the last example.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

Most of what I write has already been covered by Pressacco, but this is specific to SpecFlow.

I was getting this message for the <specFlow> element and therefore I added a specflow.xsd file to the solution this answer (with some modifications to allow for the <plugins> element).

Thereafter I (like Pressacco), right clicked within the file buffer of app.config and selected properties, and within Schemas, I added "specflow.xsd" to the end. The entirety of Schemas now reads:

"C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\1033\DotNetConfig.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\EntityFrameworkConfig_6_1_0.xsd" "C:\Program Files (x86)\Microsoft Visual Studio 12.0\xml\Schemas\RazorCustomSchema.xsd" "specflow.xsd"

How to initialize a list with constructor?

You can initialize it just like any list:

public List<ContactNumber> ContactNumbers { get; set; }

public Human(int id)
{
    Id = id;
    ContactNumbers = new List<ContactNumber>();
}

public Human(int id, string address, string name) :this(id)
{
    Address = address;
    Name = name;
    // no need to initialize the list here since you're
    // already calling the single parameter constructor
}       

However, I would even go a step further and make the setter private since you often don't need to set the list, but just access/modify its contents:

public List<ContactNumber> ContactNumbers { get; private set; }

NLTK and Stopwords Fail #lookuperror

import nltk

nltk.download()

  • A GUI pops up and in that go the Corpora section, select the required corpus.
  • Verified Result

Best way to clear a PHP array's values

This is powerful and tested unset($gradearray);//re-set the array

How do I perform the SQL Join equivalent in MongoDB?

This page on the official mongodb site addresses exactly this question:

https://mongodb-documentation.readthedocs.io/en/latest/ecosystem/tutorial/model-data-for-ruby-on-rails.html

When we display our list of stories, we'll need to show the name of the user who posted the story. If we were using a relational database, we could perform a join on users and stores, and get all our objects in a single query. But MongoDB does not support joins and so, at times, requires bit of denormalization. Here, this means caching the 'username' attribute.

Relational purists may be feeling uneasy already, as if we were violating some universal law. But let’s bear in mind that MongoDB collections are not equivalent to relational tables; each serves a unique design objective. A normalized table provides an atomic, isolated chunk of data. A document, however, more closely represents an object as a whole. In the case of a social news site, it can be argued that a username is intrinsic to the story being posted.

What does "where T : class, new()" mean?

where T : struct

The type argument must be a value type. Any value type except Nullable can be specified. See Using Nullable Types (C# Programming Guide) for more information.

where T : class

The type argument must be a reference type, including any class, interface, delegate, or array type. (See note below.)

where T : new() The type argument must have a public parameterless constructor. When used in conjunction with other constraints, the new() constraint must be specified last.

where T : [base class name]

The type argument must be or derive from the specified base class.

where T : [interface name]

The type argument must be or implement the specified interface. Multiple interface constraints can be specified. The constraining interface can also be generic.

where T : U

The type argument supplied for T must be or derive from the argument supplied for U. This is called a naked type constraint.

How can I include all JavaScript files in a directory via JavaScript file?

Given that you want a 100% client side solution, in theory you could probably do this:

Via XmlHttpRequest, get the directory listing page for that directory (most web servers return a listing of files if there is no index.html file in the directory).

Parse that file with javascript, pulling out all the .js files. This will of course be sensitive to the format of the directory listing on your web server / web host.

Add the script tags dynamically, with something like this:

function loadScript (dir, file) {
 var scr = document.createElement("script");
 scr.src = dir + file;
 document.body.appendChild(scr);
 }

Open Google Chrome from VBA/Excel

The answer given by @ray above works perfectly, but make sure you are using the right path to open up the file. If you right click on your icon and click properties, you should see where the actual path is, just copy past that and it should work.

Properties

Get JSONArray without array name?

Here is a solution under 19API lvl:

  • First of all. Make a Gson obj. --> Gson gson = new Gson();

  • Second step is get your jsonObj as String with StringRequest(instead of JsonObjectRequest)

  • The last step to get JsonArray...

YoursObjArray[] yoursObjArray = gson.fromJson(response, YoursObjArray[].class);

How to get all options in a drop-down list by Selenium WebDriver using C#?

You can try using the WebDriver.Support SelectElement found in OpenQA.Selenium.Support.UI.Selected namespace to access the option list of a select list:

IWebElement elem = driver.FindElement(By.XPath("//select[@name='time_zone']"));

SelectElement selectList = new SelectElement(elem);
IList<IWebElement> options = selectList.Options;

You can then access each option as an IWebElement, such as:

IWebElement firstOption = options[0];
Assert.AreEqual(firstOption.GetAttribute("value"), "-09:00");

java.net.UnknownHostException: Unable to resolve host "<url>": No address associated with hostname and End of input at character 0 of

I encountered this problem too, reconnecting the WiFi can solve this.

For us ,we can check if the phone can resolve the host to IP when we start application. If it cannot resolve, tell the user to check the WiFi and then exit.

I hope it helps.

Refresh Page C# ASP.NET

You shouldn't use:

Page.Response.Redirect(Page.Request.Url.ToString(), true);

because this might cause a runtime error.

A better approach is:

Page.Response.Redirect(Page.Request.Url.ToString(), false);
        Context.ApplicationInstance.CompleteRequest();

jQuery ajax success error

I had the same problem;

textStatus = 'error'
errorThrown = (empty)
xhr.status = 0

That fits my problem exactly. It turns out that when I was loading the HTML-page from my own computer this problem existed, but when I loaded the HTML-page from my webserver it went alright. Then I tried to upload it to another domain, and again the same error occoured. Seems to be a cross-domain problem. (in my case at least)

I have tried calling it this way also:

var request = $.ajax({
url: "http://crossdomain.url.net/somefile.php", dataType: "text",
crossDomain: true,
xhrFields: {
withCredentials: true
}
});

but without success.

This post solved it for me: jQuery AJAX cross domain

Is there a stopwatch in Java?

Try this.

public class StopWatch { 

      private long startTime = 0;
      private long stopTime = 0;

      public StopWatch()
      {
            startTime = System.currentTimeMillis();
      }

      public void start() {
        startTime = System.currentTimeMillis();
      }

      public void stop() {
        stopTime = System.currentTimeMillis();
        System.out.println("StopWatch: " + getElapsedTime() + " milliseconds.");
        System.out.println("StopWatch: " + getElapsedTimeSecs() + " seconds.");
      }

      /**
       * @param process_name
       */
      public void stop(String process_name) {
            stopTime = System.currentTimeMillis();
            System.out.println(process_name + " StopWatch: " + getElapsedTime() + " milliseconds.");
            System.out.println(process_name + " StopWatch: " + getElapsedTimeSecs() + " seconds.");
      }      

      //elaspsed time in milliseconds
      public long getElapsedTime() {
          return stopTime - startTime;
      }

      //elaspsed time in seconds
      public double getElapsedTimeSecs() {
        double elapsed;
          elapsed = ((double)(stopTime - startTime)) / 1000;
        return elapsed;
      }
} 

Usage:

StopWatch watch = new StopWatch();
// do something
watch.stop();

Console:

StopWatch: 143 milliseconds.
StopWatch: 0.143 seconds.

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

How to include CSS file in Symfony 2 and Twig?

In case you are using Silex add the Symfony Asset as a dependency:

composer require symfony/asset

Then you may register Asset Service Provider:

$app->register(new Silex\Provider\AssetServiceProvider(), array(
    'assets.version' => 'v1',
    'assets.version_format' => '%s?version=%s',
    'assets.named_packages' => array(
        'css' => array(
            'version' => 'css2',
            'base_path' => __DIR__.'/../public_html/resources/css'
        ),
        'images' => array(
            'base_urls' => array(
                'https://img.example.com'
            )
        ),
    ),
));

Then in your Twig template file in head section:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    {% block head %}
    <link rel="stylesheet" href="{{ asset('style.css') }}" />
    {% endblock %}
</head>
<body>

</body>
</html>

dyld: Library not loaded ... Reason: Image not found

None of the above worked for me, but brew reinstall icu4c did.

JavaScript equivalent to printf/String.Format

I didn't see pyformat in the list so I thought I'd throw it in:

console.log(pyformat( 'The {} {} jumped over the {}'
                , ['brown' ,'fox' ,'foobar']
                ))
console.log(pyformat('The {0} {1} jumped over the {1}'
                , ['brown' ,'fox' ,'foobar']
                ))
console.log(pyformat('The {color} {animal} jumped over the {thing}'
                , [] ,{color: 'brown' ,animal: 'fox' ,thing: 'foobaz'}
                ))

UIView background color in Swift

In Swift 4, just as simple as Swift 3:

self.view.backgroundColor = UIColor.brown

Remove all elements contained in another array

I just implemented as:

Array.prototype.exclude = function(list){
        return this.filter(function(el){return list.indexOf(el)<0;})
}

Use as:

myArray.exclude(toRemove);

Error: The 'brew link' step did not complete successfully

Try this. Got from another reference and worked for me.

brew uninstall node
brew update
brew upgrade
brew cleanup
brew install node
sudo chown -R $(whoami) /usr/local
brew link --overwrite node
brew postinstall node

Android Studio gradle takes too long to build

In Android Studio, above Version 3.6, There is a new location to toggle Gradle's offline mode To enable or disable Gradle's offline mode.

To enable or disable Gradle's offline mode, select View > Tool Windows > Gradle from the menu. In the top bar of the Gradle window, click Toggle Offline Mode (near settings icon).

enter image description here

It's a little bit confusing on the icon, anyway offline mode is enabled when the toggle button is highlighted. :)

How do I use the new computeIfAbsent function?

Recently I was playing with this method too. I wrote a memoized algorithm to calcualte Fibonacci numbers which could serve as another illustration on how to use the method.

We can start by defining a map and putting the values in it for the base cases, namely, fibonnaci(0) and fibonacci(1):

private static Map<Integer,Long> memo = new HashMap<>();
static {
   memo.put(0,0L); //fibonacci(0)
   memo.put(1,1L); //fibonacci(1)
}

And for the inductive step all we have to do is redefine our Fibonacci function as follows:

public static long fibonacci(int x) {
   return memo.computeIfAbsent(x, n -> fibonacci(n-2) + fibonacci(n-1));
}

As you can see, the method computeIfAbsent will use the provided lambda expression to calculate the Fibonacci number when the number is not present in the map. This represents a significant improvement over the traditional, tree recursive algorithm.

Create a copy of a table within the same database DB2

We can copy all columns from one table to another, existing table:

INSERT INTO table2 SELECT * FROM table1;

Or we can copy only the columns we want to into another, existing table:

INSERT INTO table2 (column_name(s)) SELECT column_name(s) FROM table1;

or SELECT * INTO BACKUP_TABLE1 FROM TABLE1

"PKIX path building failed" and "unable to find valid certification path to requested target"

Issue Background:

I was getting following error when i try to run mvn clean install in my project and through Netbeans IDE clean and build option. This issue is due to certificate not available when we download through NET beans IDE/through command prompt, but able to download the files through the browser.

Error:

Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Could not transfer artifact com.java.project:product:jar:1.0.32 from/to repo-local (https://url/local-repo): sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  

Resolution:

1. Download the certificate of the Url in question:

  • Launch IE by "run as adminstrator" (otherwise, we will not be able to download the certificate)
  • Enter the url in IE-> https://url/local-repo (In my case this url had a untrusted certificateenter image description here.)
  • Download the certificate by clicking on Certificate error -> view certificate
  • Select Details tab -> copy to file -> next -> select "DER encoded binary X.509 (.CER)
  • save the certificate in some location, example : c:/user/sheldon/desktop/product.cer
  • Congrats! you have successfully downloaded the certificate for the site

2. Now install the key store to fix the issue.

  • Run the keytool command to append the downloaded keystore into the existing certificate file.
  • Command: Below command in the bin folder of jdk (JAVA_HOME).

C:\Program Files\Java\jdk1.8.0_141\jre\bin>keytool -importcert -file "C:/user/sheldon/desktop/product.cer" -alias product -keystore "C:/Program Files/Java/jdk1.8.0_141/jre/lib/security/cacerts".

  • You will be prompted to enter password. Enter keystore password: enter "changeit" again for "Trust this certificate? [no]:", enter "yes"

Sample command line commands/output:

keytool -importcert -file "C:/Users/sheldon/Desktop/product.cer" -alias product -keystore "C:/Program iles/Java/jdk1.8.0_141/jre/lib/security/cacerts"
Enter keystore password:
Trust this certificate? [no]:  yes
Certificate was added to keystore
  • Contgrats! now you should have got rid of "PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException" error in your Netbeans IDE.

CORS jQuery AJAX request

It's easy, you should set server http response header first. The problem is not with your front-end javascript code. You need to return this header:

Access-Control-Allow-Origin:*

or

Access-Control-Allow-Origin:your domain

In Apache config files, the code is like this:

Header set Access-Control-Allow-Origin "*"

In nodejs,the code is like this:

res.setHeader('Access-Control-Allow-Origin','*');

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

Your example is perfect: the field is private and it has a getter. This is the normal way to access a field. If you need a direct access to an object field, use reflection. Using reflection to get a field's value is a hack and should be used in extreme cases such as using a library whose code you cannot change.

How to check if anonymous object has a method?

What do you mean by an "anonymous object?" myObj is not anonymous since you've assigned an object literal to a variable. You can just test this:

if (typeof myObj.prop2 === 'function')
{
    // do whatever
}

Sort a list of Class Instances Python

import operator
sorted_x = sorted(x, key=operator.attrgetter('score'))

if you want to sort x in-place, you can also:

x.sort(key=operator.attrgetter('score'))

Is there a regular expression to detect a valid regular expression?

The following example by Paul McGuire, originally from the pyparsing wiki, but now available only through the Wayback Machine, gives a grammar for parsing some regexes, for the purposes of returning the set of matching strings. As such, it rejects those re's that include unbounded repetition terms, like '+' and '*'. But it should give you an idea about how to structure a parser that would process re's.

# 
# invRegex.py
#
# Copyright 2008, Paul McGuire
#
# pyparsing script to expand a regular expression into all possible matching strings
# Supports:
# - {n} and {m,n} repetition, but not unbounded + or * repetition
# - ? optional elements
# - [] character ranges
# - () grouping
# - | alternation
#
__all__ = ["count","invert"]

from pyparsing import (Literal, oneOf, printables, ParserElement, Combine, 
    SkipTo, operatorPrecedence, ParseFatalException, Word, nums, opAssoc,
    Suppress, ParseResults, srange)

class CharacterRangeEmitter(object):
    def __init__(self,chars):
        # remove duplicate chars in character range, but preserve original order
        seen = set()
        self.charset = "".join( seen.add(c) or c for c in chars if c not in seen )
    def __str__(self):
        return '['+self.charset+']'
    def __repr__(self):
        return '['+self.charset+']'
    def makeGenerator(self):
        def genChars():
            for s in self.charset:
                yield s
        return genChars

class OptionalEmitter(object):
    def __init__(self,expr):
        self.expr = expr
    def makeGenerator(self):
        def optionalGen():
            yield ""
            for s in self.expr.makeGenerator()():
                yield s
        return optionalGen

class DotEmitter(object):
    def makeGenerator(self):
        def dotGen():
            for c in printables:
                yield c
        return dotGen

class GroupEmitter(object):
    def __init__(self,exprs):
        self.exprs = ParseResults(exprs)
    def makeGenerator(self):
        def groupGen():
            def recurseList(elist):
                if len(elist)==1:
                    for s in elist[0].makeGenerator()():
                        yield s
                else:
                    for s in elist[0].makeGenerator()():
                        for s2 in recurseList(elist[1:]):
                            yield s + s2
            if self.exprs:
                for s in recurseList(self.exprs):
                    yield s
        return groupGen

class AlternativeEmitter(object):
    def __init__(self,exprs):
        self.exprs = exprs
    def makeGenerator(self):
        def altGen():
            for e in self.exprs:
                for s in e.makeGenerator()():
                    yield s
        return altGen

class LiteralEmitter(object):
    def __init__(self,lit):
        self.lit = lit
    def __str__(self):
        return "Lit:"+self.lit
    def __repr__(self):
        return "Lit:"+self.lit
    def makeGenerator(self):
        def litGen():
            yield self.lit
        return litGen

def handleRange(toks):
    return CharacterRangeEmitter(srange(toks[0]))

def handleRepetition(toks):
    toks=toks[0]
    if toks[1] in "*+":
        raise ParseFatalException("",0,"unbounded repetition operators not supported")
    if toks[1] == "?":
        return OptionalEmitter(toks[0])
    if "count" in toks:
        return GroupEmitter([toks[0]] * int(toks.count))
    if "minCount" in toks:
        mincount = int(toks.minCount)
        maxcount = int(toks.maxCount)
        optcount = maxcount - mincount
        if optcount:
            opt = OptionalEmitter(toks[0])
            for i in range(1,optcount):
                opt = OptionalEmitter(GroupEmitter([toks[0],opt]))
            return GroupEmitter([toks[0]] * mincount + [opt])
        else:
            return [toks[0]] * mincount

def handleLiteral(toks):
    lit = ""
    for t in toks:
        if t[0] == "\\":
            if t[1] == "t":
                lit += '\t'
            else:
                lit += t[1]
        else:
            lit += t
    return LiteralEmitter(lit)    

def handleMacro(toks):
    macroChar = toks[0][1]
    if macroChar == "d":
        return CharacterRangeEmitter("0123456789")
    elif macroChar == "w":
        return CharacterRangeEmitter(srange("[A-Za-z0-9_]"))
    elif macroChar == "s":
        return LiteralEmitter(" ")
    else:
        raise ParseFatalException("",0,"unsupported macro character (" + macroChar + ")")

def handleSequence(toks):
    return GroupEmitter(toks[0])

def handleDot():
    return CharacterRangeEmitter(printables)

def handleAlternative(toks):
    return AlternativeEmitter(toks[0])


_parser = None
def parser():
    global _parser
    if _parser is None:
        ParserElement.setDefaultWhitespaceChars("")
        lbrack,rbrack,lbrace,rbrace,lparen,rparen = map(Literal,"[]{}()")

        reMacro = Combine("\\" + oneOf(list("dws")))
        escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables)))
        reLiteralChar = "".join(c for c in printables if c not in r"\[]{}().*?+|") + " \t"

        reRange = Combine(lbrack + SkipTo(rbrack,ignore=escapedChar) + rbrack)
        reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )
        reDot = Literal(".")
        repetition = (
            ( lbrace + Word(nums).setResultsName("count") + rbrace ) |
            ( lbrace + Word(nums).setResultsName("minCount")+","+ Word(nums).setResultsName("maxCount") + rbrace ) |
            oneOf(list("*+?")) 
            )

        reRange.setParseAction(handleRange)
        reLiteral.setParseAction(handleLiteral)
        reMacro.setParseAction(handleMacro)
        reDot.setParseAction(handleDot)

        reTerm = ( reLiteral | reRange | reMacro | reDot )
        reExpr = operatorPrecedence( reTerm,
            [
            (repetition, 1, opAssoc.LEFT, handleRepetition),
            (None, 2, opAssoc.LEFT, handleSequence),
            (Suppress('|'), 2, opAssoc.LEFT, handleAlternative),
            ]
            )
        _parser = reExpr

    return _parser

def count(gen):
    """Simple function to count the number of elements returned by a generator."""
    i = 0
    for s in gen:
        i += 1
    return i

def invert(regex):
    """Call this routine as a generator to return all the strings that
       match the input regular expression.
           for s in invert("[A-Z]{3}\d{3}"):
               print s
    """
    invReGenerator = GroupEmitter(parser().parseString(regex)).makeGenerator()
    return invReGenerator()

def main():
    tests = r"""
    [A-EA]
    [A-D]*
    [A-D]{3}
    X[A-C]{3}Y
    X[A-C]{3}\(
    X\d
    foobar\d\d
    foobar{2}
    foobar{2,9}
    fooba[rz]{2}
    (foobar){2}
    ([01]\d)|(2[0-5])
    ([01]\d\d)|(2[0-4]\d)|(25[0-5])
    [A-C]{1,2}
    [A-C]{0,3}
    [A-C]\s[A-C]\s[A-C]
    [A-C]\s?[A-C][A-C]
    [A-C]\s([A-C][A-C])
    [A-C]\s([A-C][A-C])?
    [A-C]{2}\d{2}
    @|TH[12]
    @(@|TH[12])?
    @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?
    @(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))?
    (([ECMP]|HA|AK)[SD]|HS)T
    [A-CV]{2}
    A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]
    (a|b)|(x|y)
    (a|b) (x|y)
    """.split('\n')

    for t in tests:
        t = t.strip()
        if not t: continue
        print '-'*50
        print t
        try:
            print count(invert(t))
            for s in invert(t):
                print s
        except ParseFatalException,pfe:
            print pfe.msg
            print
            continue
        print

if __name__ == "__main__":
    main()

How to do a deep comparison between 2 objects with lodash?

If you need only key comparison:

 _.reduce(a, function(result, value, key) {
     return b[key] === undefined ? key : []
  }, []);

How do I make an image smaller with CSS?

Here's what I've done:

.resize {
    width: 400px;
    height: auto;
}

.resize {
    width: 300px;
    height: auto;
}

<img class="resize" src="example.jpg"/>

This will keep the image aspect ratio the same.

Cannot open output file, permission denied

FOR LINUX OS... go to file where u r created file.then usually ......project_name/bin/Debug/project_name.executable here for this executable file you wont be having execute permission then the execute permission.Either by right click if you are unable to change permission then use use open terminal(command promt) to change permission. first go to that executable file using 'cd' command then use "chmod u+x" then permission is going to change.then go to c::b open and execute you will get output.

only thing for all file u need to do it.

How to get images in Bootstrap's card to be the same height/width?

Try this in your css:

.card-img-top {
    width: 100%;
    height: 15vw;
    object-fit: cover;
}

Adjust the height vw as you see fit. The object-fit: cover enables zoom instead of image stretching.

How can I remove all files in my git repo and update/push from my local git repo?

If you prefer using GitHub Desktop, you can simply navigate inside the parent directory of your local repository and delete all of the files inside the parent directory. Then, commit and push your changes. Your repository will be cleansed of all files.

random.seed(): What does it do?

In this case, random is actually pseudo-random. Given a seed, it will generate numbers with an equal distribution. But with the same seed, it will generate the same number sequence every time. If you want it to change, you'll have to change your seed. A lot of people like to generate a seed based on the current time or something.

VHDL - How should I create a clock in a testbench?

Concurrent signal assignment:

library ieee;
use ieee.std_logic_1164.all;

entity foo is
end;
architecture behave of foo is
    signal clk: std_logic := '0';
begin
CLOCK:
clk <=  '1' after 0.5 ns when clk = '0' else
        '0' after 0.5 ns when clk = '1';
end;

ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw

enter image description here

Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.

Align printf output in Java

Format specifications for printf and printf-like methods take an optional width parameter.

System.out.printf( "%10d. %25s $%25.2f\n",
                   i + 1, BOOK_TYPE[i], COST[i] );

Adjust widths to desired values.

Returning pointer from a function

It is not allocating memory at assignment of value 12 to integer pointer. Therefore it crashes, because it's not finding any memory.

You can try this:

#include<stdio.h>
#include<stdlib.h>
int *fun();

int main()
{
    int *ptr;
    ptr=fun();
    printf("\n\t\t%d\n",*ptr);
}

int *fun()
{
    int ptr;
    ptr=12;
    return(&ptr);
}

How to set tbody height with overflow scroll

Here is a good example for table scrolling across x and y way. Horizontal and vertical scrolling is the best thing for responsive table.

_x000D_
_x000D_
table, th, tr, td {
  border: 1px solid lightgrey;
  border-collapse: collapse;
  
}
tbody {
  max-height: 200px;
max-width: 200px;
  overflow: auto;
  display: block;
  table-layout: fixed;
}

tr {
  display: table;
}
_x000D_
<table>
  <thead>
      <tr>
    <th>1</th>
    <th>2</th>
    <th>3</th>
  </tr>
  </thead>
  <tbody>
      <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
  </tr>
    <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
  </tr>
    <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
  </tr>
    <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
  </tr>
    <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
  </tr>
    <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
  </tr>
    <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
  </tr>
    <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
  </tr>
    <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
  </tr>
    <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
  </tr>
    <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
  </tr>
    <tr>
    <th>
     <input type="checkbox"> 
  </th>
    <td>2</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>

    <td>3</td>
    <td&
                  

Sometimes adding a WCF Service Reference generates an empty reference.cs

As @dblood points out, the main pain is in the DataContractSerializer, that doens't correctly re-use the types. There are already some answers here so I'll start by adding some pro's and cons about these:

  • The 'IsReference' flag causes a lot of trouble, but removing it isn't always the answer (specifically: in situations with recursion).
  • The underlying issue is that the data contract is somehow not the same as the type names, even though they sometimes are (huh? Yes, you read that right!). Apparently the serializer is quite picky and it's very hard to find the real issue.
  • Removing the 'references checks' from the 'Configure service reference' works, but leaves you with a multiple implementations. However, I often reuse SOAP interfaces across DLL's. Also, in most mature SOA's that I know, multiple services interfaces implement and extend the same interface classes. Removing 'use referenced types' checks results in a situation where you cannot simply pass objects around anymore.

Fortunately, if you are in control of your service, there is a simple solution that solves all these issues. This means you can still re-use service interfaces across DLL's - which is IMO a must-have for a proper solution. This is how the solution works:

  1. Create a separate interface DLL. In that DLL, include all DataContract and ServiceContract's; put ServiceContract's on your interfaces.
  2. Derive the server implementation from the interface.
  3. Use the same DLL to construct the client using your favorite method. For example (IMyInterface is the service contract interface):

    var httpBinding = new BasicHttpBinding();
    var identity = new DnsEndpointIdentity("");
    var address = new EndpointAddress(url, identity, new AddressHeaderCollection());
    var channel = new ChannelFactory<IMyInterface>(httpBinding, address);
    return channel.CreateChannel();
    

In other words: Don't use the 'add service reference' functionality, but force WCF to use the (correct) service types by bypassing the proxy generation. After all, you already have these classes.

Pro's:

  1. You bypass the svcutil.exe process, which means you don't have any IsReference issues
  2. DataContract types and names are correct by definition; after all, both server and client use the very same definition.
  3. If you extend the API or use types from another DLL, (1) and (2) still hold, so you won't run in any trouble there.

Cons:

  1. A-sync methods are a pain, since you don't generate an a-sync proxy. As a result, I wouldn't recommend doing this in Silverlight applications.

C#: how to get first char of a string?

getting a char from a string may depend on the enconding (string default is UTF-16)

https://stackoverflow.com/a/32141891

string str = new String(new char[] { '\uD800', '\uDC00', 'z' });
string first = str.Substring(0, char.IsHighSurrogate(str[0]) ? 2 : 1);

How to use vim in the terminal?

You can definetely build your code from Vim, that's what the :make command does.

However, you need to go through the basics first : type vimtutor in your terminal and follow the instructions to the end.

After you have completed it a few times, open an existing (non-important) text file and try out all the things you learned from vimtutor: entering/leaving insert mode, undoing changes, quitting/saving, yanking/putting, moving and so on.

For a while you won't be productive at all with Vim and will probably be tempted to go back to your previous IDE/editor. Do that, but keep up with Vim a little bit every day. You'll probably be stopped by very weird and unexpected things but it will happen less and less.

In a few months you'll find yourself hitting o, v and i all the time in every textfield everywhere.

Have fun!

How to uninstall a Windows Service when there is no executable for it left on the system?

You should be able to uninstall it using sc.exe (I think it is included in the Windows Resource Kit) by running the following in an "administrator" command prompt:

sc.exe delete <service name>

where <service name> is the name of the service itself as you see it in the service management console, not of the exe.

You can find sc.exe in the System folder and it needs Administrative privileges to run. More information in this Microsoft KB article.

Alternatively, you can directly call the DeleteService() api. That way is a little more complex, since you need to get a handle to the service control manager via OpenSCManager() and so on, but on the other hand it gives you more control over what is happening.

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Truncating a table in a stored procedure

As well as execute immediate you can also use

DBMS_UTILITY.EXEC_DDL_STATEMENT('TRUNCATE TABLE tablename;');

The statement fails because the stored proc is executing DDL and some instances of DDL could invalidate the stored proc. By using the execute immediate or exec_ddl approaches the DDL is implemented through unparsed code.

When doing this you neeed to look out for the fact that DDL issues an implicit commit both before and after execution.

Getting all documents from one collection in Firestore

Here's a simple version of the top answer, but going into an object with the document ids:

async getMarker() {
    const snapshot = await firebase.firestore().collection('events').get()
    return snapshot.docs.reduce(function (acc, doc, i) {
              acc[doc.id] = doc.data();
              return acc;
            }, {});
}

Difference between declaring variables before or in loop?

I had this very same question for a long time. So I tested an even simpler piece of code.

Conclusion: For such cases there is NO performance difference.

Outside loop case

int intermediateResult;
for(int i=0; i < 1000; i++){
    intermediateResult = i+2;
    System.out.println(intermediateResult);
}

Inside loop case

for(int i=0; i < 1000; i++){
    int intermediateResult = i+2;
    System.out.println(intermediateResult);
}

I checked the compiled file on IntelliJ's decompiler and for both cases, I got the same Test.class

for(int i = 0; i < 1000; ++i) {
    int intermediateResult = i + 2;
    System.out.println(intermediateResult);
}

I also disassembled code for both the case using the method given in this answer. I'll show only the parts relevant to the answer

Outside loop case

Code:
  stack=2, locals=3, args_size=1
     0: iconst_0
     1: istore_2
     2: iload_2
     3: sipush        1000
     6: if_icmpge     26
     9: iload_2
    10: iconst_2
    11: iadd
    12: istore_1
    13: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
    16: iload_1
    17: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
    20: iinc          2, 1
    23: goto          2
    26: return
LocalVariableTable:
        Start  Length  Slot  Name   Signature
           13      13     1 intermediateResult   I
            2      24     2     i   I
            0      27     0  args   [Ljava/lang/String;

Inside loop case

Code:
      stack=2, locals=3, args_size=1
         0: iconst_0
         1: istore_1
         2: iload_1
         3: sipush        1000
         6: if_icmpge     26
         9: iload_1
        10: iconst_2
        11: iadd
        12: istore_2
        13: getstatic     #2                  // Field java/lang/System.out:Ljava/io/PrintStream;
        16: iload_2
        17: invokevirtual #3                  // Method java/io/PrintStream.println:(I)V
        20: iinc          1, 1
        23: goto          2
        26: return
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
           13       7     2 intermediateResult   I
            2      24     1     i   I
            0      27     0  args   [Ljava/lang/String;

If you pay close attention, only the Slot assigned to i and intermediateResult in LocalVariableTable is swapped as a product of their order of appearance. The same difference in slot is reflected in other lines of code.

  • No extra operation is being performed
  • intermediateResult is still a local variable in both cases, so there is no difference access time.

BONUS

Compilers do a ton of optimization, take a look at what happens in this case.

Zero work case

for(int i=0; i < 1000; i++){
    int intermediateResult = i;
    System.out.println(intermediateResult);
}

Zero work decompiled

for(int i = 0; i < 1000; ++i) {
    System.out.println(i);
}

Adding attribute in jQuery

You can add attributes using attr like so:

$('#someid').attr('name', 'value');

However, for DOM properties like checked, disabled and readonly, the proper way to do this (as of JQuery 1.6) is to use prop.

$('#someid').prop('disabled', true);

sql searching multiple words in a string

Oracle SQL :

select * 
from MY_TABLE
where REGEXP_LIKE (company , 'Microsodt industry | goglge auto car | oracles    database')
  • company - is the database column name.
  • results - this SQL will show you if company column rows contain one of those companies (OR phrase) please note that : no wild characters are needed, it's built in.

more info at : http://www.techonthenet.com/oracle/regexp_like.php

'console' is undefined error for Internet Explorer

Try

if (!window.console) console = ...

An undefined variable cannot be referred directly. However, all global variables are attributes of the same name of the global context (window in case of browsers), and accessing an undefined attribute is fine.

Or use if (typeof console === 'undefined') console = ... if you want to avoid the magic variable window, see @Tim Down's answer.

jQuery remove all list items from an unordered list

An example using .remove():

<p>Remove LI's from list</p>
<ul>
    <li>Test</li>
    <li>Test</li>
    <li>Test</li>
    <li>Test</li>
    <li>Test</li>
</ul>
<p>END</p>

setTimeout(function(){$('ul li').remove();},1000);

http://jsfiddle.net/userdude/ZAd2Y/

Also, .empty() should have worked.

How to add reference to a method parameter in javadoc?

The correct way of referring to a method parameter is like this:

enter image description here

Comparing user-inputted characters in C

For a start, your answer variable should be of type char, not char*.

As for the if statement:

if (answer == ('Y' || 'y'))

This is first evaluating 'Y' || 'y' which, in Boolean logic (and for ASCII) is true since both of them are "true" (non-zero). In other words, you'd only get the if statement to fire if you'd somehow entered CTRLA (again, for ASCII, and where a true values equates to 1)*a.

You could use the more correct:

if ((answer == 'Y') || (answer == 'y'))

but you really should be using:

if (toupper(answer) == 'Y')

since that's the more portable way to achieve the same end.


*a You may be wondering why I'm putting in all sorts of conditionals for my statements. While the vast majority of C implementations use ASCII and certain known values, it's not necessarily mandated by the ISO standards. I know for a fact that at least one compiler still uses EBCDIC so I don't like making unwarranted assumptions.

How to reload apache configuration for a site without restarting apache?

If you are using Ubuntu server, you can use systemctl

systemctl reload apache2

Why doesn't Git ignore my specified file?

I run into this, it's an old question, but I want that file to be tracked but to not track it on certain working copies, to do that you can run

git update-index --assume-unchanged sites/default/settings.php

How to edit a text file in my terminal

Open the file again using vi. and then press the insert button to begin editing it.

How to show an alert box in PHP?

use this code

echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';

The problem was:

  1. you missed "
  2. It should be alert not alery

How to capitalize the first letter of word in a string using Java?

Adding everything together, it is a good idea to trim for extra white space at beginning of string. Otherwise, .substring(0,1).toUpperCase will try to capitalize a white space.

    public String capitalizeFirstLetter(String original) {
        if (original == null || original.length() == 0) {
            return original;
        }
        return original.trim().substring(0, 1).toUpperCase() + original.substring(1);
    }

Query to select data between two dates with the format m/d/yyyy

select * from xxx where dates between '2012-10-10' and '2012-10-12'

I always use YYYY-MM-DD in my views and never had any issue. Plus, it is readable and non equivocal.
You should be aware that using BETWEEN might not return what you expect with a DATETIME field, since it would eliminate records dated '2012-10-12 08:00' for example.
I would rather use where dates >= '2012-10-10' and dates < '2012-10-13' (lower than next day)

How to use ClassLoader.getResources() correctly?

There is no way to recursively search through the classpath. You need to know the Full pathname of a resource to be able to retrieve it in this way. The resource may be in a directory in the file system or in a jar file so it is not as simple as performing a directory listing of "the classpath". You will need to provide the full path of the resource e.g. '/com/mypath/bla.xml'.

For your second question, getResource will return the first resource that matches the given resource name. The order that the class path is searched is given in the javadoc for getResource.

How to get the first column of a pandas DataFrame as a Series?

This works great when you want to load a series from a csv file

x = pd.read_csv('x.csv', index_col=False, names=['x'],header=None).iloc[:,0]
print(type(x))
print(x.head(10))


<class 'pandas.core.series.Series'>
0    110.96
1    119.40
2    135.89
3    152.32
4    192.91
5    177.20
6    181.16
7    177.30
8    200.13
9    235.41
Name: x, dtype: float64

DISTINCT for only one column

This assumes SQL Server 2005+ and your definition of "last" is the max PK for a given email

WITH CTE AS
(
SELECT ID, 
       Email, 
       ProductName, 
       ProductModel, 
       ROW_NUMBER() OVER (PARTITION BY Email ORDER BY ID DESC) AS RowNumber 
FROM   Products
)
SELECT ID, 
       Email, 
       ProductName, 
       ProductModel
FROM CTE 
WHERE RowNumber = 1

Javascript : natural sort of alphanumerical strings

The most fully-featured library to handle this as of 2019 seems to be natural-orderby.

const { orderBy } = require('natural-orderby')

const unordered = [
  '123asd',
  '19asd',
  '12345asd',
  'asd123',
  'asd12'
]

const ordered = orderBy(unordered)

// [ '19asd',
//   '123asd',
//   '12345asd',
//   'asd12',
//   'asd123' ]

It not only takes arrays of strings, but also can sort by the value of a certain key in an array of objects. It can also automatically identify and sort strings of: currencies, dates, currency, and a bunch of other things.

Surprisingly, it's also only 1.6kB when gzipped.

How to delete the contents of a folder?

the easiest way to delete all files in a folder/remove all files

import os
files = os.listdir(yourFilePath)
for f in files:
    os.remove(yourFilePath + f)

How to click on hidden element in Selenium WebDriver?

Here is the script in Python.

You cannot click on elements in selenium that are hidden. However, you can execute JavaScript to click on the hidden element for you.

element = driver.find_element_by_id(buttonID)
driver.execute_script("$(arguments[0]).click();", element)

Java: how do I get a class literal from a generic type?

There are no Class literals for parameterized types, however there are Type objects that correctly define these types.

See java.lang.reflect.ParameterizedType - http://java.sun.com/j2se/1.5.0/docs/api/java/lang/reflect/ParameterizedType.html

Google's Gson library defines a TypeToken class that allows to simply generate parameterized types and uses it to spec json objects with complex parameterized types in a generic friendly way. In your example you would use:

Type typeOfListOfFoo = new TypeToken<List<Foo>>(){}.getType()

I intended to post links to the TypeToken and Gson classes javadoc but Stack Overflow won't let me post more than one link since I'm a new user, you can easily find them using Google search

Eclipse reported "Failed to load JNI shared library"

Yep, in Windows 7 64 bit you have C:\Program Files and C:\Program Files (x86). You can find Java folders in both of them, but you must add C:\Program Files\Java\jre7\bin to environment variable PATH.

MacOS Xcode CoreSimulator folder very big. Is it ok to delete content?

That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.

Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431

What is syntax for selector in CSS for next element?

You can use the sibling selector ~:

h1.hc-reform ~ p{
     clear:both;
}

This selects all the p elements that come after .hc-reform, not just the first one.

Is it possible to embed animated GIFs in PDFs?

Another possibility is LaTeX + animate package. You will need to provide the individual frames making the animation. The resulting pdf does NOT require any plugin, the animation is shown in Adobe reader

Angularjs if-then-else construction in expression

This can be done in one line.

{{corretor.isAdministrador && 'YES' || 'NÂO'}}

Usage in a td tag:

<td class="text-center">{{corretor.isAdministrador && 'Sim' || 'Não'}}</td>

How to copy data from another workbook (excel)?

I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -

Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")

The Range("A1") in Sheet1 of Book1 now contains "A".

Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".

Javadoc link to method in other class

For the Javadoc tag @see, you don't need to use @link; Javadoc will create a link for you. Try

@see com.my.package.Class#method()

Here's more info about @see.

How do I create an average from a Ruby array?

For public amusement, yet another solution:

a = 0, 4, 8, 2, 5, 0, 2, 6
a.reduce [ 0.0, 0 ] do |(s, c), e| [ s + e, c + 1 ] end.reduce :/
#=> 3.375

Convert blob to base64

 var reader = new FileReader();
 reader.readAsDataURL(blob); 
 reader.onloadend = function() {
     var base64data = reader.result;                
     console.log(base64data);
 }

Form the docs readAsDataURL encodes to base64

How to use WebRequest to POST some data and read response?

Below is the code that read the data from the text file and sends it to the handler for processing and receive the response data from the handler and read it and store the data in the string builder class

 //Get the data from text file that needs to be sent.
                FileStream fileStream = new FileStream(@"G:\Papertest.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                byte[] buffer = new byte[fileStream.Length];
                int count = fileStream.Read(buffer, 0, buffer.Length);

                //This is a handler would recieve the data and process it and sends back response.
                WebRequest myWebRequest = WebRequest.Create(@"http://localhost/Provider/ProcessorHandler.ashx");

                myWebRequest.ContentLength = buffer.Length;
                myWebRequest.ContentType = "application/octet-stream";
                myWebRequest.Method = "POST";
                // get the stream object that holds request stream.
                Stream stream = myWebRequest.GetRequestStream();
                       stream.Write(buffer, 0, buffer.Length);
                       stream.Close();

                //Sends a web request and wait for response.
                try
                {
                    WebResponse webResponse = myWebRequest.GetResponse();
                    //get Stream Data from the response
                    Stream respData = webResponse.GetResponseStream();
                    //read the response from stream.
                    StreamReader streamReader = new StreamReader(respData);
                    string name;
                    StringBuilder str = new StringBuilder();
                    while ((name = streamReader.ReadLine()) != null)
                    {
                        str.Append(name); // Add to stringbuider when response contains multple lines data
                   }
                }
                catch (Exception ex)
                {
                    throw ex;
                }

How can I list the contents of a directory in Python?

os.walk can be used if you need recursion:

import os
start_path = '.' # current directory
for path,dirs,files in os.walk(start_path):
    for filename in files:
        print os.path.join(path,filename)

How to dump only specific tables from MySQL?

If you're in local machine then use this command

/usr/local/mysql/bin/mysqldump -h127.0.0.1 --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

For remote machine, use below one

/usr/local/mysql/bin/mysqldump -h [remoteip] --port = 3306 -u [username] -p [password] --databases [db_name] --tables [tablename] > /to/path/tablename.sql;

Extracting specific columns from a data frame

There are two obvious choices: Joshua Ulrich's df[,c("A","B","E")] or

df[,c(1,2,5)]

as in

> df <- data.frame(A=c(1,2),B=c(3,4),C=c(5,6),D=c(7,7),E=c(8,8),F=c(9,9)) 
> df
  A B C D E F
1 1 3 5 7 8 9
2 2 4 6 7 8 9
> df[,c(1,2,5)]
  A B E
1 1 3 8
2 2 4 8
> df[,c("A","B","E")]
  A B E
1 1 3 8
2 2 4 8

Woocommerce get products

Do not use WP_Query() or get_posts(). From the WooCommerce doc:

wc_get_products and WC_Product_Query provide a standard way of retrieving products that is safe to use and will not break due to database changes in future WooCommerce versions. Building custom WP_Queries or database queries is likely to break your code in future versions of WooCommerce as data moves towards custom tables for better performance.

You can retrieve the products you want like this:

$args = array(
    'category' => array( 'hoodies' ),
    'orderby'  => 'name',
);
$products = wc_get_products( $args );

WooCommerce documentation

Note: the category argument takes an array of slugs, not IDs.

Why do this() and super() have to be the first statement in a constructor?

That's because your constructor depends on other constructors. To your constructor work correctly its necessary to other constructor works correctly which is dependent. That's why its necessary to check dependent constructors first which called by either this() or super() in your constructor. If other constructors which called by either this() or super() have a problem so whats point execute other statements because all will fail if called constructor fails.

Insert content into iFrame

You can enter (for example) text from div into iFrame:

var $iframe = $('#iframe');
$iframe.ready(function() {
    $iframe.contents().find("body").append($('#mytext'));
});

and divs:

<iframe id="iframe"></iframe>
<div id="mytext">Hello!</div>

and JSFiddle demo: link

PHPmailer sending HTML CODE

do like this-paste your html code inside your separate html file using GET method.

$mail->IsHTML(true);                                 
    $mail->WordWrap = 70;                                 
    $mail->addAttachment= $_GET['addattachment']; $mail->AltBody   
    =$_GET['AltBody'];  $mail->Subject = $_GET['subject']; $mail->Body = $_GET['body'];

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

It can also be due to a duplicate entry in any of the tables that are used.

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I had that problem. And I found this solve. In Android Studio, Open File menu, and go to Project Structure, In Module app, go to dependencies tab and you can add 'com.google.android.gms:play-services:x.x.x' by clicking on + button.

Optimal number of threads per core

The ideal is 1 thread per core, as long as none of the threads will block.

One case where this may not be true: there are other threads running on the core, in which case more threads may give your program a bigger slice of the execution time.

How to add a local repo and treat it as a remote repo

I am posting this answer to provide a script with explanations that covers three different scenarios of creating a local repo that has a local remote. You can run the entire script and it will create the test repos in your home folder (tested on windows git bash). The explanations are inside the script for easier saving to your personal notes, its very readable from, e.g. Visual Studio Code.

I would also like to thank Jack for linking to this answer where adelphus has good, detailed, hands on explanations on the topic.

This is my first post here so please advise what should be improved.

## SETUP LOCAL GIT REPO WITH A LOCAL REMOTE
# the main elements:
# - remote repo must be initialized with --bare parameter
# - local repo must be initialized
# - local repo must have at least one commit that properly initializes a branch(root of the commit tree)
# - local repo needs to have a remote
# - local repo branch must have an upstream branch on the remote

{ # the brackets are optional, they allow to copy paste into terminal and run entire thing without interruptions, run without them to see which cmd outputs what

cd ~
rm -rf ~/test_git_local_repo/

## Option A - clean slate - you have nothing yet

mkdir -p ~/test_git_local_repo/option_a ; cd ~/test_git_local_repo/option_a
git init --bare local_remote.git # first setup the local remote
git clone local_remote.git local_repo # creates a local repo in dir local_repo
cd ~/test_git_local_repo/option_a/local_repo
git remote -v show origin # see that git clone has configured the tracking
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git push origin master # now have a fully functional setup, -u not needed, git clone does this for you

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branches and their respective remote upstream branches with the initial commit
git remote -v show origin # see all branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option B - you already have a local git repo and you want to connect it to a local remote

mkdir -p ~/test_git_local_repo/option_b ; cd ~/test_git_local_repo/option_b
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing git local repo you want to connect with the local remote
mkdir local_repo ; cd local_repo
git init # if not yet a git repo
touch README.md ; git add . ; git commit -m "initial commit on master" # properly init master
git checkout -b develop ; touch fileB ; git add . ; git commit -m "add fileB on develop" # create develop and fake change

# connect with local remote
cd ~/test_git_local_repo/option_b/local_repo
git remote add origin ~/test_git_local_repo/option_b/local_remote.git
git remote -v show origin # at this point you can see that there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream
git push -u origin develop # -u to set upstream; need to run this for every other branch you already have in the project

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch(es) and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote

## Option C - you already have a directory with some files and you want it to be a git repo with a local remote

mkdir -p ~/test_git_local_repo/option_c ; cd ~/test_git_local_repo/option_c
git init --bare local_remote.git # first setup the local remote

# simulate a pre-existing directory with some files
mkdir local_repo ; cd local_repo ; touch README.md fileB

# make a pre-existing directory a git repo and connect it with local remote
cd ~/test_git_local_repo/option_c/local_repo
git init
git add . ; git commit -m "inital commit on master" # properly init master
git remote add origin ~/test_git_local_repo/option_c/local_remote.git
git remote -v show origin # see there is no the tracking configured (unlike with git clone), so you need to push with -u
git push -u origin master # -u to set upstream

# check all is set-up correctly
git pull # check you can pull
git branch -avv # see local branch and its remote upstream with the initial commit
git remote -v show origin # see all remote branches are set to pull and push to remote
git log --oneline --graph --decorate --all # see all commits and branches tips point to the same commits for both local and remote
}

How to exclude rows that don't join with another table?

Another solution is:

SELECT * FROM TABLE1 WHERE id NOT IN (SELECT id FROM TABLE2)

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

If you didn't change anything related to certificates (didn't replace or update them) just do a Product -> Clean. It helped me several times. (Xcode 6.2)

PhoneGap Eclipse Issue - eglCodecCommon glUtilsParamSize: unknow param errors

@theczechsensation's solution is already half way there.

For those who like to exclude noisy log messages and keep the log to their app only this is the solution:

New Logcat Filter Settings

Add your exclusions to Log Tag like this: ^(?!(eglCodecCommon|tagToExclude))

Add your package name or prefix to Package Name: com.mycompany.

This way it is possible to filter for as many strings you like and keep the log to your package.

Convert time.Time to string

You can use the Time.String() method to convert a time.Time to a string. This uses the format string "2006-01-02 15:04:05.999999999 -0700 MST".

If you need other custom format, you can use Time.Format(). For example to get the timestamp in the format of yyyy-MM-dd HH:mm:ss use the format string "2006-01-02 15:04:05".

Example:

t := time.Now()
fmt.Println(t.String())
fmt.Println(t.Format("2006-01-02 15:04:05"))

Output (try it on the Go Playground):

2009-11-10 23:00:00 +0000 UTC
2009-11-10 23:00:00

Note: time on the Go Playground is always set to the value seen above. Run it locally to see current date/time.

Also note that using Time.Format(), as the layout string you always have to pass the same time –called the reference time– formatted in a way you want the result to be formatted. This is documented at Time.Format():

Format returns a textual representation of the time value formatted according to layout, which defines the format by showing how the reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

would be displayed if it were the value; it serves as an example of the desired output. The same display rules will then be applied to the time value.

Use Toast inside Fragment

When calling Toast inside android fragment:

1. Activity mActivity=this.getActivity();  

2. Toast.makeText(mActivity,"Text you want to display",Toast.LENGTH_SHORT).show();

This works for me.

When is TCP option SO_LINGER (0) required?

The typical reason to set a SO_LINGER timeout of zero is to avoid large numbers of connections sitting in the TIME_WAIT state, tying up all the available resources on a server.

When a TCP connection is closed cleanly, the end that initiated the close ("active close") ends up with the connection sitting in TIME_WAIT for several minutes. So if your protocol is one where the server initiates the connection close, and involves very large numbers of short-lived connections, then it might be susceptible to this problem.

This isn't a good idea, though - TIME_WAIT exists for a reason (to ensure that stray packets from old connections don't interfere with new connections). It's a better idea to redesign your protocol to one where the client initiates the connection close, if possible.

Preventing scroll bars from being hidden for MacOS trackpad users in WebKit/Blink

Another good way of dealing with Lion's hidden scroll bars is to display a prompt to scroll down. It doesn't work with small scroll areas such as text fields but well with large scroll areas and keeps the overall style of the site. One site doing this is http://versusio.com, just check this example page and wait 1.5 seconds to see the prompt:

http://versusio.com/en/samsung-galaxy-nexus-32gb-vs-apple-iphone-4s-64gb

The implementation isn't hard but you have to take care, that you don't display the prompt when the user has already scrolled.

You need jQuery + Underscore and

$(window).scroll to check if the user already scrolled by himself,

_.delay() to trigger a delay before you display the prompt -- the prompt shouldn't be to obtrusive

$('#prompt_div').fadeIn('slow') to fade in your prompt and of course

$('#prompt_div').fadeOut('slow') to fade out when the user scrolled after he saw the prompt

In addition, you can bind Google Analytics events to track user's scrolling behavior.

jQuery: How can I create a simple overlay?

If you're already using jquery, I don't see why you wouldn't also be able to use a lightweight overlay plugin. Other people have already written some nice ones in jquery, so why re-invent the wheel?

Where are logs located?

You should be checking the root directory and not the app directory.

Look in $ROOT/storage/laravel.log not app/storage/laravel.log, where root is the top directory of the project.

Error - replacement has [x] rows, data has [y]

TL;DR ...and late to the party, but that short explanation might help future googlers..

In general that error message means that the replacement doesn't fit into the corresponding column of the dataframe.

A minimal example:

df <- data.frame(a = 1:2); df$a <- 1:3

throws the error

Error in $<-.data.frame(*tmp*, a, value = 1:3) : replacement has 3 rows, data has 2

which is clear, because the vector a of df has 2 entries (rows) whilst the vector we try to replace it has 3 entries (rows).

Slide div left/right using jQuery

$('#hello').hide('slide', {direction: 'left'}, 1000); requires the jQuery-ui library. See http://www.jqueryui.com

Why does Boolean.ToString output "True" and not "true"

How is it not compatible with C#? Boolean.Parse and Boolean.TryParse is case insensitive and the parsing is done by comparing the value to Boolean.TrueString or Boolean.FalseString which are "True" and "False".

EDIT: When looking at the Boolean.ToString method in reflector it turns out that the strings are hard coded so the ToString method is as follows:

public override string ToString()
{
    if (!this)
    {
        return "False";
    }
    return "True";
}

How can I verify if one list is a subset of another?

>>> a = [1, 3, 5]
>>> b = [1, 3, 5, 8]
>>> c = [3, 5, 9]
>>> set(a) <= set(b)
True
>>> set(c) <= set(b)
False

>>> a = ['yes', 'no', 'hmm']
>>> b = ['yes', 'no', 'hmm', 'well']
>>> c = ['sorry', 'no', 'hmm']
>>> 
>>> set(a) <= set(b)
True
>>> set(c) <= set(b)
False

ImageView - have height match width?

If your image view is inside a constraint layout, you can use following constraints to create a square image view make sure to use 1:1 to make square

<ImageView
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:id="@+id/ivImageView"
    app:layout_constraintDimensionRatio="1:1"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintEnd_toEndOf="parent"/>

Access iframe elements in JavaScript

Two ways

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')

OR

window.frames['myIFrame'].contentWindow.document.getElementById('myIFrameElemId')

how to realize countifs function (excel) in R

Given a dataset

df <- data.frame( sex = c('M', 'M', 'F', 'F', 'M'), 
                  occupation = c('analyst', 'dentist', 'dentist', 'analyst', 'cook') )

you can subset rows

df[df$sex == 'M',] # To get all males
df[df$occupation == 'analyst',] # All analysts

etc.

If you want to get number of rows, just call the function nrow such as

nrow(df[df$sex == 'M',])

Excel Date to String conversion

The selected answer did not work for me as Excel was still not converting the text to date. Here is my solution.

Say that in the first column, A, you have data of the type 2016/03/25 21:20:00 but is stored as text. Then in column B write =DATEVALUE(A1) and in column C write =TIMEVALUE(A1).

Then in column D do =B1+C1 to add the numerical formats of the date and time.

Finally, copy the values from D into column E by right clicking in column E and select Paste Special -> Paste as Values.

Highlight the numerical values in column E and change the data type to date - I prefer using a custom date of the form YYYY-MM-DD HH:MM:SS.

JavaScript Number Split into individual digits

('' + 123456789).split('').map( x => +x ).reduce( (a,b) => a+b ) === 45

true

or without map

('' + 123456789).split('').reduce( (a,b) => (+a)+(+b) ) === 45

true

What's the difference between equal?, eql?, ===, and ==?

Equality operators: == and !=

The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.

"koan" == "koan" # Output: => true

The != operator, also known as inequality, is the opposite of ==. It will return true if both objects are not equal and false if they are equal.

"koan" != "discursive thought" # Output: => true

Note that two arrays with the same elements in a different order are not equal, uppercase and lowercase versions of the same letter are not equal and so on.

When comparing numbers of different types (e.g., integer and float), if their numeric value is the same, == will return true.

2 == 2.0 # Output: => true

equal?

Unlike the == operator which tests if both operands are equal, the equal method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby.

Example: a = "zen" b = "zen"

a.object_id  # Output: => 20139460
b.object_id  # Output :=> 19972120

a.equal? b  # Output: => false

In the example above, we have two strings with the same value. However, they are two distinct objects, with different object IDs. Hence, the equal? method will return false.

Let's try again, only this time b will be a reference to a. Notice that the object ID is the same for both variables, as they point to the same object.

a = "zen"
b = a

a.object_id  # Output: => 18637360
b.object_id  # Output: => 18637360

a.equal? b  # Output: => true

eql?

In the Hash class, the eql? method it is used to test keys for equality. Some background is required to explain this. In the general context of computing, a hash function takes a string (or a file) of any size and generates a string or integer of fixed size called hashcode, commonly referred to as only hash. Some commonly used hashcode types are MD5, SHA-1, and CRC. They are used in encryption algorithms, database indexing, file integrity checking, etc. Some programming languages, such as Ruby, provide a collection type called hash table. Hash tables are dictionary-like collections which store data in pairs, consisting of unique keys and their corresponding values. Under the hood, those keys are stored as hashcodes. Hash tables are commonly referred to as just hashes. Notice how the word hashcan refer to a hashcode or to a hash table. In the context of Ruby programming, the word hash almost always refers to the dictionary-like collection.

Ruby provides a built-in method called hash for generating hashcodes. In the example below, it takes a string and returns a hashcode. Notice how strings with the same value always have the same hashcode, even though they are distinct objects (with different object IDs).

"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547
"meditation".hash  # Output: => 1396080688894079547

The hash method is implemented in the Kernel module, included in the Object class, which is the default root of all Ruby objects. Some classes such as Symbol and Integer use the default implementation, others like String and Hash provide their own implementations.

Symbol.instance_method(:hash).owner  # Output: => Kernel
Integer.instance_method(:hash).owner # Output: => Kernel

String.instance_method(:hash).owner  # Output: => String
Hash.instance_method(:hash).owner  # Output: => Hash

In Ruby, when we store something in a hash (collection), the object provided as a key (e.g., string or symbol) is converted into and stored as a hashcode. Later, when retrieving an element from the hash (collection), we provide an object as a key, which is converted into a hashcode and compared to the existing keys. If there is a match, the value of the corresponding item is returned. The comparison is made using the eql? method under the hood.

"zen".eql? "zen"    # Output: => true
# is the same as
"zen".hash == "zen".hash # Output: => true

In most cases, the eql? method behaves similarly to the == method. However, there are a few exceptions. For instance, eql? does not perform implicit type conversion when comparing an integer to a float.

2 == 2.0    # Output: => true
2.eql? 2.0    # Output: => false
2.hash == 2.0.hash  # Output: => false

Case equality operator: ===

Many of Ruby's built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it's implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right "belongs to" or "is a member of" the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses).

String === "zen"  # Output: => true
Range === (1..2)   # Output: => true
Array === [1,2,3]   # Output: => true
Integer === 2   # Output: => true

The same result can be achieved with other methods which are probably best suited for the job. It's usually better to write code that is easy to read by being as explicit as possible, without sacrificing efficiency and conciseness.

2.is_a? Integer   # Output: => true
2.kind_of? Integer  # Output: => true
2.instance_of? Integer # Output: => false

Notice the last example returned false because integers such as 2 are instances of the Fixnum class, which is a subclass of the Integer class. The ===, is_a? and instance_of? methods return true if the object is an instance of the given class or any subclasses. The instance_of method is stricter and only returns true if the object is an instance of that exact class, not a subclass.

The is_a? and kind_of? methods are implemented in the Kernel module, which is mixed in by the Object class. Both are aliases to the same method. Let's verify:

Kernel.instance_method(:kind_of?) == Kernel.instance_method(:is_a?) # Output: => true

Range Implementation of ===

When the === operator is called on a range object, it returns true if the value on the right falls within the range on the left.

(1..4) === 3  # Output: => true
(1..4) === 2.345 # Output: => true
(1..4) === 6  # Output: => false

("a".."d") === "c" # Output: => true
("a".."d") === "e" # Output: => false

Remember that the === operator invokes the === method of the left-hand object. So (1..4) === 3 is equivalent to (1..4).=== 3. In other words, the class of the left-hand operand will define which implementation of the === method will be called, so the operand positions are not interchangeable.

Regexp Implementation of ===

Returns true if the string on the right matches the regular expression on the left. /zen/ === "practice zazen today" # Output: => true # is the same as "practice zazen today"=~ /zen/

Implicit usage of the === operator on case/when statements

This operator is also used under the hood on case/when statements. That is its most common use.

minutes = 15

case minutes
  when 10..20
    puts "match"
  else
    puts "no match"
end

# Output: match

In the example above, if Ruby had implicitly used the double equal operator (==), the range 10..20 would not be considered equal to an integer such as 15. They match because the triple equal operator (===) is implicitly used in all case/when statements. The code in the example above is equivalent to:

if (10..20) === minutes
  puts "match"
else
  puts "no match"
end

Pattern matching operators: =~ and !~

The =~ (equal-tilde) and !~ (bang-tilde) operators are used to match strings and symbols against regex patterns.

The implementation of the =~ method in the String and Symbol classes expects a regular expression (an instance of the Regexp class) as an argument.

"practice zazen" =~ /zen/   # Output: => 11
"practice zazen" =~ /discursive thought/ # Output: => nil

:zazen =~ /zen/    # Output: => 2
:zazen =~ /discursive thought/  # Output: => nil

The implementation in the Regexp class expects a string or a symbol as an argument.

/zen/ =~ "practice zazen"  # Output: => 11
/zen/ =~ "discursive thought" # Output: => nil

In all implementations, when the string or symbol matches the Regexp pattern, it returns an integer which is the position (index) of the match. If there is no match, it returns nil. Remember that, in Ruby, any integer value is "truthy" and nil is "falsy", so the =~ operator can be used in if statements and ternary operators.

puts "yes" if "zazen" =~ /zen/ # Output: => yes
"zazen" =~ /zen/?"yes":"no" # Output: => yes

Pattern-matching operators are also useful for writing shorter if statements. Example:

if meditation_type == "zazen" || meditation_type == "shikantaza" || meditation_type == "kinhin"
  true
end
Can be rewritten as:
if meditation_type =~ /^(zazen|shikantaza|kinhin)$/
  true
end

The !~ operator is the opposite of =~, it returns true when there is no match and false if there is a match.

More info is available at this blog post.

Python dictionary replace values

I think this may help you solve your issue.

Imagine you have a dictionary like this:

dic0 = {0:"CL1", 1:"CL2", 2:"CL3"}

And you want to change values by this one:

dic0to1 = {"CL1":"Unknown1", "CL2":"Unknown2", "CL3":"Unknown3"}

You can use code bellow to change values of dic0 properly respected to dic0t01 without worrying yourself about indexes in dictionary:

for x, y in dic0.items():
    dic0[x] = dic0to1[y]

Now you have:

>>> dic0
{0: 'Unknown1', 1: 'Unknown2', 2: 'Unknown3'}

Error: 0xC0202009 at Data Flow Task, OLE DB Destination [43]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E21

So this error is occurring because you have a value in your source for the AppID column that is not valid for your AppID column in the destination.

Some possible examples:

  • You're trying to insert a 10 character value into an 8 character field.
  • You're trying to insert a value larger than 127 into a tinyint field.
  • You're trying to insert the value 6.4578 into a decimal(5,1) field.

SSIS is governed by metadata, and it expects that you've set up your inputs and outputs properly such that the acceptable values for both are within the same range.

Gradle failed to resolve library in Android Studio

For me follwing steps helped.

It seems to be bug of Android Studio 3.4/3.5 and it was "fixed" by disabling:

File ? Settings ? Experimental ? Gradle ? Only sync the active variant

Format date as dd/MM/yyyy using pipes

I think that it's because the locale is hardcoded into the DatePipe. See this link:

And there is no way to update this locale by configuration right now.

C compile error: "Variable-sized object may not be initialized"

int size=5;
int ar[size ]={O};

/* This  operation gives an error -  
variable sized array may not be 
initialised.  Then just try this. 
*/
int size=5,i;
int ar[size];
for(i=0;i<size;i++)
{
    ar[i]=0;
}

What are the differences between "=" and "<-" assignment operators in R?

x = y = 5 is equivalent to x = (y = 5), because the assignment operators "group" right to left, which works. Meaning: assign 5 to y, leaving the number 5; and then assign that 5 to x.

This is not the same as (x = y) = 5, which doesn't work! Meaning: assign the value of y to x, leaving the value of y; and then assign 5 to, umm..., what exactly?

When you mix the different kinds of assignment operators, <- binds tighter than =. So x = y <- 5 is interpreted as x = (y <- 5), which is the case that makes sense.

Unfortunately, x <- y = 5 is interpreted as (x <- y) = 5, which is the case that doesn't work!

See ?Syntax and ?assignOps for the precedence (binding) and grouping rules.

How to Load an Assembly to AppDomain with all references recursively?

It took me a while to understand @user1996230's answer so I decided to provide a more explicit example. In the below example I make a proxy for an object loaded in another AppDomain and call a method on that object from another domain.

class ProxyObject : MarshalByRefObject
{
    private Type _type;
    private Object _object;

    public void InstantiateObject(string AssemblyPath, string typeName, object[] args)
    {
        assembly = Assembly.LoadFrom(AppDomain.CurrentDomain.BaseDirectory + AssemblyPath); //LoadFrom loads dependent DLLs (assuming they are in the app domain's base directory
        _type = assembly.GetType(typeName);
        _object = Activator.CreateInstance(_type, args); ;
    }

    public void InvokeMethod(string methodName, object[] args)
    {
        var methodinfo = _type.GetMethod(methodName);
        methodinfo.Invoke(_object, args);
    }
}

static void Main(string[] args)
{
    AppDomainSetup setup = new AppDomainSetup();
    setup.ApplicationBase = @"SomePathWithDLLs";
    AppDomain domain = AppDomain.CreateDomain("MyDomain", null, setup);
    ProxyObject proxyObject = (ProxyObject)domain.CreateInstanceFromAndUnwrap(typeof(ProxyObject).Assembly.Location,"ProxyObject");
    proxyObject.InstantiateObject("SomeDLL","SomeType", new object[] { "someArgs});
    proxyObject.InvokeMethod("foo",new object[] { "bar"});
}

Count the number occurrences of a character in a string

Python-3.x:

"aabc".count("a")

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

Mockito - difference between doReturn() and when()

Both approaches behave differently if you use a spied object (annotated with @Spy) instead of a mock (annotated with @Mock):

  • when(...) thenReturn(...) makes a real method call just before the specified value will be returned. So if the called method throws an Exception you have to deal with it / mock it etc. Of course you still get your result (what you define in thenReturn(...))

  • doReturn(...) when(...) does not call the method at all.

Example:

public class MyClass {
     protected String methodToBeTested() {
           return anotherMethodInClass();
     }

     protected String anotherMethodInClass() {
          throw new NullPointerException();
     }
}

Test:

@Spy
private MyClass myClass;

// ...

// would work fine
doReturn("test").when(myClass).anotherMethodInClass();

// would throw a NullPointerException
when(myClass.anotherMethodInClass()).thenReturn("test");

HashMap with multiple values under the same key

Another nice choice is to use MultiValuedMap from Apache Commons. Take a look at the All Known Implementing Classes at the top of the page for specialized implementations.

Example:

HashMap<K, ArrayList<String>> map = new HashMap<K, ArrayList<String>>()

could be replaced with

MultiValuedMap<K, String> map = new MultiValuedHashMap<K, String>();

So,

map.put(key, "A");
map.put(key, "B");
map.put(key, "C");

Collection<String> coll = map.get(key);

would result in collection coll containing "A", "B", and "C".

Set the maximum character length of a UITextField in Swift

My Swift 4 version of shouldChangeCharactersIn

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {

        guard let preText = textField.text as NSString?,
            preText.replacingCharacters(in: range, with: string).count <= MAX_TEXT_LENGTH else {
            return false
        }

        return true
    }

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

Following solution is clean and works perfectly.

  1. Download Elevate zip file from https://www.winability.com/download/Elevate.zip

  2. Inside zip you should find two files: Elevate.exe and Elevate64.exe. (The latter is a native 64-bit compilation, if you require that, although the regular 32-bit version, Elevate.exe, should work fine with both the 32- and 64-bit versions of Windows)

  3. Copy the file Elevate.exe into a folder where Windows can always find it (such as C:/Windows). Or you better you can copy in same folder where you are planning to keep your bat file.

  4. To use it in a batch file, just prepend the command you want to execute as administrator with the elevate command, like this:

 elevate net start service ...

Upgrade to python 3.8 using conda

Open Anaconda Prompt (base):

  1. Update conda:
conda update -n base -c defaults conda
  1. Create new environment with Python 3.8:
conda create -n python38 python=3.8
  1. Activate your new Python 3.8 environment:
conda activate python38
  1. Start Python 3.8:
python

How to redirect in a servlet filter?

Try and check of your ServletResponse response is an instanceof HttpServletResponse like so:

if (response instanceof HttpServletResponse) {
    response.sendRedirect(....);
}

How to remove last n characters from a string in Bash?

In this case you could use basename assuming you have the same suffix on the files you want to remove.

Example:

basename -s .rtf "some string.rtf"

This will return "some string"

If you don't know the suffix, and want it to remove everything after and including the last dot:

f=file.whateverthisis
basename "${f%.*}"

outputs "file"

% means chop, . is what you are chopping, * is wildcard

Convert date to another timezone in JavaScript

Most browsers support the toLocaleString function with arguments, older browsers usually ignore the arguments.

_x000D_
_x000D_
const str = new Date().toLocaleString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(str);
_x000D_
_x000D_
_x000D_

Format specifier %02x

%x is a format specifier that format and output the hex value. If you are providing int or long value, it will convert it to hex value.

%02x means if your provided value is less than two digits then 0 will be prepended.

You provided value 16843009 and it has been converted to 1010101 which a hex value.

command/usr/bin/codesign failed with exit code 1- code sign error

This worked for me. Give it a try:

cd ~/Library/Developer/Xcode/DerivedData
xattr -rc .

Does a `+` in a URL scheme/host/path represent a space?

You can find a nice list of corresponding URL encoded characters on W3Schools.

  • + becomes %2B
  • space becomes %20

Calculating distance between two geographic locations

distanceTo will give you the distance in meters between the two given location ej target.distanceTo(destination).

distanceBetween give you the distance also but it will store the distance in a array of float( results[0]). the doc says If results has length 2 or greater, the initial bearing is stored in results[1]. If results has length 3 or greater, the final bearing is stored in results[2]

hope that this helps

i've used distanceTo to get the distance from point A to B i think that is the way to go.

Is there a better way to run a command N times in bash?

Using a constant:

for ((n=0;n<10;n++)); do
    some_command; 
done

Using a variable (can include math expressions):

x=10; for ((n=0; n < (x / 2); n++)); do some_command; done

MVC 5 Access Claims Identity User Data

Request.GetOwinContext().Authentication.User.Claims

However it is better to add the claims inside the "GenerateUserIdentityAsync" method, especially if regenerateIdentity in the Startup.Auth.cs is enabled.

Build query string for System.Net.HttpClient get

For those who do not want to include System.Web in projects that don't already use it, you can use FormUrlEncodedContent from System.Net.Http and do something like the following:

keyvaluepair version

string query;
using(var content = new FormUrlEncodedContent(new KeyValuePair<string, string>[]{
    new KeyValuePair<string, string>("ham", "Glazed?"),
    new KeyValuePair<string, string>("x-men", "Wolverine + Logan"),
    new KeyValuePair<string, string>("Time", DateTime.UtcNow.ToString()),
})) {
    query = content.ReadAsStringAsync().Result;
}

dictionary version

string query;
using(var content = new FormUrlEncodedContent(new Dictionary<string, string>()
{
    { "ham", "Glaced?"},
    { "x-men", "Wolverine + Logan"},
    { "Time", DateTime.UtcNow.ToString() },
})) {
    query = content.ReadAsStringAsync().Result;
}

Matrix Transpose in Python

If you want to transpose a matrix like A = np.array([[1,2],[3,4]]), then you can simply use A.T, but for a vector like a = [1,2], a.T does not return a transpose! and you need to use a.reshape(-1, 1), as below

import numpy as np
a = np.array([1,2])
print('a.T not transposing Python!\n','a = ',a,'\n','a.T = ', a.T)
print('Transpose of vector a is: \n',a.reshape(-1, 1))

A = np.array([[1,2],[3,4]])
print('Transpose of matrix A is: \n',A.T)

assembly to compare two numbers

As already mentioned, usually the comparison is done through subtraction.
For example, X86 Assembly/Control Flow.

At the hardware level there are special digital circuits for doing the calculations, like adders.

Grouped bar plot in ggplot

First you need to get the counts for each category, i.e. how many Bads and Goods and so on are there for each group (Food, Music, People). This would be done like so:

raw <- read.csv("http://pastebin.com/raw.php?i=L8cEKcxS",sep=",")
raw[,2]<-factor(raw[,2],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,3]<-factor(raw[,3],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)
raw[,4]<-factor(raw[,4],levels=c("Very Bad","Bad","Good","Very Good"),ordered=FALSE)

raw=raw[,c(2,3,4)] # getting rid of the "people" variable as I see no use for it

freq=table(col(raw), as.matrix(raw)) # get the counts of each factor level

Then you need to create a data frame out of it, melt it and plot it:

Names=c("Food","Music","People")     # create list of names
data=data.frame(cbind(freq),Names)   # combine them into a data frame
data=data[,c(5,3,1,2,4)]             # sort columns

# melt the data frame for plotting
data.m <- melt(data, id.vars='Names')

# plot everything
ggplot(data.m, aes(Names, value)) +   
  geom_bar(aes(fill = variable), position = "dodge", stat="identity")

Is this what you're after?

enter image description here

To clarify a little bit, in ggplot multiple grouping bar you had a data frame that looked like this:

> head(df)
  ID Type Annee X1PCE X2PCE X3PCE X4PCE X5PCE X6PCE
1  1    A  1980   450   338   154    36    13     9
2  2    A  2000   288   407   212    54    16    23
3  3    A  2020   196   434   246    68    19    36
4  4    B  1980   111   326   441    90    21    11
5  5    B  2000    63   298   443   133    42    21
6  6    B  2020    36   257   462   162    55    30

Since you have numerical values in columns 4-9, which would later be plotted on the y axis, this can be easily transformed with reshape and plotted.

For our current data set, we needed something similar, so we used freq=table(col(raw), as.matrix(raw)) to get this:

> data
   Names Very.Bad Bad Good Very.Good
1   Food        7   6    5         2
2  Music        5   5    7         3
3 People        6   3    7         4

Just imagine you have Very.Bad, Bad, Good and so on instead of X1PCE, X2PCE, X3PCE. See the similarity? But we needed to create such structure first. Hence the freq=table(col(raw), as.matrix(raw)).

How to change port for jenkins window service when 8080 is being used

If you are running on Redhat, do following

  1. Stop Jenkins
    $sudo service jenkins stop

  2. change port number in /etc/sysconfig/jenkins like i did for port 8081
    JENKINS_PORT="8081"

  3. start Jenkins again
    $sudo service jenkins start

make sure your FW has correct burn rules.

msvcr110.dll is missing from computer error while installing PHP

I had installed PHP in IIS7 on Windows Server 2008 R2 using the Web Platform Installer. It did not work out of the box. I had to install the Visual C++ Redistributable for VS 2012 Update 4 (32bit) as found here http://www.microsoft.com/en-us/download/details.aspx?id=30679 .

In Perl, how do I create a hash whose keys come from a given array?

You might also want to check out Tie::IxHash, which implements ordered associative arrays. That would allow you to do both types of lookups (hash and index) on one copy of your data.

Insert current date in datetime format mySQL

I believe, you need to change your code little bit like follows alongside with your database filed type.

mysql_query("INSERT INTO table (`dateposted`) VALUES ($datetime)");

Hope, will work perfectly.

How to run a Powershell script from the command line and pass a directory as a parameter

you are calling a script file not a command so you have to use -file eg :

powershell -executionPolicy bypass -noexit -file "c:\temp\test.ps1" "c:\test with space"

for PS V2

powershell.exe -noexit &'c:\my scripts\test.ps1'

(check bottom of this technet page http://technet.microsoft.com/en-us/library/ee176949.aspx )

How can I change the font size using seaborn FacetGrid?

You can scale up the fonts in your call to sns.set().

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.1))

enter image description here

sns.set(font_scale=5)  # crazy big
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='big')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.3))

enter image description here

Android Studio: Add jar as library?

I have read all the answers here and they all seem to cover old versions of Android Studio!

With a project created with Android Studio 2.2.3 I just needed to create a libs directory under app and place my jar there. I did that with my file manager, no need to click or edit anything in Android Studio.

Why it works? Open Build / Edit Libraries and Dependencies and you will see:

{include=[*.jar], dir=libs}

How do I change the root directory of an Apache server?

I had made the /var/www to be a soft link to the required directory (for example, /users/username/projects) and things were fine after that.

However, naturally, the original /var/www needs to be deleted - or renamed.

Member '<method>' cannot be accessed with an instance reference

This causes the error:

MyClass aCoolObj = new MyClass();
aCoolObj.MyCoolStaticMethod();

This is the fix:

MyClass.MyCoolStaticMethod();

Explanation:

You can't call a static method from an instance of an object. The whole point of static methods is to not be tied to instances of objects, but instead to persist through all instances of that object, and/or to be used without any instances of the object.

How to change font-color for disabled input?

You can:

input[type="text"][disabled] {
   color: red;
}

changing color of h2

Try CSS:

<h2 style="color:#069">Process Report</h2>

If you have more than one h2 tags which should have the same color add a style tag to the head tag like this:

<style type="text/css">
h2 {
    color:#069;
}
</style>

What command shows all of the topics and offsets of partitions in Kafka?

We're using Kafka 2.11 and make use of this tool - kafka-consumer-groups.

$ rpm -qf /bin/kafka-consumer-groups
confluent-kafka-2.11-1.1.1-1.noarch

For example:

$ kafka-consumer-groups --describe --group logstash | grep -E "TOPIC|filebeat"
Note: This will not show information about old Zookeeper-based consumers.
TOPIC            PARTITION  CURRENT-OFFSET  LOG-END-OFFSET  LAG             CONSUMER-ID                                     HOST             CLIENT-ID
beats_filebeat   0          20003914484     20003914888     404             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   1          19992522286     19992522709     423             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   2          19990597254     19990597637     383             logstash-0-XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX /192.168.1.1   logstash-0
beats_filebeat   7          19991718707     19991719268     561             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   8          20015611981     20015612509     528             logstash-0-YYYYYYYY-YYYY-YYYY-YYYY-YYYYYYYYYYYY /192.168.1.2   logstash-0
beats_filebeat   5          19990536340     19990541331     4991            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   6          19990728038     19990733086     5048            logstash-0-ZZZZZZZZ-ZZZZ-ZZZZ-ZZZZ-ZZZZZZZZZZZZ /192.168.1.3   logstash-0
beats_filebeat   3          19994613945     19994616297     2352            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0
beats_filebeat   4          19990681602     19990684038     2436            logstash-0-AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA /192.168.1.4   logstash-0

Random Tip

NOTE: We use an alias that overloads kafka-consumer-groups like so in our /etc/profile.d/kafka.sh:

alias kafka-consumer-groups="KAFKA_JVM_PERFORMANCE_OPTS=\"-Djava.security.auth.login.config=$HOME/.kafka_client_jaas.conf\"  kafka-consumer-groups --bootstrap-server ${KAFKA_HOSTS} --command-config /etc/kafka/security-enabler.properties"

How do I make a JAR from a .java file?

Here is another fancy way of doing this:

$ ls | grep .java | xargs -I {} javac {} ; jar -cf myJar.jar *.class

Which will grab all the .java files ( ls | grep .java ) from your current directory and compile them into .class (xargs -I {} javac {}) and then create the jar file from the previously compiled classes (jar -cf myJar.jar *.class).

Get value of multiselect box using jQuery or pure JS

You could do like this too.

<form action="ResultsDulith.php" id="intermediate" name="inputMachine[]" multiple="multiple" method="post">
    <select id="selectDuration" name="selectDuration[]" multiple="multiple"> 
        <option value="1 WEEK" >Last 1 Week</option>
        <option value="2 WEEK" >Last 2 Week </option>
        <option value="3 WEEK" >Last 3 Week</option>
         <option value="4 WEEK" >Last 4 Week</option>
          <option value="5 WEEK" >Last 5 Week</option>
           <option value="6 WEEK" >Last 6 Week</option>
    </select>
     <input type="submit"/> 
</form>

Then take the multiple selection from following PHP code below. It print the selected multiple values accordingly.

$shift=$_POST['selectDuration'];

print_r($shift);

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

This kind of logic could be implemented using EXISTS:

CREATE TABLE tab(a INT, b VARCHAR(10));
INSERT INTO tab(a,b) VALUES(1,'a'),(1, NULL),(NULL, 'a'),(2,'b');

Query:

DECLARE @a INT;

--SET @a = 1;    -- specific NOT NULL value
--SET @a = NULL; -- NULL value
--SET @a = -1;   -- all values

SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1');

db<>fiddle demo

It could be extended to contain multiple params:

SELECT *
FROM tab t
WHERE EXISTS(SELECT t.a INTERSECT SELECT @a UNION SELECT @a WHERE @a = '-1')
  AND EXISTS(SELECT t.b INTERSECT SELECT @b UNION SELECT @a WHERE @b = '-1');

Connecting to Oracle Database through C#?

You can use Oracle.ManagedDataAccess NuGet package too (.NET >= 4.0, database >= 10g Release 2).

Is a new line = \n OR \r\n?

\n is used for Unix systems (including Linux, and OSX).

\r\n is mainly used on Windows.

\r is used on really old Macs.

PHP_EOL constant is used instead of these characters for portability between platforms.

Can angularjs routes have optional parameter values?

Actually I think OZ_ may be somewhat correct.

If you have the route '/users/:userId' and navigate to '/users/' (note the trailing /), $routeParams in your controller should be an object containing userId: "" in 1.1.5. So no the paramater userId isn't completely ignored, but I think it's the best you're going to get.

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

Paying tribute to IgorBeaz, you need to stop running the current container. For that you are going to know current CONTAINER ID:

$ docker container ls

You get something like:

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                  NAMES
12a32e8928ef        friendlyhello       "python app.py"     51 seconds ago      Up 50 seconds       0.0.0.0:4000->80/tcp   romantic_tesla   

Then you stop the container by:

$ docker stop 12a32e8928ef

Finally you try to do what you wanted to do, for example:

$ docker run -p 4000:80 friendlyhello

Get distance between two points in canvas

You can do it with pythagoras theorem

If you have two points (x1, y1) and (x2, y2) then you can calculate the difference in x and difference in y, lets call them a and b.

enter image description here

var a = x1 - x2;
var b = y1 - y2;

var c = Math.sqrt( a*a + b*b );

// c is the distance

Telegram Bot - how to get a group chat id?

Using python and telethon it's very easy to get chat id. This solution is best for those who work with telegram API.

If you don't have telethon, run this:

pip install telethon

If you don't have a registered app with telegram, register one: enter image description here The link is this: https://my.telegram.org/

Then run the following code:

from telethon import InteractiveTelegramClient
from telethon.utils.tl_utils import get_display_name

client = InteractiveTelegramClient('session_id', 'YOUR_PHONE_NUMBER', api_id=1234YOURAPI_ID, api_hash='YOUR_API_HASH')

dialog_count = 10
dialogs, entities = client.get_dialogs(dialog_count)
for i, entity in enumerate(entities):
                    i += 1  # 1-based index
                    print('{}. {}. id: {}'.format(i, get_display_name(entity), entity.id))

You may want to send a message to your group so the group show up in top of the list.

Setting individual axis limits with facet_wrap and scales = "free" in ggplot2

Here's some code with a dummy geom_blank layer,

range_act <- range(range(results$act), range(results$pred))

d <- reshape2::melt(results, id.vars = "pred")

dummy <- data.frame(pred = range_act, value = range_act,
                    variable = "act", stringsAsFactors=FALSE)

ggplot(d, aes(x = pred, y = value)) +
  facet_wrap(~variable, scales = "free") +
  geom_point(size = 2.5) + 
  geom_blank(data=dummy) + 
  theme_bw()

enter image description here

MySQL Server has gone away when importing large sql file

As stated here:

Two most common reasons (and fixes) for the MySQL server has gone away (error 2006) are:

Server timed out and closed the connection. How to fix:

  1. check that wait_timeout variable in your mysqld’s my.cnf configuration file is large enough. On Debian: sudo nano /etc/mysql/my.cnf, set wait_timeout = 600 seconds (you can tweak/decrease this value when error 2006 is gone), then sudo /etc/init.d/mysql restart. I didn't check, but the default value for wait_timeout might be around 28800 seconds (8 hours).

  2. Server dropped an incorrect or too large packet. If mysqld gets a packet that is too large or incorrect, it assumes that something has gone wrong with the client and closes the connection. You can increase the maximal packet size limit by increasing the value of max_allowed_packet in my.cnf file. On Debian: sudo nano /etc/mysql/my.cnf, set max_allowed_packet = 64M (you can tweak/decrease this value when error 2006 is gone), then sudo /etc/init.d/mysql restart.

Edit:

Notice that MySQL option files do not have their commands already available as comments (like in php.ini for instance). So you must type any change/tweak in my.cnf or my.ini and place them in mysql/data directory or in any of the other paths, under the proper group of options such as [client], [myslqd], etc. For example:

[mysqld]
wait_timeout = 600
max_allowed_packet = 64M

Then restart the server. To get their values, type in the mysql client:

> select @@wait_timeout;
> select @@max_allowed_packet;

Declare global variables in Visual Studio 2010 and VB.NET

Pretty much the same way that you always have, with "Modules" instead of classes and just use "Public" instead of the old "Global" keyword:

Public Module Module1
    Public Foo As Integer
End Module

Pandas DataFrame concat vs append

I have implemented a tiny benchmark (please find the code on Gist) to evaluate the pandas' concat and append. I updated the code snippet and the results after the comment by ssk08 - thanks alot!

The benchmark ran on a Mac OS X 10.13 system with Python 3.6.2 and pandas 0.20.3.

+--------+---------------------------------+---------------------------------+
|        | ignore_index=False              | ignore_index=True               |
+--------+---------------------------------+---------------------------------+
| size   | append | concat | append/concat | append | concat | append/concat |
+--------+--------+--------+---------------+--------+--------+---------------+
| small  | 0.4635 | 0.4891 | 94.77 %       | 0.4056 | 0.3314 | 122.39 %      |
+--------+--------+--------+---------------+--------+--------+---------------+
| medium | 0.5532 | 0.6617 | 83.60 %       | 0.3605 | 0.3521 | 102.37 %      |
+--------+--------+--------+---------------+--------+--------+---------------+
| large  | 0.9558 | 0.9442 | 101.22 %      | 0.6670 | 0.6749 | 98.84 %       |
+--------+--------+--------+---------------+--------+--------+---------------+

Using ignore_index=False append is slightly faster, with ignore_index=True concat is slightly faster.

tl;dr No significant difference between concat and append.