Programs & Examples On #Scripting languages

0

Does Hibernate create tables in the database automatically

If property hibernate.ddl-auto = update, then it will not create the tables automatically. To create tables automatically, you need to set the property to hibernate.ddl-auto = create

The list of option which is used in the spring boot are

  • validate: validate the schema, makes no changes to the database.

  • update: update the schema.

  • create: creates the schema, destroying previous data.

  • create-drop: drop the schema at the end of the session

  • none: is all other cases

So for the first time you can set it to create and then next time on-wards you should set it to update.

Overriding a JavaScript function while referencing the original

The answer that @Matthew Crumley provides is making use of the immediately invoked function expressions, to close the older 'a' function into the execution context of the returned function. I think this was the best answer, but personally, I would prefer passing the function 'a' as an argument to IIFE. I think it is more understandable.

   var a = (function(original_a) {
        if (condition) {
            return function() {
                new_code();
                original_a();
            }
        } else {
            return function() {
                original_a();
                other_new_code();
            }
        }
    })(a);

How to install requests module in Python 3.4, instead of 2.7

i just reinstalled the pip and it works, but I still wanna know why it happened...

i used the apt-get remove --purge python-pip after I just apt-get install pyhton-pip and it works, but don't ask me why...

OpenCV error: the function is not implemented

Before installing libgtk2.0-dev and pkg-config or libqt4-dev. Make sure that you have uninstalled opencv. You can confirm this by running import cv2 on your python shell. If it fails, then install the needed packages and re-run cmake .

ExpressJS - throw er Unhandled error event

My answers is one of the solution

If you are trying to run angular application with below command

ng serve --open

--open Opens the url in default browser this tag is causing the issue. i don't know what is the purpose after angular 10 version which is not working. I am still analysing

How to run a script as root on Mac OS X?

Or you can access root terminal by typing sudo -s

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

The server directive has to be in the http directive. It should not be outside of it.

Incase if you need detailed information, refer this.

How to display the first few characters of a string in Python?

You can 'slice' a string very easily, just like you'd pull items from a list:

a_string = 'This is a string'

To get the first 4 letters:

first_four_letters = a_string[:4]
>>> 'This'

Or the last 5:

last_five_letters = a_string[-5:]
>>> 'string'

So applying that logic to your problem:

the_string = '416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f '
first_32_chars = the_string[:32]
>>> 416d76b8811b0ddae2fdad8f4721ddbe

View HTTP headers in Google Chrome?

My favorite way in Chrome is clicking on a bookmarklet:

javascript:(function(){function read(url){var r=new XMLHttpRequest();r.open('HEAD',url,false);r.send(null);return r.getAllResponseHeaders();}alert(read(window.location))})();

Put this code in your developer console pad.

Source: http://www.danielmiessler.com/blog/a-bookmarklet-that-displays-http-headers

How to convert color code into media.brush?

For WinRT (Windows Store App)

using Windows.UI;
using Windows.UI.Xaml.Media;

    public static Brush ColorToBrush(string color) // color = "#E7E44D"
    {
        color = color.Replace("#", "");
        if (color.Length == 6)
        {
            return new SolidColorBrush(ColorHelper.FromArgb(255,
                byte.Parse(color.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
                byte.Parse(color.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)));
        }
        else
        {
            return null;
        }
    }

Name [jdbc/mydb] is not bound in this Context

you put resource-ref in the description tag in web.xml

How to bind to a PasswordBox in MVVM

If you want it combined it all in only one control and one command

<PasswordBox Name="PasswordBoxPin" PasswordChar="*">
    <PasswordBox.InputBindings>
        <KeyBinding Key="Return" Command="{Binding AuthentifyEmpCommand}" CommandParameter="{Binding ElementName=PasswordBoxPin}"/>
    </PasswordBox.InputBindings>
</PasswordBox>

And on your Vm (like Konamiman showed)

public void AuthentifyEmp(object obj)
{
    var passwordBox = obj as PasswordBox;
    var password = passwordBox.Password;
}
private RelayCommand _authentifyEmpCommand;
public RelayCommand AuthentifyEmpCommand => _authentifyEmpCommand ?? (_authentifyEmpCommand = new RelayCommand(AuthentifyEmp, null));

EDIT: Based on comments I feel the need to specify that this is a violation of MVVM pattern, use it only if that is not one of your primary concerns.

Excel how to find values in 1 column exist in the range of values in another

This is what you need:

 =NOT(ISERROR(MATCH(<cell in col A>,<column B>, 0)))  ## pseudo code

For the first cell of A, this would be:

 =NOT(ISERROR(MATCH(A2,$B$2:$B$5, 0)))

Enter formula (and drag down) as follows:

enter image description here

You will get:

enter image description here

Access all Environment properties as a Map or Properties object

Working with Spring Boot 2, I needed to do something similar. Most of the answers above work fine, just beware that at various phases in the app lifecycles the results will be different.

For example, after a ApplicationEnvironmentPreparedEvent any properties inside application.properties are not present. However, after a ApplicationPreparedEvent event they are.

Collections.sort with multiple fields

Use Comparator interface with methods introduced in JDK1.8: comparing and thenComparing, or more concrete methods: comparingXXX and thenComparingXXX.

For example, if we wanna sort a list of persons by their id firstly, then age, then name:

            Comparator<Person> comparator = Comparator.comparingLong(Person::getId)
                    .thenComparingInt(Person::getAge)
                    .thenComparing(Person::getName);
            personList.sort(comparator);

Seeking useful Eclipse Java code templates

Nothing fancy for code production - but quite useful for code reviews

I have my template coderev low/med/high do the following

/**
 * Code Review: Low Importance
 * 
 *
 * TODO: Insert problem with code here 
 *
 */

And then in the Tasks view - will show me all of the code review comments I want to bring up during a meeting.

inner join in linq to entities

You can find a whole bunch of Linq examples in visual studio. Just select Help -> Samples, and then unzip the Linq samples.

Open the linq samples solution and open the LinqSamples.cs of the SampleQueries project.

The answer you are looking for is in method Linq14:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

var pairs =
   from a in numbersA
   from b in numbersB
   where a < b
   select new {a, b};

How to solve maven 2.6 resource plugin dependency?

I had exactly the same error. My network is an internal one of a company. I downloaded neon-eclipse for java developpers. These steps worked for me:

1- I downloaded a VPN client on my PC to be totally blinded from the network. Shellfire I used. Use free account and connect to Shellserver.

2- Inside the windows firewall, I added incoming rule for Eclipse. Navigate to where eclipse exe is found.

3- Perform Maven Update project.

Then the project was able to fetch from the maven repository.

hope it helps.

How to upgrade rubygems

To update just one gem (and it's dependencies), do:

    bundle update gem-name

But to update just the gem alone (without updating it's dependencies), do

    bundle update --source gem-name

Commenting out a set of lines in a shell script

if false
then

...code...

fi

false always returns false so this will always skip the code.

How to Split Image Into Multiple Pieces in Python

import os
import sys
from PIL import Image

savedir = r"E:\new_mission _data\test"
filename = r"E:\new_mission _data\test\testing1.png"
img = Image.open(filename)
width, height = img.size
start_pos = start_x, start_y = (0, 0)
cropped_image_size = w, h = (1024,1024)

frame_num = 1
for col_i in range(0, width, w):
    for row_i in range(0, height, h):
        crop = img.crop((col_i, row_i, col_i + w, row_i + h))
        save_to= os.path.join(savedir, "testing_{:02}.png")
        crop.save(save_to.format(frame_num))
        frame_num += 1

PHPMyAdmin Default login password

I just installed Fedora 16 (yea, I know it's old and not supported but, I had the CD burnt :) )

Anyway, coming to the solution, this is what I was required to do:

su -
gedit /etc/phpMyAdmin/config.inc.php

if not found... try phpmyadmin - all small caps.

gedit /etc/phpmyadmin/config.inc.php

Locate

$cfg['Servers'][$i]['AllowNoPassword']

and set it to:

$cfg['Servers'][$i]['AllowNoPassword'] = TRUE;

Save it.

What is secret key for JWT based authentication and how to generate it?

A Json Web Token made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

Now let's do some practices with nodejs:

Configuration file is perfect for storing JWT SECRET data. Using the standard HSA 256 encryption for the signature, the secret should at least be 32 characters long, but the longer the better.

config.env:

JWT_SECRET = my-32-character-ultra-secure-and-ultra-long-secret
//after 90days JWT will no longer be valid, even the signuter is correct and everything is matched.
JWT_EXPIRES_IN=90

now install JWT using command

npm i jsonwebtoken

Example after user signup passing him JWT token so he can stay logged in and get access of resources.

exports.signup = catchAsync(async (req, res, next) => {
  const newUser = await User.create({
    name: req.body.name,
    email: req.body.email,
    password: req.body.password,
    passwordConfirm: req.body.passwordConfirm,
  });
  const token = jwt.sign({ id: newUser._id }, process.env.JWT_SECRET, {
    expiresIn: process.env.JWT_EXPIRES_IN,
  });

  res.status(201).json({
    status: 'success',
    token,
    data: {
      newUser,
    },
  });
});

output: enter image description here

In my opinion, do not take help from a third-party to generate your super-secret key, because you can't say it's secret anymore. Just use your keyboard.

java.io.IOException: Server returned HTTP response code: 500

Change the content-type to "application/x-www-form-urlencoded", i solved the problem.

"Fade" borders in CSS

How to fade borders with CSS:

<div style="border-style:solid;border-image:linear-gradient(red, transparent) 1;border-bottom:0;">Text</div>

Please excuse the inline styles for the sake of demonstration. The 1 property for the border-image is border-image-slice, and in this case defines the border as a single continuous region.

Source: Gradient Borders

How to show Snackbar when Activity starts?

You can try this library. This is a wrapper for android default snackbar. https://github.com/ChathuraHettiarachchi/CSnackBar

Snackbar.with(this,null)
    .type(Type.SUCCESS)
    .message("Profile updated successfully!")
    .duration(Duration.SHORT)
    .show();

This contains multiple types of snackbar and even a customview intergrated snackbar

Automating running command on Linux from Windows using PuTTY

Code:

using System;
using System.Diagnostics;
namespace playSound
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(args[0]);

            Process amixerMediaProcess = new Process();
            amixerMediaProcess.StartInfo.CreateNoWindow = false;
            amixerMediaProcess.StartInfo.UseShellExecute = false;
            amixerMediaProcess.StartInfo.ErrorDialog = false;
            amixerMediaProcess.StartInfo.RedirectStandardOutput = false;
            amixerMediaProcess.StartInfo.RedirectStandardInput = false;
            amixerMediaProcess.StartInfo.RedirectStandardError = false;
            amixerMediaProcess.EnableRaisingEvents = true;

            amixerMediaProcess.StartInfo.Arguments = string.Format("{0}","-ssh username@"+args[0]+" -pw password -m commands.txt");
            amixerMediaProcess.StartInfo.FileName = "plink.exe";
            amixerMediaProcess.Start();


            Console.Write("Presskey to continue . . . ");
            Console.ReadKey(true);
    }
}

}

Sample commands.txt:

ps

Link: https://huseyincakir.wordpress.com/2015/08/27/send-commands-to-a-remote-device-over-puttyssh-putty-send-command-from-command-line/

How to SSH into Docker?

I guess it is possible. You just need to install a SSH server in each container and expose a port on the host. The main annoyance would be maintaining/remembering the mapping of port to container.

However, I have to question why you'd want to do this. SSH'ng into containers should be rare enough that it's not a hassle to ssh to the host then use docker exec to get into the container.

How to create the most compact mapping n ? isprime(n) up to a limit N?

There are many ways to do the primality test.

There isn't really a data structure for you to query. If you have lots of numbers to test, you should probably run a probabilistic test since those are faster, and then follow it up with a deterministic test to make sure the number is prime.

You should know that the math behind the fastest algorithms is not for the faint of heart.

jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)

If you want to get source map file different version, you can use this link http://code.jquery.com/jquery-x.xx.x.min.map

Instead x.xx.x put your version number.

Note: Some links, which you get on this method, may be broken :)

Create a view with ORDER BY clause

As one of the comments in this posting suggests using stored procedures to return the data... I think that is the best answer. In my case what I did is wrote a View to encapsulate the query logic and joins, then I wrote a Stored Proc to return the data sorted and the proc also includes other enhancement features such as parameters for filtering the data.

Now you have to option to query the view, which allows you to manipulate the data further. Or you have the option to execute the stored proc, which is quicker and more precise output.

STORED PROC Execution to query data

exec [olap].[uspUsageStatsLogSessionsRollup]

VIEW Definition

USE [DBA]
GO

/****** Object:  View [olap].[vwUsageStatsLogSessionsRollup]    Script Date: 2/19/2019 10:10:06 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--USE DBA
-- select * from olap.UsageStatsLog_GCOP039 where CubeCommand='[ORDER_HISTORY]'
;

ALTER VIEW [olap].[vwUsageStatsLogSessionsRollup] as
(
    SELECT --*
        t1.UsageStatsLogDate
        , COALESCE(CAST(t1.UsageStatsLogDate AS nvarchar(100)), 'TOTAL- DATES:') AS UsageStatsLogDate_Totals
        , t1.ADUserNameDisplayNEW
        , COALESCE(t1.ADUserNameDisplayNEW, 'TOTAL- USERS:') AS ADUserNameDisplay_Totals
        , t1.CubeCommandNEW
        , COALESCE(t1.CubeCommandNEW, 'TOTAL- CUBES:') AS CubeCommand_Totals
        , t1.SessionsCount
        , t1.UsersCount
        , t1.CubesCount
    FROM
    (
        select 
            CAST(olapUSL.UsageStatsLogTime as date) as UsageStatsLogDate
            , olapUSL.ADUserNameDisplayNEW
            , olapUSL.CubeCommandNEW
            , count(*) SessionsCount
            , count(distinct olapUSL.ADUserNameDisplayNEW) UsersCount
            , count(distinct olapUSL.CubeCommandNEW) CubesCount
        from 
            olap.vwUsageStatsLog olapUSL
        where CubeCommandNEW != '[]'
        GROUP BY CUBE(CAST(olapUSL.UsageStatsLogTime as date), olapUSL.ADUserNameDisplayNEW, olapUSL.CubeCommandNEW )
            ----GROUP BY 
            ------GROUP BY GROUPING SETS
            --------GROUP BY ROLLUP
    ) t1

    --ORDER BY
    --  t1.UsageStatsLogDate DESC
    --  , t1.ADUserNameDisplayNEW
    --  , t1.CubeCommandNEW
)
;


GO

STORED PROC Definition

USE [DBA]
GO

/****** Object:  StoredProcedure [olap].[uspUsageStatsLogSessionsRollup]    Script Date: 2/19/2019 9:39:31 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:      BRIAN LOFTON
-- Create date: 2/19/2019
-- Description: This proceedured returns data from a view with sorted results and an optional date range filter.
-- =============================================
ALTER PROCEDURE [olap].[uspUsageStatsLogSessionsRollup]
    -- Add the parameters for the stored procedure here
    @paramStartDate date = NULL,
    @paramEndDate date = NULL,
    @paramDateTotalExcluded as int = 0,
    @paramUserTotalExcluded as int = 0,
    @paramCubeTotalExcluded as int = 0
AS

BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @varStartDate as date 
        = CASE  
            WHEN @paramStartDate IS NULL THEN '1900-01-01' 
            ELSE @paramStartDate 
        END
    DECLARE @varEndDate as date 
        = CASE  
            WHEN @paramEndDate IS NULL THEN '2100-01-01' 
            ELSE @paramStartDate 
        END

    -- Return Data from this statement
    SELECT 
        t1.UsageStatsLogDate_Totals
        , t1.ADUserNameDisplay_Totals
        , t1.CubeCommand_Totals
        , t1.SessionsCount
        , t1.UsersCount
        , t1.CubesCount
        -- Fields with NULL in the totals
            --  , t1.CubeCommandNEW
            --  , t1.ADUserNameDisplayNEW
            --  , t1.UsageStatsLogDate
    FROM 
        olap.vwUsageStatsLogSessionsRollup t1
    WHERE

        (
            --t1.UsageStatsLogDate BETWEEN @varStartDate AND @varEndDate
            t1.UsageStatsLogDate BETWEEN '1900-01-01' AND '2100-01-01'
            OR t1.UsageStatsLogDate IS NULL
        )
        AND
        (
            @paramDateTotalExcluded=0
            OR (@paramDateTotalExcluded=1 AND UsageStatsLogDate_Totals NOT LIKE '%TOTAL-%')
        )
        AND
        (
            @paramDateTotalExcluded=0
            OR (@paramUserTotalExcluded=1 AND ADUserNameDisplay_Totals NOT LIKE '%TOTAL-%')
        )
        AND
        (
            @paramCubeTotalExcluded=0
            OR (@paramCubeTotalExcluded=1 AND CubeCommand_Totals NOT LIKE '%TOTAL-%')
        )
    ORDER BY
            t1.UsageStatsLogDate DESC
            , t1.ADUserNameDisplayNEW
            , t1.CubeCommandNEW

END


GO

Writing a Python list of lists to a csv file

import csv
with open(file_path, 'a') as outcsv:   
    #configure writer to write standard csv file
    writer = csv.writer(outcsv, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL, lineterminator='\n')
    writer.writerow(['number', 'text', 'number'])
    for item in list:
        #Write item to outcsv
        writer.writerow([item[0], item[1], item[2]])

official docs: http://docs.python.org/2/library/csv.html

Java constant examples (Create a java file having only constants)

Both are valid but I normally choose interfaces. A class (abstract or not) is not needed if there is no implementations.

As an advise, try to choose the location of your constants wisely, they are part of your external contract. Do not put every single constant in one file.

For example, if a group of constants is only used in one class or one method put them in that class, the extended class or the implemented interfaces. If you do not take care you could end up with a big dependency mess.

Sometimes an enumeration is a good alternative to constants (Java 5), take look at: http://docs.oracle.com/javase/1.5.0/docs/guide/language/enums.html

Can I use multiple "with"?

Try:

With DependencedIncidents AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
),
lalala AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
)

And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.

ITextSharp HTML to PDF?

2020 UPDATE:

Converting HTML to PDF is very simple to do now. All you have to do is use NuGet to install itext7 and itext7.pdfhtml. You can do this in Visual Studio by going to "Project" > "Manage NuGet Packages..."

Make sure to include this dependency:

using iText.Html2pdf;

Now literally just paste this one liner and you're done:

HtmlConverter.ConvertToPdf(new FileInfo(@"temp.html"), new FileInfo(@"report.pdf"));

If you're running this example in visual studio, your html file should be in the /bin/Debug directory.

If you're interested, here's a good resource. Also, note that itext7 is licensed under AGPL.

CSS background-image - What is the correct usage?

The path can either be full or relative (of course if the image is from another domain it must be full).

You don't need to use quotes in the URI; the syntax can either be:

background-image: url(image.jpg);

Or

background-image: url("image.jpg");

However, from W3:

Some characters appearing in an unquoted URI, such as parentheses, white space characters, single quotes (') and double quotes ("), must be escaped with a backslash so that the resulting URI value is a URI token: '\(', '\)'.

So in instances such as these it is either necessary to use quotes or double quotes, or escape the characters.

Add custom buttons on Slick Carousel

Why you cant use default CSS classes and add some your style?

.slick-next {
  /*my style*/
  background: url(my-image.png);
}

and

.slick-prev {
  /*my style*/
  background: url(my-image.png);
}

Are you used simple background css property?

in example: http://jsfiddle.net/BNvke/1/

You can use Font Awesome too. Don't forget about CSS pseudo elements.

And don't forget jQuery, you can replace elements, add classes, etc.

How to clear APC cache entries?

If you want to clear apc cache in command : (use sudo if you need it)

APCu

php -r "apcu_clear_cache();" 

APC

php -r "apc_clear_cache(); apc_clear_cache('user'); apc_clear_cache('opcode');"

Sort Pandas Dataframe by Date

sort method has been deprecated and replaced with sort_values. After converting to datetime object using df['Date']=pd.to_datetime(df['Date'])

df.sort_values(by=['Date'])

Note: to sort in-place and/or in a descending order (the most recent first):

df.sort_values(by=['Date'], inplace=True, ascending=False)

Handling multiple IDs in jQuery

Solution:

To your secondary question

var elem1 = $('#elem1'),
    elem2 = $('#elem2'),
    elem3 = $('#elem3');

You can use the variable as the replacement of selector.

elem1.css({'display':'none'}); //will work

In the below case selector is already stored in a variable.

$(elem1,elem2,elem3).css({'display':'none'}); // will not work

Where can I find "make" program for Mac OS X Lion?

After upgrading to Mountain Lion using the NDK, I had the following error:

Cannot find 'make' program. Please install Cygwin make package or define the GNUMAKE variable to point to it

Error was fixed by downloading and using the latest NDK

Fast ceiling of an integer division in C / C++

I would have rather commented but I don't have a high enough rep.

As far as I am aware, for positive arguments and a divisor which is a power of 2, this is the fastest way (tested in CUDA):

//example y=8
q = (x >> 3) + !!(x & 7);

For generic positive arguments only, I tend to do it like so:

q = x/y + !!(x % y);

How to exit if a command failed?

Provided my_command is canonically designed, ie returns 0 when succeeds, then && is exactly the opposite of what you want. You want ||.

Also note that ( does not seem right to me in bash, but I cannot try from where I am. Tell me.

my_command || {
    echo 'my_command failed' ;
    exit 1; 
}

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

TLDR? Try: file = open(filename, encoding='cp437)

Why? When one use:

file = open(filename)
text = file.read()

Python assumes the file uses the same codepage as current environment (cp1252 in case of the opening post) and tries to decode it to its own default UTF-8. If the file contains characters of values not defined in this codepage (like 0x90) we get UnicodeDecodeError. Sometimes we don't know the encoding of the file, sometimes the file's encoding may be unhandled by Python (like e.g. cp790), sometimes the file can contain mixed encodings.

If such characters are unneeded, one may decide to replace them by question marks, with:

file = open(filename, errors='replace')

Another workaround is to use:

file = open(filename, errors='ignore')

The characters are then left intact, but other errors will be masked too.

Quite good solution is to specify the encoding, yet not any encoding (like cp1252), but the one which has ALL characters defined (like cp437):

file = open(filename, encoding='cp437')

Codepage 437 is the original DOS encoding. All codes are defined, so there are no errors while reading the file, no errors are masked out, the characters are preserved (not quite left intact but still distinguishable).

How to execute multiple SQL statements from java

I'm not sure that you want to send two SELECT statements in one request statement because you may not be able to access both ResultSets. The database may only return the last result set.

Multiple ResultSets

However, if you're calling a stored procedure that you know can return multiple resultsets something like this will work

CallableStatement stmt = con.prepareCall(...);
try {
...

boolean results = stmt.execute();

while (results) {
    ResultSet rs = stmt.getResultSet();
    try {
    while (rs.next()) {
        // read the data
    }
    } finally {
        try { rs.close(); } catch (Throwable ignore) {}
    }

    // are there anymore result sets?
    results = stmt.getMoreResults();
}
} finally {
    try { stmt.close(); } catch (Throwable ignore) {}
}

Multiple SQL Statements

If you're talking about multiple SQL statements and only one SELECT then your database should be able to support the one String of SQL. For example I have used something like this on Sybase

StringBuffer sql = new StringBuffer( "SET rowcount 100" );
sql.append( " SELECT * FROM tbl_books ..." );
sql.append( " SET rowcount 0" );

stmt = conn.prepareStatement( sql.toString() );

This will depend on the syntax supported by your database. In this example note the addtional spaces padding the statements so that there is white space between the staments.

Get a UTC timestamp

As wizzard pointed out, the correct method is,

new Date().getTime();

or under Javascript 1.5, just

Date.now();

From the documentation,

The value returned by the getTime method is the number of milliseconds since 1 January 1970 00:00:00 UTC.

If you wanted to make a time stamp without milliseconds you can use,

Math.floor(Date.now() / 1000);

I wanted to make this an answer so the correct method is more visible.

You can compare ExpExc's and Narendra Yadala's results to the method above at http://jsfiddle.net/JamesFM/bxEJd/, and verify with http://www.unixtimestamp.com/ or by running date +%s on a Unix terminal.

How can you dynamically create variables via a while loop?

vars()['meta_anio_2012'] = 'translate'

Correct way to write line to file?

When you said Line it means some serialized characters which are ended to '\n' characters. Line should be last at some point so we should consider '\n' at the end of each line. Here is solution:

with open('YOURFILE.txt', 'a') as the_file:
    the_file.write("Hello")

in append mode after each write the cursor move to new line, if you want to use w mode you should add \n characters at the end of the write() function:

the_file.write("Hello\n")

How can I access "static" class variables within class methods in Python?

bar is your static variable and you can access it using Foo.bar.

Basically, you need to qualify your static variable with Class name.

Import Script from a Parent Directory

If you want to run the script directly, you can:

  1. Add the FolderA's path to the environment variable (PYTHONPATH).
  2. Add the path to sys.path in the your script.

Then:

import module_you_wanted

How to format a floating number to fixed width in Python

See Python 3.x format string syntax:

IDLE 3.5.1   
numbers = ['23.23', '.1233', '1', '4.223', '9887.2']

for x in numbers:  
    print('{0: >#016.4f}'. format(float(x)))  

     23.2300
      0.1233
      1.0000
      4.2230
   9887.2000

Base table or view not found: 1146 Table Laravel 5

I faced this problem too in laravel 5.2 and if declaring the table name doesn't work,it is probably because you have some wrong declaration or mistake in validation code in Request (If you are using one)

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

If you are looking for Swift 3, Follow the steps to achieve this:

func viewDidLoad() {

    //Define Layout here
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()

    //Get device width
    let width = UIScreen.main.bounds.width

    //set section inset as per your requirement.
    layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)

    //set cell item size here 
    layout.itemSize = CGSize(width: width / 2, height: width / 2)

    //set Minimum spacing between 2 items
    layout.minimumInteritemSpacing = 0

    //set minimum vertical line spacing here between two lines in collectionview
    layout.minimumLineSpacing = 0

    //apply defined layout to collectionview
    collectionView!.collectionViewLayout = layout

}

This is verified on Xcode 8.0 with Swift 3.

Get current location of user in Android without using GPS or internet

By getting the getLastKnownLocation you do not actually initiate a fix yourself.

Be aware that this could start the provider, but if the user has ever gotten a location before, I don't think it will. The docs aren't really too clear on this.

According to the docs getLastKnownLocation:

Returns a Location indicating the data from the last known location fix obtained from the given provider. This can be done without starting the provider.

Here is a quick snippet:

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import java.util.List;

public class UtilLocation {
    public static Location getLastKnownLoaction(boolean enabledProvidersOnly, Context context){
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        Location utilLocation = null;
        List<String> providers = manager.getProviders(enabledProvidersOnly);
        for(String provider : providers){

            utilLocation = manager.getLastKnownLocation(provider);
            if(utilLocation != null) return utilLocation;
        }
        return null;
    }
}

You also have to add new permission to AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

ALTER TABLE `{$installer->getTable('sales/quote_payment')}`
ADD `custom_field_one` VARCHAR( 255 ) NOT NULL,
    ADD `custom_field_two` VARCHAR( 255 ) NOT NULL;

Add backtick i.e. " ` " properly. Write your getTable name and column name between backtick.

How to get request url in a jQuery $.get/ajax request

I can't get it to work on $.get() because it has no complete event.

I suggest to use $.ajax() like this,

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

craz demo

Sublime text 3. How to edit multiple lines?

Select multiple lines by clicking first line then holding shift and clicking last line. Then press:

CTRL+SHIFT+L

or on MAC: CMD+SHIFT+L (as per comments)

Alternatively you can select lines and go to SELECTION MENU >> SPLIT INTO LINES.

Now you can edit multiple lines, move cursors etc. for all selected lines.

Enable binary mode while restoring a Database from an SQL dump

Extract your file with Tar archiving tool. you can use it in this way:

tar xf example.sql.gz

IntelliJ IDEA "The selected directory is not a valid home for JDK"

I ended up needing to replace 2017 with 2019, and everything worked fine. /shrug... no other suggestions here worked for me.

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

in my case i was using compile sdk 23 and build tools 25.0.0 just changed compile sdk to 25 and done..

How to prevent downloading images and video files from my website?

Insert a transparent gif 1px x 1px just inside the <body> tag:

<body><img src="route-to-images/blim.gif" class="blimover">

Then style it with this:

.blimover {
  width: 100% !important;
  height: 100% !important;
  z-index: 1000 !important;
  position: absolute !important;
  top: 0 !important;
  left: 0 !important;
}

This will remove any click functionality from a page, but it sure stops people stealing any content!

You can apply the same to a <div>, <section>, <article> etc, just name accordingly and prevent your copy and/or images being ripped.

Nothing stops a screengrab though ... ...

what happens when you type in a URL in browser

First the computer looks up the destination host. If it exists in local DNS cache, it uses that information. Otherwise, DNS querying is performed until the IP address is found.

Then, your browser opens a TCP connection to the destination host and sends the request according to HTTP 1.1 (or might use HTTP 1.0, but normal browsers don't do it any more).

The server looks up the required resource (if it exists) and responds using HTTP protocol, sends the data to the client (=your browser)

The browser then uses HTML parser to re-create document structure which is later presented to you on screen. If it finds references to external resources, such as pictures, css files, javascript files, these are is delivered the same way as the HTML document itself.

AngularJS/javascript converting a date String to date object

This is what I did on the controller

var collectionDate = '2002-04-26T09:00:00';
var date = new Date(collectionDate);
//then pushed all my data into an array $scope.rows which I then used in the directive

I ended up formatting the date to my desired pattern on the directive as follows.

var data = new google.visualization.DataTable();
                    data.addColumn('date', 'Dates');
                    data.addColumn('number', 'Upper Normal');
                    data.addColumn('number', 'Result');
                    data.addColumn('number', 'Lower Normal');
                    data.addRows(scope.rows);
                    var formatDate = new google.visualization.DateFormat({pattern: "dd/MM/yyyy"});
                    formatDate.format(data, 0);
//set options for the line chart
var options = {'hAxis': format: 'dd/MM/yyyy'}

//Instantiate and draw the chart passing in options
var chart = new google.visualization.LineChart($elm[0]);
                    chart.draw(data, options);

This gave me dates ain the format of dd/MM/yyyy (26/04/2002) on the x axis of the chart.

How to schedule a stored procedure in MySQL

I used this query and it worked for me:

CREATE EVENT `exec`
  ON SCHEDULE EVERY 5 SECOND
  STARTS '2013-02-10 00:00:00'
  ENDS '2015-02-28 00:00:00'
  ON COMPLETION NOT PRESERVE ENABLE
DO 
  call delete_rows_links();

How can I remove non-ASCII characters but leave periods and spaces using Python?

You can filter all characters from the string that are not printable using string.printable, like this:

>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'

string.printable on my machine contains:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c

EDIT: On Python 3, filter will return an iterable. The correct way to obtain a string back would be:

''.join(filter(lambda x: x in printable, s))

IIS_IUSRS and IUSR permissions in IIS8

When I added IIS_IUSRS permission to site folder - resources, like js and css, still were unaccessible (error 401, forbidden). However, when I added IUSR - it became ok. So for sure "you CANNOT remove the permissions for IUSR without worrying", dear @Travis G@

How to align entire html body to the center?

http://bluerobot.com/web/css/center1.html

body {
    margin:50px 0; 
    padding:0;
    text-align:center;
}

#Content {
    width:500px;
    margin:0 auto;
    text-align:left;
    padding:15px;
    border:1px dashed #333;
    background-color:#eee;
}

Get path to execution directory of Windows Forms application

Check this out:

Imports System.IO
Imports System.Management

Public Class Form1
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        TextBox1.Text = Path.GetFullPath(Application.ExecutablePath)
        Process.Start(TextBox1.Text)
    End Sub
End Class

How to maintain page scroll position after a jquery event is carried out?

For all who came here from google and are using an anchor element for firing the event, please make sure to void the click likewise:

<a  
href='javascript:void(0)'  
onclick='javascript:whatever causing the page to scroll to the top'  
></a>

Javascript replace all "%20" with a space

Check this out: How to replace all occurrences of a string in JavaScript?

Short answer:

str.replace(/%20/g, " ");

EDIT: In this case you could also do the following:

decodeURI(str)

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

I found solution. It works fine when I throw away next line from form:

enctype="multipart/form-data"

And now it pass all parameters at request ok:

 <form action="/registration" method="post">
   <%-- error messages --%>
   <div class="form-group">
    <c:forEach items="${registrationErrors}" var="error">
    <p class="error">${error}</p>
     </c:forEach>
   </div>

how to generate public key from windows command prompt

If you've got git-bash installed (which comes with Git, Github for Windows, or Visual Studio 2015), then that includes a Windows version of ssh-keygen.

https://help.github.com/articles/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent/

How to modify a CSS display property from JavaScript?

I found the solution.

As said in the EDIT of my answer, a <div> is misfunctioning in a <table>. So I wrote this code instead :

<tr id="hidden" style="display:none;">
    <td class="depot_table_left">
        <label for="sexe">Sexe</label>
    </td>
    <td>
        <select type="text" name="sexe">
            <option value="1">Sexe</option>
            <option value="2">Joueur</option>
            <option value="3">Joueuse</option>
        </select>
    </td>
</tr>

And this is working fine.

Thanks everybody ;)

Reading int values from SqlDataReader

Call ToString() instead of casting the reader result.

reader[0].ToString();
reader[1].ToString();
// etc...

And if you want to fetch specific data type values (int in your case) try the following:

reader.GetInt32(index);

Selecting last element in JavaScript array

var last = function( obj, key ) { 
    var a = obj[key];
    return a[a.length - 1];
};

last(loc, 'f096012e-2497-485d-8adb-7ec0b9352c52');

Is it possible in Java to access private fields via reflection

Yes, it absolutely is - assuming you've got the appropriate security permissions. Use Field.setAccessible(true) first if you're accessing it from a different class.

import java.lang.reflect.*;

class Other
{
    private String str;
    public void setStr(String value)
    {
        str = value;
    }
}

class Test
{
    public static void main(String[] args)
        // Just for the ease of a throwaway test. Don't
        // do this normally!
        throws Exception
    {
        Other t = new Other();
        t.setStr("hi");
        Field field = Other.class.getDeclaredField("str");
        field.setAccessible(true);
        Object value = field.get(t);
        System.out.println(value);
    }
}

And no, you shouldn't normally do this... it's subverting the intentions of the original author of the class. For example, there may well be validation applied in any situation where the field can normally be set, or other fields may be changed at the same time. You're effectively violating the intended level of encapsulation.

How to make a back-to-top button using CSS and HTML only?

<a id="topbutton" href="#top">first page </a>

Basically what you have to do is replace the " #top" with the id of the first section or your page, or it could be the nav... Any id locate in the first part of the page and then try to set some style with css!

Git Commit Messages: 50/72 Formatting

I'd agree it is interesting to propose a particular style of working. However, unless I have the chance to set the style, I usually follow what's been done for consistency.

Taking a look at the Linux Kernel Commits, the project that started git if you like, http://git.kernel.org/?p=linux/kernel/git/torvalds/linux-2.6.git;a=commit;h=bca476139d2ded86be146dae09b06e22548b67f3, they don't follow the 50/72 rule. The first line is 54 characters.

I would say consistency matters. Set up proper means of identifying users who've made commits (user.name, user.email - especially on internal networks. User@OFFICE-1-PC-10293982811111 isn't a useful contact address). Depending on the project, make the appropriate detail available in the commit. It's hard to say what that should be; it might be tasks completed in a development process, then details of what's changed.

I don't believe users should use git one way because certain interfaces to git treat the commits in certain ways.

I should also note there are other ways to find commits. For a start, git diff will tell you what's changed. You can also do things like git log --pretty=format:'%T %cN %ce' to format the options of git log.

Objective C - Assign, Copy, Retain

  1. assign

    • assign is a default property attribute
    • assign is a property attribute tells the compiler how to synthesize the property’s setter implementation
  2. copy:

    • copy is required when the object is mutable
    • copy returns an object which you must explicitly release (e.g., in dealloc) in non-garbage collected environments
    • you need to release the object when finished with it because you are retaining the copy
  3. retain:

    • specifies the new value should be sent “-retain” on assignment and the old value sent “-release”
    • if you write retain it will auto work like strong
    • Methods like “alloc” include an implicit “retain”

Default value to a parameter while passing by reference in C++

There still is the old C way of providing optional arguments: a pointer that can be NULL when not present:

void write( int *optional = 0 ) {
    if (optional) *optional = 5;
}

How to disable Compatibility View in IE

In JSF I used:

<h:head>
    <f:facet name="first">
        <meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
    </f:facet>

    <!-- ... other meta tags ... -->

</h:head>

SSL Error When installing rubygems, Unable to pull data from 'https://rubygems.org/

In my case, the Ubuntu CA certificates were out of date. I fixed it by running:

 sudo update-ca-certificates

What is the meaning of "operator bool() const"

Another common use is for std containers to do equality comparison on key values inside custom objects

class Foo
{
    public: int val;
};

class Comparer { public:
bool operator () (Foo& a, Foo&b) const {
return a.val == b.val; 
};

class Blah
{
std::set< Foo, Comparer > _mySet;
};

How to make spring inject value into a static field

As these answers are old, I found this alternative. It is very clean and works with just java annotations:

To fix it, create a “none static setter” to assign the injected value for the static variable. For example :

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class GlobalValue {

public static String DATABASE;

@Value("${mongodb.db}")
public void setDatabase(String db) {
    DATABASE = db;
}
}

https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

How to find what code is run by a button or element in Chrome using Developer Tools

You can use findHandlersJS

You can find the handler by doing in the chrome console:

findEventHandlers("click", "img.envio")

You'll get the following information printed in chrome's console:

  • element
    The actual element where the event handler was registered in
  • events
    Array with information about the jquery event handlers for the event type that we are interested in (e.g. click, change, etc)
  • handler
    Actual event handler method that you can see by right clicking it and selecting Show function definition
  • selector
    The selector provided for delegated events. It will be empty for direct events.
  • targets
    List with the elements that this event handler targets. For example, for a delegated event handler that is registered in the document object and targets all buttons in a page, this property will list all buttons in the page. You can hover them and see them highlighted in chrome.

More info here and you can try it in this example site here.

Installing PHP Zip Extension

I tried changing the repository list with:

http://security.ubuntu.com/ubuntu bionic-security main universe http://archive.ubuntu.com/ubuntu bionic main restricted universe

But none of them seem to work, but I finally found a repository that works running the following command

add-apt-repository ppa:ondrej/php

And then updating and installing normally the package using apt-get

As you can see it's installed at last.

How to convert BigDecimal to Double in Java?

You need to use the doubleValue() method to get the double value from a BigDecimal object.

BigDecimal bd; // the value you get
double d = bd.doubleValue(); // The double you want

How to remove all null elements from a ArrayList or String Array?

Using Java 8, you can do this using stream() and filter()

tourists = tourists.stream().filter(t -> t != null).collect(Collectors.toList())

or

tourists = tourists.stream().filter(Objects::nonNull).collect(Collectors.toList())

For more info : Java 8 - Streams

How can I fetch all items from a DynamoDB table without specifying the primary key?

A simple code to list all the Items from DynamoDB Table by specifying the region of AWS Service.

import boto3

dynamodb = boto3.resource('dynamodb', region_name='ap-south-1')
table = dynamodb.Table('puppy_store')
response = table.scan()
items = response['Items']

# Prints All the Items at once
print(items)

# Prints Items line by line
for i, j in enumerate(items):
    print(f"Num: {i} --> {j}")

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

while(cap.isOpened()):

    ret, img = cap.read()
    print img
    if img==None:   #termino los frames?
        break   #si, entonces terminar programa
    #gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    cv2.imshow('img2',img)

Add Marker function with Google Maps API

THis is other method
You can also use setCenter method with add new marker

check below code

$('#my_map').gmap3({
      action: 'setCenter',
      map:{
         options:{
          zoom: 10
         }
      },
      marker:{
         values:
          [
            {latLng:[position.coords.latitude, position.coords.longitude], data:"Netherlands !"}
          ]
      }
   });

How to use shared memory with Linux in C

try this code sample, I tested it, source: http://www.makelinux.net/alp/035

#include <stdio.h> 
#include <sys/shm.h> 
#include <sys/stat.h> 

int main () 
{
  int segment_id; 
  char* shared_memory; 
  struct shmid_ds shmbuffer; 
  int segment_size; 
  const int shared_segment_size = 0x6400; 

  /* Allocate a shared memory segment.  */ 
  segment_id = shmget (IPC_PRIVATE, shared_segment_size, 
                 IPC_CREAT | IPC_EXCL | S_IRUSR | S_IWUSR); 
  /* Attach the shared memory segment.  */ 
  shared_memory = (char*) shmat (segment_id, 0, 0); 
  printf ("shared memory attached at address %p\n", shared_memory); 
  /* Determine the segment's size. */ 
  shmctl (segment_id, IPC_STAT, &shmbuffer); 
  segment_size  =               shmbuffer.shm_segsz; 
  printf ("segment size: %d\n", segment_size); 
  /* Write a string to the shared memory segment.  */ 
  sprintf (shared_memory, "Hello, world."); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Reattach the shared memory segment, at a different address.  */ 
  shared_memory = (char*) shmat (segment_id, (void*) 0x5000000, 0); 
  printf ("shared memory reattached at address %p\n", shared_memory); 
  /* Print out the string from shared memory.  */ 
  printf ("%s\n", shared_memory); 
  /* Detach the shared memory segment.  */ 
  shmdt (shared_memory); 

  /* Deallocate the shared memory segment.  */ 
  shmctl (segment_id, IPC_RMID, 0); 

  return 0; 
} 

Angular ng-click with call to a controller function not working

You should probably use the ngHref directive along with the ngClick:

 <a ng-href='#here' ng-click='go()' >click me</a>

Here is an example: http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

<body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    {{msg}}
    <a ng-href='#here' ng-click='go()' >click me</a>
    <div style='height:1000px'>

      <a id='here'></a>

    </div>
     <h1>here</h1>
  </body>

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';

  $scope.go = function() {

    $scope.msg = 'clicked';
  }
});

I don't know if this will work with the library you are using but it will at least let you link and use the ngClick function.

** Update **

Here is a demo of the set and get working fine with a service.

http://plnkr.co/edit/FSH0tP0YBFeGwjIhKBSx?p=preview

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, sharedProperties) {
  $scope.name = 'World';

  $scope.go = function(item) {
    sharedProperties.setListName(item);


  }

  $scope.getItem = function() {

    $scope.msg = sharedProperties.getListName();
  }
});

app.service('sharedProperties', function () {
    var list_name = '';

    return {

        getListName: function() {
            return list_name;
        },
        setListName: function(name) {
            list_name = name;
        }
    };


});

* Edit *

Please review https://github.com/centralway/lungo-angular-bridge which talks about how to use lungo and angular. Also note that if your page is completely reloading when browsing to another link, you will need to persist your shared properties into localstorage and/or a cookie.

How to detect the end of loading of UITableView

Using private API:

@objc func tableViewDidFinishReload(_ tableView: UITableView) {
    print(#function)
    cellsAreLoaded = true
}

Using public API:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // cancel the perform request if there is another section
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(tableViewDidLoadRows:) object:tableView];

    // create a perform request to call the didLoadRows method on the next event loop.
    [self performSelector:@selector(tableViewDidLoadRows:) withObject:tableView afterDelay:0];

    return [self.myDataSource numberOfRowsInSection:section];
}

// called after the rows in the last section is loaded
-(void)tableViewDidLoadRows:(UITableView*)tableView{
    self.cellsAreLoaded = YES;
}

A possible better design is to add the visible cells to a set, then when you need to check if the table is loaded you can instead do a for loop around this set, e.g.

var visibleCells = Set<UITableViewCell>()

override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    visibleCells.insert(cell)
}

override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
    visibleCells.remove(cell)
}

// example property you want to show on a cell that you only want to update the cell after the table is loaded. cellForRow also calls configure too for the initial state.
var count = 5 {
    didSet {
        for cell in visibleCells {
            configureCell(cell)
        }
    }
}

Sql error on update : The UPDATE statement conflicted with the FOREIGN KEY constraint

I would not change the constraints, instead, you can insert a new record in the table_1 with the primary key (id_no = 7008255601088). This is nothing but a duplicate row of the id_no = 8008255601088. so now patient_address with the foreign key constraint (id_no = 8008255601088) can be updated to point to the record with the new ID(ID which needed to be updated), which is updating the id_no to id_no =7008255601088.

Then you can remove the initial primary key row with id_no =7008255601088.

Three steps include:

  1. Insert duplicate row for new id_no
  2. Update Patient_address to point to new duplicate row
  3. Remove the row with old id_no

Get the string representation of a DOM node

Try

new XMLSerializer().serializeToString(element);

XPath: select text node

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

Both should work.

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2

How to increase font size in a plot in R?

In case you want to increase the font of the labels of the histogram when setting labels=TRUE

bp=hist(values, labels = FALSE, 
 main='Histogram',
 xlab='xlab',ylab='ylab',  cex.main=2, cex.lab=2,cex.axis=2)

text(x=bp$mids, y=bp$counts, labels=bp$counts ,cex=2,pos=3)

Shell Script: How to write a string to file and to stdout on console?

You can use >> to print in another file.

echo "hello" >> logfile.txt

enum to string in modern C++11 / C++14 / C++17 and future C++20

I am not sure if this approach is already covered in one of the other answers (actually it is, see below). I encountered the problem many times and didnt find a solution that did not use obfuscated macros or third party libraries. Hence I decided to write my own obfuscated macro version.

What I want to enable is the equivalent of

enum class test1 { ONE, TWO = 13, SIX };

std::string toString(const test1& e) { ... }

int main() {
    test1 x;
    std::cout << toString(x) << "\n";
    std::cout << toString(test1::TWO) << "\n";
    std::cout << static_cast<std::underlying_type<test1>::type>(test1::TWO) << "\n";
    //std::cout << toString(123);// invalid
}

which should print

ONE
TWO
13

I am not a fan of macros. However, unless c++ natively supports converting enums to strings one has to use some sort of code generation and/or macros (and I doubt this will happen too soon). I am using a X-macro:

// x_enum.h
#include <string>
#include <map>
#include <type_traits>
#define x_begin enum class x_name {
#define x_val(X) X
#define x_value(X,Y) X = Y
#define x_end };
x_enum_def
#undef x_begin
#undef x_val
#undef x_value
#undef x_end

#define x_begin inline std::string toString(const x_name& e) { \
                static std::map<x_name,std::string> names = { 
#define x_val(X)      { x_name::X , #X }
#define x_value(X,Y)  { x_name::X , #X }
#define x_end }; return names[e]; }
x_enum_def
#undef x_begin
#undef x_val
#undef x_value
#undef x_end
#undef x_name
#undef x_enum_def

Most of it is defining and undefining symbols that the user will pass as parameter to the X-marco via an include. The usage is like this

#define x_name test1
#define x_enum_def x_begin x_val(ONE) , \
                           x_value(TWO,13) , \
                           x_val(SIX) \
                   x_end
#include "x_enum.h"

Live Demo

Note that I didnt include choosing the underlying type yet. I didnt need it so far, but it should be straight forward to modify to code to enable that.

Only after writing this I realized that it is rather similar to eferions answer. Maybe I read it before and maybe it was the main source of inspiration. I was always failing in understanding X-macros until I wrote my own ;).

How do I detect what .NET Framework versions and service packs are installed?

In Windows 7 (it should work for Windows 8 also, but I haven't tested it):

Go to a command prompt

Steps to go to a command prompt:

  1. Click Start Menu
  2. In Search Box, type "cmd" (without quotes)
  3. Open cmd.exe

In cmd, type this command

wmic /namespace:\\root\cimv2 path win32_product where "name like '%%.NET%%'" get version

This gives the latest version of NET Framework installed.

One can also try Raymond.cc Utilties for the same.

Get random boolean in Java

Why not use the Random class, which has a method nextBoolean:

import java.util.Random;

/** Generate 10 random booleans. */
public final class MyProgram {

  public static final void main(String... args){

    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      boolean randomBool = randomGenerator.nextBoolean();
      System.out.println("Generated : " + randomBool);
    }
  }
}

How to check if keras tensorflow backend is GPU or CPU version?

According to the documentation.

If you are running on the TensorFlow or CNTK backends, your code will automatically run on GPU if any available GPU is detected.

You can check what all devices are used by tensorflow by -

from tensorflow.python.client import device_lib
print(device_lib.list_local_devices())

Also as suggested in this answer

import tensorflow as tf
sess = tf.Session(config=tf.ConfigProto(log_device_placement=True))

This will print whether your tensorflow is using a CPU or a GPU backend. If you are running this command in jupyter notebook, check out the console from where you have launched the notebook.

If you are sceptic whether you have installed the tensorflow gpu version or not. You can install the gpu version via pip.

pip install tensorflow-gpu

Removing an item from a select box

JavaScript

_x000D_
_x000D_
function removeOptionsByValue(selectBox, value)_x000D_
{_x000D_
  for (var i = selectBox.length - 1; i >= 0; --i) {_x000D_
    if (selectBox[i].value == value) {_x000D_
      selectBox.remove(i);_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
function addOption(selectBox, text, value, selected)_x000D_
{_x000D_
  selectBox.add(new Option(text, value || '', false, selected || false));_x000D_
}_x000D_
_x000D_
var selectBox = document.getElementById('selectBox');_x000D_
_x000D_
removeOptionsByValue(selectBox, 'option3');_x000D_
addOption(selectBox, 'option5', 'option5', true);
_x000D_
<select name="selectBox" id="selectBox">_x000D_
    <option value="option1">option1</option>_x000D_
    <option value="option2">option2</option>_x000D_
    <option value="option3">option3</option>_x000D_
    <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
jQuery(function($) {_x000D_
  $.fn.extend({_x000D_
    remove_options: function(value) {_x000D_
      return this.each(function() {_x000D_
        $('> option', this)_x000D_
          .filter(function() {_x000D_
            return this.value == value;_x000D_
          })_x000D_
          .remove();_x000D_
      });_x000D_
    },_x000D_
    add_option: function(text, value, selected) {_x000D_
      return this.each(function() {_x000D_
        $(this).append(new Option(text, value || '', false, selected || false));_x000D_
      });_x000D_
    }_x000D_
  });_x000D_
});_x000D_
_x000D_
jQuery(function($) {_x000D_
  $('#selectBox')_x000D_
    .remove_options('option3')_x000D_
    .add_option('option5', 'option5', true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="selectBox" id="selectBox">_x000D_
    <option value="option1">option1</option>_x000D_
    <option value="option2">option2</option>_x000D_
    <option value="option3">option3</option>_x000D_
    <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

How do I convert an integer to binary in JavaScript?

This answer attempts to address inputs with an absolute value in the range of 214748364810 (231) – 900719925474099110 (253-1).


In JavaScript, numbers are stored in 64-bit floating point representation, but bitwise operations coerce them to 32-bit integers in two's complement format, so any approach which uses bitwise operations restricts the range of output to -214748364810 (-231) – 214748364710 (231-1).

However, if bitwise operations are avoided and the 64-bit floating point representation is preserved by using only mathematical operations, we can reliably convert any safe integer to 64-bit two's complement binary notation by sign-extending the 53-bit twosComplement:

_x000D_
_x000D_
function toBinary (value) {
  if (!Number.isSafeInteger(value)) {
    throw new TypeError('value must be a safe integer');
  }

  const negative = value < 0;
  const twosComplement = negative ? Number.MAX_SAFE_INTEGER + value + 1 : value;
  const signExtend = negative ? '1' : '0';

  return twosComplement.toString(2).padStart(53, '0').padStart(64, signExtend);
}

function format (value) {
  console.log(value.toString().padStart(64));
  console.log(value.toString(2).padStart(64));
  console.log(toBinary(value));
}

format(8);
format(-8);
format(2**33-1);
format(-(2**33-1));
format(2**53-1);
format(-(2**53-1));
format(2**52);
format(-(2**52));
format(2**52+1);
format(-(2**52+1));
_x000D_
.as-console-wrapper{max-height:100%!important}
_x000D_
_x000D_
_x000D_

For older browsers, polyfills exist for the following functions and values:

As an added bonus, you can support any radix (2–36) if you perform the two's complement conversion for negative numbers in ?64 / log2(radix)? digits by using BigInt:

_x000D_
_x000D_
function toRadix (value, radix) {
  if (!Number.isSafeInteger(value)) {
    throw new TypeError('value must be a safe integer');
  }

  const digits = Math.ceil(64 / Math.log2(radix));
  const twosComplement = value < 0
    ? BigInt(radix) ** BigInt(digits) + BigInt(value)
    : value;

  return twosComplement.toString(radix).padStart(digits, '0');
}

console.log(toRadix(0xcba9876543210, 2));
console.log(toRadix(-0xcba9876543210, 2));
console.log(toRadix(0xcba9876543210, 16));
console.log(toRadix(-0xcba9876543210, 16));
console.log(toRadix(0x1032547698bac, 2));
console.log(toRadix(-0x1032547698bac, 2));
console.log(toRadix(0x1032547698bac, 16));
console.log(toRadix(-0x1032547698bac, 16));
_x000D_
.as-console-wrapper{max-height:100%!important}
_x000D_
_x000D_
_x000D_

If you are interested in my old answer that used an ArrayBuffer to create a union between a Float64Array and a Uint16Array, please refer to this answer's revision history.

How can I check if a string represents an int, without using try/except?

I suggest the following:

import ast

def is_int(s):
    return isinstance(ast.literal_eval(s), int)

From the docs:

Safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None.

I should note that this will raise a ValueError exception when called against anything that does not constitute a Python literal. Since the question asked for a solution without try/except, I have a Kobayashi-Maru type solution for that:

from ast import literal_eval
from contextlib import suppress

def is_int(s):
    with suppress(ValueError):
        return isinstance(literal_eval(s), int)
    return False

¯\_(?)_/¯

Pass Javascript Array -> PHP

Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:

function obj2url(prefix, obj) {
        var args=new Array();
        if(typeof(obj) == 'object'){
            for(var i in obj)
                args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
        }
        else
            args[args.length]=prefix+'='+encodeURIComponent(obj);
        return args.join('&');
    }

prefix is a parameter name.

EDIT:

var a = {
    one: two,
    three: four
};

alert('/script.php?'+obj2url('a', a)); 

Will produce

/script.php?a[one]=two&a[three]=four

which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.

Can't bind to 'routerLink' since it isn't a known property

I totally chose another way for this method.

app.component.ts

import { Router } from '@angular/router';
export class AppComponent {

   constructor(
        private router: Router,
    ) {}

    routerComment() {
        this.router.navigateByUrl('/marketing/social/comment');
    }
}

app.component.html

<button (click)="routerComment()">Router Link </button>

Is there a destructor for Java?

Just thinking about the original question... which, I think we can conclude from all the other learned answers, and also from Bloch's essential Effective Java, item 7, "Avoid finalizers", seeks the solution to a legitimate question in a manner which is inappropriate to the Java language...:

... wouldn't a pretty obvious solution to do what the OP actually wants be to keep all your objects which need to be reset in a sort of "playpen", to which all other non-resettable objects have references only through some sort of accessor object...

And then when you need to "reset" you disconnect the existing playpen and make a new one: all the web of objects in the playpen is cast adrift, never to return, and one day to be collected by the GC.

If any of these objects are Closeable (or not, but have a close method) you could put them in a Bag in the playpen as they are created (and possibly opened), and the last act of the accessor before cutting off the playpen would be to go through all the Closeables closing them... ?

The code would probably look something like this:

accessor.getPlaypen().closeCloseables();
accessor.setPlaypen( new Playpen() );

closeCloseables would probably be a blocking method, probably involving a latch (e.g. CountdownLatch), to deal with (and wait as appropriate for) any Runnables/Callables in any threads specific to the Playpen to be ended as appropriate, in particular in the JavaFX thread.

Pandas - replacing column values

Yes, you are using it incorrectly, Series.replace() is not inplace operation by default, it returns the replaced dataframe/series, you need to assign it back to your dataFrame/Series for its effect to occur. Or if you need to do it inplace, you need to specify the inplace keyword argument as True Example -

data['sex'].replace(0, 'Female',inplace=True)
data['sex'].replace(1, 'Male',inplace=True)

Also, you can combine the above into a single replace function call by using list for both to_replace argument as well as value argument , Example -

data['sex'].replace([0,1],['Female','Male'],inplace=True)

Example/Demo -

In [10]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [11]: data['sex'].replace([0,1],['Female','Male'],inplace=True)

In [12]: data
Out[12]:
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

You can also use a dictionary, Example -

In [15]: data = pd.DataFrame([[1,0],[0,1],[1,0],[0,1]], columns=["sex", "split"])

In [16]: data['sex'].replace({0:'Female',1:'Male'},inplace=True)

In [17]: data
Out[17]:
      sex  split
0    Male      0
1  Female      1
2    Male      0
3  Female      1

How can I parse a CSV string with JavaScript, which contains comma in data?

No regexp, readable, and according to https://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules:

function csv2arr(str: string) {
    let line = ["",];
    const ret = [line,];
    let quote = false;

    for (let i = 0; i < str.length; i++) {
        const cur = str[i];
        const next = str[i + 1];

        if (!quote) {
            const cellIsEmpty = line[line.length - 1].length === 0;
            if (cur === '"' && cellIsEmpty) quote = true;
            else if (cur === ",") line.push("");
            else if (cur === "\r" && next === "\n") { line = ["",]; ret.push(line); i++; }
            else if (cur === "\n" || cur === "\r") { line = ["",]; ret.push(line); }
            else line[line.length - 1] += cur;
        } else {
            if (cur === '"' && next === '"') { line[line.length - 1] += cur; i++; }
            else if (cur === '"') quote = false;
            else line[line.length - 1] += cur;
        }
    }
    return ret;
}

Return a "NULL" object if search result not found

The reason that you can't return NULL here is because you've declared your return type as Attr&. The trailing & makes the return value a "reference", which is basically a guaranteed-not-to-be-null pointer to an existing object. If you want to be able to return null, change Attr& to Attr*.

Inputting a default image in case the src attribute of an html <img> is not valid?

Google threw out this page to the "image fallback html" keywords, but because non of the above helped me, and I was looking for a "svg fallback support for IE below 9", I kept on searching and this is what I found:

<img src="base-image.svg" alt="picture" />
<!--[if (lte IE 8)|(!IE)]><image src="fallback-image.png" alt="picture" /><![endif]-->

It might be off-topic, but it resolved my own issue and it might help someone else too.

java.lang.OutOfMemoryError: Java heap space in Maven

For those new to Maven (like me) here is the whole config that goes in the build section of your pom. Cheers.

<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.19</version>
        <configuration>
            <argLine>-Xmx1024m</argLine>
        </configuration>
      </plugin>
    </plugins>
  </build>

How to get Maven project version to the bash command line

This is by far the easiest bash cut and paste solution:

VERSION=$(mvn -Dexec.executable='echo' -Dexec.args='${project.version}' --non-recursive exec:exec -q)
echo $VERSION

it echoes

1.4

How to print environment variables to the console in PowerShell?

Prefix the variable name with env:

$env:path

For example, if you want to print the value of environment value "MINISHIFT_USERNAME", then command will be:

$env:MINISHIFT_USERNAME

You can also enumerate all variables via the env drive:

Get-ChildItem env:

How to sort the files according to the time stamp in unix?

File modification:

ls -t

Inode change:

ls -tc

File access:

ls -tu

"Newest" one at the bottom:

ls -tr

None of this is a creation time. Most Unix filesystems don't support creation timestamps.

SQL Query - how do filter by null or not null

How about statusid = statusid. Null is never equal to null.

How do servlets work? Instantiation, sessions, shared variables and multithreading

Sessions

enter image description here enter image description here

In short: the web server issues a unique identifier to each visitor on his first visit. The visitor must bring back that ID for him to be recognised next time around. This identifier also allows the server to properly segregate objects owned by one session against that of another.

Servlet Instantiation

If load-on-startup is false:

enter image description here enter image description here

If load-on-startup is true:

enter image description here enter image description here

Once he's on the service mode and on the groove, the same servlet will work on the requests from all other clients.

enter image description here

Why isn't it a good idea to have one instance per client? Think about this: Will you hire one pizza guy for every order that came? Do that and you'd be out of business in no time.

It comes with a small risk though. Remember: this single guy holds all the order information in his pocket: so if you're not cautious about thread safety on servlets, he may end up giving the wrong order to a certain client.

How can I force division to be floating point? Division keeps rounding down to 0?

You can cast to float by doing c = a / float(b). If the numerator or denominator is a float, then the result will be also.


A caveat: as commenters have pointed out, this won't work if b might be something other than an integer or floating-point number (or a string representing one). If you might be dealing with other types (such as complex numbers) you'll need to either check for those or use a different method.

Disabling of EditText in Android

As some answer mention it, if you disable the editText he become gray and if you set focusable false the cursor is displaying.

If you would like to do it only with xml this did the trick

       <YourFloatLabel
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

            <EditText
                android:id="@+id/view_ads_search_select"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

            <FrameLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:focusable="true"
                android:clickable="true"/>  
       </YourFloatLabel>

I simply add a FrameLayout appear above the editText and set it focusable and clickable so the editText can't be click.

How do you overcome the svn 'out of date' error?

I just had the same problem in several folders and this is what I did to commit:

1) In "Team Synchronize" perspective, right click on the folder > Override and Update
2) Delete the folder again
3) Commit and be happy

How to loop backwards in python?

def reverse(text):
    reversed = ''
    for i in range(len(text)-1, -1, -1):
        reversed += text[i]
    return reversed

print("reverse({}): {}".format("abcd", reverse("abcd")))

POST request not allowed - 405 Not Allowed - nginx, even with headers included

This configuration to your nginx.conf should help you.

https://gist.github.com/baskaran-md/e46cc25ccfac83f153bb

server {
    listen       80;
    server_name  localhost;

    location / {
        root   html;
        index  index.html index.htm;
    }

    error_page  404     /404.html;
    error_page  403     /403.html;

    # To allow POST on static pages
    error_page  405     =200 $uri;

    # ...
}

Simple Digit Recognition OCR in OpenCV-Python

OCR which stands for Optical Character Recognition is a computer vision technique used to identify the different types of handwritten digits that are used in common mathematics. To perform OCR in OpenCV we will use the KNN algorithm which detects the nearest k neighbors of a particular data point and then classifies that data point based on the class type detected for n neighbors.

Data Used


This data contains 5000 handwritten digits where there are 500 digits for every type of digit. Each digit is of 20×20 pixel dimensions. We will split the data such that 250 digits are for training and 250 digits are for testing for every class.

Below is the implementation.




import numpy as np
import cv2
   
      
# Read the image
image = cv2.imread('digits.png')
  
# gray scale conversion
gray_img = cv2.cvtColor(image,
                        cv2.COLOR_BGR2GRAY)
  
# We will divide the image
# into 5000 small dimensions 
# of size 20x20
divisions = list(np.hsplit(i,100) for i in np.vsplit(gray_img,50))
  
# Convert into Numpy array
# of size (50,100,20,20)
NP_array = np.array(divisions)
   
# Preparing train_data
# and test_data.
# Size will be (2500,20x20)
train_data = NP_array[:,:50].reshape(-1,400).astype(np.float32)
  
# Size will be (2500,20x20)
test_data = NP_array[:,50:100].reshape(-1,400).astype(np.float32)
  
# Create 10 different labels 
# for each type of digit
k = np.arange(10)
train_labels = np.repeat(k,250)[:,np.newaxis]
test_labels = np.repeat(k,250)[:,np.newaxis]
   
# Initiate kNN classifier
knn = cv2.ml.KNearest_create()
  
# perform training of data
knn.train(train_data,
          cv2.ml.ROW_SAMPLE, 
          train_labels)
   
# obtain the output from the
# classifier by specifying the
# number of neighbors.
ret, output ,neighbours,
distance = knn.findNearest(test_data, k = 3)
   
# Check the performance and
# accuracy of the classifier.
# Compare the output with test_labels
# to find out how many are wrong.
matched = output==test_labels
correct_OP = np.count_nonzero(matched)
   
#Calculate the accuracy.
accuracy = (correct_OP*100.0)/(output.size)
   
# Display accuracy.
print(accuracy)


Output

91.64


Well, I decided to workout myself on my question to solve the above problem. What I wanted is to implement a simple OCR using KNearest or SVM features in OpenCV. And below is what I did and how. (it is just for learning how to use KNearest for simple OCR purposes).

1) My first question was about letter_recognition.data file that comes with OpenCV samples. I wanted to know what is inside that file.

It contains a letter, along with 16 features of that letter.

And this SOF helped me to find it. These 16 features are explained in the paper Letter Recognition Using Holland-Style Adaptive Classifiers. (Although I didn't understand some of the features at the end)

2) Since I knew, without understanding all those features, it is difficult to do that method. I tried some other papers, but all were a little difficult for a beginner.

So I just decided to take all the pixel values as my features. (I was not worried about accuracy or performance, I just wanted it to work, at least with the least accuracy)

I took the below image for my training data:

enter image description here

(I know the amount of training data is less. But, since all letters are of the same font and size, I decided to try on this).

To prepare the data for training, I made a small code in OpenCV. It does the following things:

  1. It loads the image.
  2. Selects the digits (obviously by contour finding and applying constraints on area and height of letters to avoid false detections).
  3. Draws the bounding rectangle around one letter and wait for key press manually. This time we press the digit key ourselves corresponding to the letter in the box.
  4. Once the corresponding digit key is pressed, it resizes this box to 10x10 and saves all 100 pixel values in an array (here, samples) and corresponding manually entered digit in another array(here, responses).
  5. Then save both the arrays in separate .txt files.

At the end of the manual classification of digits, all the digits in the training data (train.png) are labeled manually by ourselves, image will look like below:

enter image description here

Below is the code I used for the above purpose (of course, not so clean):

import sys

import numpy as np
import cv2

im = cv2.imread('pitrain.png')
im3 = im.copy()

gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)

#################      Now finding Contours         ###################

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

samples =  np.empty((0,100))
responses = []
keys = [i for i in range(48,58)]

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            cv2.imshow('norm',im)
            key = cv2.waitKey(0)

            if key == 27:  # (escape to quit)
                sys.exit()
            elif key in keys:
                responses.append(int(chr(key)))
                sample = roismall.reshape((1,100))
                samples = np.append(samples,sample,0)

responses = np.array(responses,np.float32)
responses = responses.reshape((responses.size,1))
print "training complete"

np.savetxt('generalsamples.data',samples)
np.savetxt('generalresponses.data',responses)

Now we enter in to training and testing part.

For the testing part, I used the below image, which has the same type of letters I used for the training phase.

enter image description here

For training we do as follows:

  1. Load the .txt files we already saved earlier
  2. create an instance of the classifier we are using (it is KNearest in this case)
  3. Then we use KNearest.train function to train the data

For testing purposes, we do as follows:

  1. We load the image used for testing
  2. process the image as earlier and extract each digit using contour methods
  3. Draw a bounding box for it, then resize it to 10x10, and store its pixel values in an array as done earlier.
  4. Then we use KNearest.find_nearest() function to find the nearest item to the one we gave. ( If lucky, it recognizes the correct digit.)

I included last two steps (training and testing) in single code below:

import cv2
import numpy as np

#######   training part    ############### 
samples = np.loadtxt('generalsamples.data',np.float32)
responses = np.loadtxt('generalresponses.data',np.float32)
responses = responses.reshape((responses.size,1))

model = cv2.KNearest()
model.train(samples,responses)

############################# testing part  #########################

im = cv2.imread('pi.png')
out = np.zeros(im.shape,np.uint8)
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
thresh = cv2.adaptiveThreshold(gray,255,1,1,11,2)

contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt)>50:
        [x,y,w,h] = cv2.boundingRect(cnt)
        if  h>28:
            cv2.rectangle(im,(x,y),(x+w,y+h),(0,255,0),2)
            roi = thresh[y:y+h,x:x+w]
            roismall = cv2.resize(roi,(10,10))
            roismall = roismall.reshape((1,100))
            roismall = np.float32(roismall)
            retval, results, neigh_resp, dists = model.find_nearest(roismall, k = 1)
            string = str(int((results[0][0])))
            cv2.putText(out,string,(x,y+h),0,1,(0,255,0))

cv2.imshow('im',im)
cv2.imshow('out',out)
cv2.waitKey(0)

And it worked, below is the result I got:

enter image description here


Here it worked with 100% accuracy. I assume this is because all the digits are of the same kind and the same size.

But anyway, this is a good start to go for beginners (I hope so).

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

It sets how the database server sorts (compares pieces of text). in this case:

SQL_Latin1_General_CP1_CI_AS

breaks up into interesting parts:

  1. latin1 makes the server treat strings using charset latin 1, basically ascii
  2. CP1 stands for Code Page 1252
  3. CI case insensitive comparisons so 'ABC' would equal 'abc'
  4. AS accent sensitive, so 'ü' does not equal 'u'

P.S. For more detailed information be sure to read @solomon-rutzky's answer.

Django Template Variables and Javascript

A solution that worked for me is using the hidden input field in the template

<input type="hidden" id="myVar" name="variable" value="{{ variable }}">

Then getting the value in javascript this way,

var myVar = document.getElementById("myVar").value;

Setting a max height on a table

NOTE this answer is now incorrect. I may get back to it at a later time.

As others have pointed out, you can't set the height of a table unless you set its display to block, but then you get a scrolling header. So what you're looking for is to set the height and display:block on the tbody alone:

<table style="border: 1px solid red">
    <thead>
        <tr>
            <td>Header stays put, no scrolling</td>
        </tr>
    </thead>
    <tbody style="display: block; border: 1px solid green; height: 30px; overflow-y: scroll">
        <tr>
            <td>cell 1/1</td>
            <td>cell 1/2</td>
        </tr>
        <tr>
            <td>cell 2/1</td>
            <td>cell 2/2</td>
        </tr>
        <tr>
            <td>cell 3/1</td>
            <td>cell 3/2</td>
        </tr>
    </tbody>
</table>

Here's the fiddle.

Memory address of an object in C#

Switch the alloc type:

GCHandle handle = GCHandle.Alloc(a, GCHandleType.Normal);

How to get a specific output iterating a hash in Ruby?

hash.each do |key, array|
  puts "#{key}-----"
  puts array
end

Regarding order I should add, that in 1.8 the items will be iterated in random order (well, actually in an order defined by Fixnum's hashing function), while in 1.9 it will be iterated in the order of the literal.

How to trigger a phone call when clicking a link in a web page on mobile phone

Just use HTML anchor tag <a> and start the attribute href with tel:. I suggest starting the phone number with the country code. pay attention to the following example:

<a href="tel:+989123456789">NO Different What it is</a>

For this example, the country code is +98.

Hint: It is so suitable for cellphones, I know tel: prefix calls FaceTime on macOS but on Windows I'm not sure, but I guess it caused to launch Skype.

For more information: you can visit the list of URL schemes supported by browsers to know all href values prefixes.

Update multiple columns in SQL

I'd like to share with you how I address this kind of question. My case is slightly different as the result of table2 is dynamic and the column numbers may be less than that of table1. But the concept is the same.

First, get the result of table2.

enter image description here

Next, unpivot it.

enter image description here

Then write the update query using dynamic SQL. Sample code is written for testing 2 simple tables - tblA and tblB

--CREATE TABLE tblA(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--CREATE TABLE tblB(id int, col1 VARCHAR(25), col2 VARCHAR(25), col3 VARCHAR(25), col4 VARCHAR(25))
--INSERT INTO tblA(id, col1, col2, col3, col4)
--VALUES(1,'A1','A2','A3','A4')
--INSERT INTO tblB(id, col1, col2, col3, col4)
--VALUES(1,'B1','B2','B3','B4')

DECLARE @id VARCHAR(10) = 1, @TSQL NVARCHAR(MAX)
DECLARE @tblPivot TABLE(    
    colName VARCHAR(255),
    val VARCHAR(255)
)

INSERT INTO @tblPivot
SELECT colName, val
FROM tblB
UNPIVOT
(
    val
    FOR colName IN (col1, col2, col3, col4)
) unpiv
WHERE id = @id

SELECT @TSQL = COALESCE(@TSQL + '''
,','') + colName + ' = ''' + val
FROM @tblPivot

SET @TSQL = N'UPDATE tblA
SET ' + @TSQL + ''' 
WHERE id = ' + @id
PRINT @TSQL
--EXEC SP_EXECUTESQL @TSQL

PRINT @TSQL result:

enter image description here

geom_smooth() what are the methods available?

The method argument specifies the parameter of the smooth statistic. You can see stat_smooth for the list of all possible arguments to the method argument.

Dynamically updating plot in matplotlib

In order to do this without FuncAnimation (eg you want to execute other parts of the code while the plot is being produced or you want to be updating several plots at the same time), calling draw alone does not produce the plot (at least with the qt backend).

The following works for me:

import matplotlib.pyplot as plt
plt.ion()
class DynamicUpdate():
    #Suppose we know the x range
    min_x = 0
    max_x = 10

    def on_launch(self):
        #Set up plot
        self.figure, self.ax = plt.subplots()
        self.lines, = self.ax.plot([],[], 'o')
        #Autoscale on unknown axis and known lims on the other
        self.ax.set_autoscaley_on(True)
        self.ax.set_xlim(self.min_x, self.max_x)
        #Other stuff
        self.ax.grid()
        ...

    def on_running(self, xdata, ydata):
        #Update data (with the new _and_ the old points)
        self.lines.set_xdata(xdata)
        self.lines.set_ydata(ydata)
        #Need both of these in order to rescale
        self.ax.relim()
        self.ax.autoscale_view()
        #We need to draw *and* flush
        self.figure.canvas.draw()
        self.figure.canvas.flush_events()

    #Example
    def __call__(self):
        import numpy as np
        import time
        self.on_launch()
        xdata = []
        ydata = []
        for x in np.arange(0,10,0.5):
            xdata.append(x)
            ydata.append(np.exp(-x**2)+10*np.exp(-(x-7)**2))
            self.on_running(xdata, ydata)
            time.sleep(1)
        return xdata, ydata

d = DynamicUpdate()
d()

React Router v4 - How to get current route?

I think the author's of React Router (v4) just added that withRouter HOC to appease certain users. However, I believe the better approach is to just use render prop and make a simple PropsRoute component that passes those props. This is easier to test as you it doesn't "connect" the component like withRouter does. Have a bunch of nested components wrapped in withRouter and it's not going to be fun. Another benefit is you can also use this pass through whatever props you want to the Route. Here's the simple example using render prop. (pretty much the exact example from their website https://reacttraining.com/react-router/web/api/Route/render-func) (src/components/routes/props-route)

import React from 'react';
import { Route } from 'react-router';

export const PropsRoute = ({ component: Component, ...props }) => (
  <Route
    { ...props }
    render={ renderProps => (<Component { ...renderProps } { ...props } />) }
  />
);

export default PropsRoute;

usage: (notice to get the route params (match.params) you can just use this component and those will be passed for you)

import React from 'react';
import PropsRoute from 'src/components/routes/props-route';

export const someComponent = props => (<PropsRoute component={ Profile } />);

also notice that you could pass whatever extra props you want this way too

<PropsRoute isFetching={ isFetchingProfile } title="User Profile" component={ Profile } />

Escape double quote in VB string

Did you try using double-quotes? Regardless, no one in 2011 should be limited by the native VB6 shell command. Here's a function that uses ShellExecuteEx, much more versatile.

Option Explicit

Private Const SEE_MASK_DEFAULT = &H0

Public Enum EShellShowConstants
        essSW_HIDE = 0
        essSW_SHOWNORMAL = 1
        essSW_SHOWMINIMIZED = 2
        essSW_MAXIMIZE = 3
        essSW_SHOWMAXIMIZED = 3
        essSW_SHOWNOACTIVATE = 4
        essSW_SHOW = 5
        essSW_MINIMIZE = 6
        essSW_SHOWMINNOACTIVE = 7
        essSW_SHOWNA = 8
        essSW_RESTORE = 9
        essSW_SHOWDEFAULT = 10
End Enum

Private Type SHELLEXECUTEINFO
        cbSize        As Long
        fMask         As Long
        hwnd          As Long
        lpVerb        As String
        lpFile        As String
        lpParameters  As String
        lpDirectory   As String
        nShow         As Long
        hInstApp      As Long
        lpIDList      As Long     'Optional
        lpClass       As String   'Optional
        hkeyClass     As Long     'Optional
        dwHotKey      As Long     'Optional
        hIcon         As Long     'Optional
        hProcess      As Long     'Optional
End Type

Private Declare Function ShellExecuteEx Lib "shell32.dll" Alias "ShellExecuteExA" (lpSEI As SHELLEXECUTEINFO) As Long

Public Function ExecuteProcess(ByVal FilePath As String, ByVal hWndOwner As Long, ShellShowType As EShellShowConstants, Optional EXEParameters As String = "", Optional LaunchElevated As Boolean = False) As Boolean
    Dim SEI As SHELLEXECUTEINFO

    On Error GoTo Err

    'Fill the SEI structure
    With SEI
        .cbSize = Len(SEI)                  ' Bytes of the structure
        .fMask = SEE_MASK_DEFAULT           ' Check MSDN for more info on Mask
        .lpFile = FilePath                  ' Program Path
        .nShow = ShellShowType              ' How the program will be displayed
        .lpDirectory = PathGetFolder(FilePath)
        .lpParameters = EXEParameters       ' Each parameter must be separated by space. If the lpFile member specifies a document file, lpParameters should be NULL.
        .hwnd = hWndOwner                   ' Owner window handle

        ' Determine launch type (would recommend checking for Vista or greater here also)
        If LaunchElevated = True Then ' And m_OpSys.IsVistaOrGreater = True
            .lpVerb = "runas"
        Else
            .lpVerb = "Open"
        End If
    End With

     ExecuteProcess = ShellExecuteEx(SEI)   ' Execute the program, return success or failure

    Exit Function
Err:
    ' TODO: Log Error
    ExecuteProcess = False
End Function

Private Function PathGetFolder(psPath As String) As String
    On Error Resume Next
    Dim lPos As Long
    lPos = InStrRev(psPath, "\")
    PathGetFolder = Left$(psPath, lPos - 1)
End Function

running a command as a super user from a python script

To run a command as root, and pass it the password at the command prompt, you could do it as so:

import subprocess
from getpass import getpass

ls = "sudo -S ls -al".split()
cmd = subprocess.run(
    ls, stdout=subprocess.PIPE, input=getpass("password: "), encoding="ascii",
)
print(cmd.stdout)

For your example, probably something like this:

import subprocess
from getpass import getpass

restart_apache = "sudo /usr/sbin/apache2ctl restart".split()
proc = subprocess.run(
    restart_apache,
    stdout=subprocess.PIPE,
    input=getpass("password: "),
    encoding="ascii",
)

Detect if a page has a vertical scrollbar?

I found vanila solution

_x000D_
_x000D_
var hasScrollbar = function() {_x000D_
  // The Modern solution_x000D_
  if (typeof window.innerWidth === 'number')_x000D_
    return window.innerWidth > document.documentElement.clientWidth_x000D_
_x000D_
  // rootElem for quirksmode_x000D_
  var rootElem = document.documentElement || document.body_x000D_
_x000D_
  // Check overflow style property on body for fauxscrollbars_x000D_
  var overflowStyle_x000D_
_x000D_
  if (typeof rootElem.currentStyle !== 'undefined')_x000D_
    overflowStyle = rootElem.currentStyle.overflow_x000D_
_x000D_
  overflowStyle = overflowStyle || window.getComputedStyle(rootElem, '').overflow_x000D_
_x000D_
    // Also need to check the Y axis overflow_x000D_
  var overflowYStyle_x000D_
_x000D_
  if (typeof rootElem.currentStyle !== 'undefined')_x000D_
    overflowYStyle = rootElem.currentStyle.overflowY_x000D_
_x000D_
  overflowYStyle = overflowYStyle || window.getComputedStyle(rootElem, '').overflowY_x000D_
_x000D_
  var contentOverflows = rootElem.scrollHeight > rootElem.clientHeight_x000D_
  var overflowShown    = /^(visible|auto)$/.test(overflowStyle) || /^(visible|auto)$/.test(overflowYStyle)_x000D_
  var alwaysShowScroll = overflowStyle === 'scroll' || overflowYStyle === 'scroll'_x000D_
_x000D_
  return (contentOverflows && overflowShown) || (alwaysShowScroll)_x000D_
}
_x000D_
_x000D_
_x000D_

How many concurrent AJAX (XmlHttpRequest) requests are allowed in popular browsers?

I have writen a single file AJAX tester. Enjoy it!!! Just because I have had problems with my hosting provider

<?php /*

Author:   Luis Siquot
Purpose:  Check ajax performance and errors
License:  GPL
site5:    Please don't drop json requests (nor delay)!!!!

*/

$r = (int)$_GET['r'];
$w = (int)$_GET['w'];
if($r) { 
   sleep($w);
   echo json_encode($_GET);
   die ();
}  //else
?><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">

var _settimer;
var _timer;
var _waiting;

$(function(){
  clearTable();
  $('#boton').bind('click', donow);
})

function donow(){
  var w;
  var estim = 0;
  _waiting = $('#total')[0].value * 1;
  clearTable();
  for(var r=1;r<=_waiting;r++){
       w = Math.floor(Math.random()*6)+2;
       estim += w;
       dodebug({r:r, w:w});
       $.ajax({url: '<?php echo $_SERVER['SCRIPT_NAME']; ?>',
               data:    {r:r, w:w},
               dataType: 'json',   // 'html', 
               type: 'GET',
               success: function(CBdata, status) {
                  CBdebug(CBdata);
               }
       });
  }
  doStat(estim);
  timer(estim+10);
}

function doStat(what){
    $('#stat').replaceWith(
       '<table border="0" id="stat"><tr><td>Request Time Sum=<th>'+what+
       '<td>&nbsp;&nbsp;/2=<th>'+Math.ceil(what/2)+
       '<td>&nbsp;&nbsp;/3=<th>'+Math.ceil(what/3)+
       '<td>&nbsp;&nbsp;/4=<th>'+Math.ceil(what/4)+
       '<td>&nbsp;&nbsp;/6=<th>'+Math.ceil(what/6)+
       '<td>&nbsp;&nbsp;/8=<th>'+Math.ceil(what/8)+
       '<td> &nbsp; (seconds)</table>'
    );
}

function timer(what){
  if(what)         {_timer = 0; _settimer = what;}
  if(_waiting==0)  {
    $('#showTimer')[0].innerHTML = 'completed in <b>' + _timer + ' seconds</b> (aprox)';
    return ;
  }
  if(_timer<_settimer){
     $('#showTimer')[0].innerHTML = _timer;
     setTimeout("timer()",1000);
     _timer++;
     return;
  }
  $('#showTimer')[0].innerHTML = '<b>don\'t wait any more!!!</b>';
}


function CBdebug(what){
    _waiting--;
    $('#req'+what.r)[0].innerHTML = 'x';
}


function dodebug(what){
    var tt = '<tr><td>' + what.r + '<td>' + what.w + '<td id=req' + what.r + '>&nbsp;'
    $('#debug').append(tt);
}


function clearTable(){
    $('#debug').replaceWith('<table border="1" id="debug"><tr><td>Request #<td>Wait Time<td>Done</table>');
}


</script>
</head>
<body>
<center>
<input type="button" value="start" id="boton">
<input type="text" value="80" id="total" size="2"> concurrent json requests
<table id="stat"><tr><td>&nbsp;</table>
Elapsed Time: <span id="showTimer"></span>
<table id="debug"></table>
</center>
</body>

Edit:
r means row and w waiting time.
When you initially press start button 80 (or any other number) of concurrent ajax request are launched by javascript, but as is known they are spooled by the browser. Also they are requested to the server in parallel (limited to certain number, this is the fact of this question). Here the requests are solved server side with a random delay (established by w). At start time all the time needed to solve all ajax calls is calculated. When test is finished, you can see if it took half, took third, took a quarter, etc of the total time, deducting which was the parallelism on the calls to the server. This is not strict, nor precise, but is nice to see in real time how ajaxs calls are completed (seeing the incoming cross). And is a very simple self contained script to show ajax basics.
Of course, this assumes, that server side is not introducing any extra limit.
Preferably use in conjunction with firebug net panel (or your browser's equivalent)

How to save a git commit message from windows cmd?

You are inside vim. To save changes and quit, type:

<esc> :wq <enter>

That means:

  • Press Escape. This should make sure you are in command mode
  • type in :wq
  • Press Return

An alternative that stdcall in the comments mentions is:

  • Press Escape
  • Press shift+Z shift+Z (capital Z twice).

How to save data in an android app

In onCreate:

SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);

    String mySetting = sharedPref.getString("mySetting", null);

In onDestroy or equivalent:

SharedPreferences sharedPref = getSharedPreferences("mySettings", MODE_PRIVATE);

    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putString("mySetting", "Hello Android");
    editor.commit();

What is the fastest way to create a checksum for large files in C#

You're doing something wrong (probably too small read buffer). On a machine of undecent age (Athlon 2x1800MP from 2002) that has DMA on disk probably out of whack (6.6M/s is damn slow when doing sequential reads):

Create a 1G file with "random" data:

# dd if=/dev/sdb of=temp.dat bs=1M count=1024    
1073741824 bytes (1.1 GB) copied, 161.698 s, 6.6 MB/s

# time sha1sum -b temp.dat
abb88a0081f5db999d0701de2117d2cb21d192a2 *temp.dat

1m5.299s

# time md5sum -b temp.dat
9995e1c1a704f9c1eb6ca11e7ecb7276 *temp.dat

1m58.832s

This is also weird, md5 is consistently slower than sha1 for me (reran several times).

How can I detect Internet Explorer (IE) and Microsoft Edge using JavaScript?

I'm using UAParser https://github.com/faisalman/ua-parser-js

var a = new UAParser();
var name = a.getResult().browser.name;
var version = a.getResult().browser.version;

Terminating a script in PowerShell

Exit will exit PowerShell too. If you wish to "break" out of just the current function or script - use Break :)

If ($Breakout -eq $true)
{
     Write-Host "Break Out!"
     Break
}
ElseIf ($Breakout -eq $false)
{
     Write-Host "No Breakout for you!"
}
Else
{
    Write-Host "Breakout wasn't defined..."
}

How can I clone a private GitLab repository?

If you are using Windows,

  1. make a folder and open git bash from there

  2. in the git bash,

    git clone [email protected]:Example/projectName.git

Ruby max integer

In ruby Fixnums are automatically converted to Bignums.

To find the highest possible Fixnum you could do something like this:

class Fixnum
 N_BYTES = [42].pack('i').size
 N_BITS = N_BYTES * 8
 MAX = 2 ** (N_BITS - 2) - 1
 MIN = -MAX - 1
end
p(Fixnum::MAX)

Shamelessly ripped from a ruby-talk discussion. Look there for more details.

Identifying and removing null characters in UNIX

I discovered the following, which prints out which lines, if any, have null characters:

perl -ne '/\000/ and print;' file-with-nulls

Also, an octal dump can tell you if there are nulls:

od file-with-nulls | grep ' 000'

How can I change the current URL?

Hmm, I would use

window.location = 'http://localhost/index.html#?options=go_here';

I'm not exactly sure if that is what you mean.

Using CSS to insert text

The answer using jQuery that everyone seems to like has a major flaw, which is it is not scalable (at least as it is written). I think Martin Hansen has the right idea, which is to use HTML5 data-* attributes. And you can even use the apostrophe correctly:

html:

<div class="task" data-task-owner="Joe">mop kitchen</div>
<div class="task" data-task-owner="Charles" data-apos="1">vacuum hallway</div>

css:

div.task:before { content: attr(data-task-owner)"'s task - " ; }
div.task[data-apos]:before { content: attr(data-task-owner)"' task - " ; }

output:

Joe's task - mop kitchen
Charles' task - vacuum hallway

JavaFX 2.1 TableView refresh items

I suppose this thread has a very good description of the problem with table refresh.

Correct way to find max in an Array in Swift

You can also sort your array and then use array.first or array.last

Sorting a list using Lambda/Linq to objects

This is how I solved my problem:

List<User> list = GetAllUsers();  //Private Method

if (!sortAscending)
{
    list = list
           .OrderBy(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
           .ToList();
}
else
{
    list = list
           .OrderByDescending(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
           .ToList();
}

UITableViewCell, show delete button on swipe

I had a problem which I have just managed to solve so I am sharing it as it may help someone.

I have a UITableView and added the methods shown to enable swipe to delete:

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return YES if you want the specified item to be editable.
    return YES;
}

// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        //add code here for when you hit delete
    }    
}

I am working on an update that allows me to put the table into edit mode and enables multiselect. To do that I added the code from Apple's TableMultiSelect sample. Once I got that working I found that my swipe the delete function had stopped working.

It turns out that adding the following line to viewDidLoad was the issue:

self.tableView.allowsMultipleSelectionDuringEditing = YES;

With this line in, the multiselect would work but the swipe to delete wouldn't. Without the line it was the other way around.

The fix:

Add the following method to your viewController:

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    self.tableView.allowsMultipleSelectionDuringEditing = editing; 
    [super setEditing:editing animated:animated];
}

Then in your method that puts the table into editing mode (from a button press for example) you should use:

[self setEditing:YES animated:YES];

instead of:

[self.tableView setEditing:YES animated:YES];

This means that multiselect is only enabled when the table is in editing mode.

Removing fields from struct or hiding them in JSON Response

Take three ingredients:

  1. The reflect package to loop over all the fields of a struct.

  2. An if statement to pick up the fields you want to Marshal, and

  3. The encoding/json package to Marshal the fields of your liking.

Preparation:

  1. Blend them in a good proportion. Use reflect.TypeOf(your_struct).Field(i).Name() to get a name of the ith field of your_struct.

  2. Use reflect.ValueOf(your_struct).Field(i) to get a type Value representation of an ith field of your_struct.

  3. Use fieldValue.Interface() to retrieve the actual value (upcasted to type interface{}) of the fieldValue of type Value (note the bracket use - the Interface() method produces interface{}

If you luckily manage not to burn any transistors or circuit-breakers in the process you should get something like this:

func MarshalOnlyFields(structa interface{},
    includeFields map[string]bool) (jsona []byte, status error) {
    value := reflect.ValueOf(structa)
    typa := reflect.TypeOf(structa)
    size := value.NumField()
    jsona = append(jsona, '{')
    for i := 0; i < size; i++ {
        structValue := value.Field(i)
        var fieldName string = typa.Field(i).Name
        if marshalledField, marshalStatus := json.Marshal((structValue).Interface()); marshalStatus != nil {
            return []byte{}, marshalStatus
        } else {
            if includeFields[fieldName] {
                jsona = append(jsona, '"')
                jsona = append(jsona, []byte(fieldName)...)
                jsona = append(jsona, '"')
                jsona = append(jsona, ':')
                jsona = append(jsona, (marshalledField)...)
                if i+1 != len(includeFields) {
                    jsona = append(jsona, ',')
                }
            }
        }
    }
    jsona = append(jsona, '}')
    return
}

Serving:

serve with an arbitrary struct and a map[string]bool of fields you want to include, for example

type magic struct {
    Magic1 int
    Magic2 string
    Magic3 [2]int
}

func main() {
    var magic = magic{0, "tusia", [2]int{0, 1}}
    if json, status := MarshalOnlyFields(magic, map[string]bool{"Magic1": true}); status != nil {
        println("error")
    } else {
        fmt.Println(string(json))
    }

}

Bon Appetit!

shell-script headers (#!/bin/sh vs #!/bin/csh)

This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).

When you type in a command at the Unix prompt, you are interacting with the shell.

E.g., #!/bin/csh refers to the C-shell, /bin/tcsh the t-shell, /bin/bash the bash shell, etc.

You can tell which interactive shell you are using the

 echo $SHELL

command, or alternatively

 env | grep -i shell

You can change your command shell with the chsh command.

Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.

This page might be of interest as it "translates" between bash and tcsh commands/syntax.

Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh shell interactively, but often run bash scripts using /bin/bash in the script file.

Aside:

This concept extends to other scripts too. For instance if you program in Python you'd put

 #!/usr/bin/python

at the top of your Python program

Change selected value of kendo ui dropdownlist

Seems there's an easier way, at least in Kendo UI v2015.2.624:

$('#myDropDownSelector').data('kendoDropDownList').search('Text value to find');

If there's not a match in the dropdown, Kendo appears to set the dropdown to an unselected value, which makes sense.


I couldn't get @Gang's answer to work, but if you swap his value with search, as above, we're golden.

How do I compare strings in GoLang?

For the Platform Independent Users or Windows users, what you can do is:

import runtime:

import (
    "runtime"
    "strings"
)

and then trim the string like this:

if runtime.GOOS == "windows" {
  input = strings.TrimRight(input, "\r\n")
} else {
  input = strings.TrimRight(input, "\n")
}

now you can compare it like that:

if strings.Compare(input, "a") == 0 {
  //....yourCode
}

This is a better approach when you're making use of STDIN on multiple platforms.

Explanation

This happens because on windows lines end with "\r\n" which is known as CRLF, but on UNIX lines end with "\n" which is known as LF and that's why we trim "\n" on unix based operating systems while we trim "\r\n" on windows.

How to remove underline from a name on hover

To keep the color and prevent an underline on the link:

legend.green-color a{
    color:green;
    text-decoration: none;
}

Cannot run emulator in Android Studio

  1. Go to "Edit the System Environment variables".
  2. Click on New Button and enter "ANDROID_SDK_ROOT" in variable name and enter android sdk full path in variable value. Click on ok and close.
  3. Refresh AVD.
  4. This will resolve error.

Entity Framework Core add unique constraint code-first

For someone who is trying all these solution but not working try this one, it worked for me

protected override void OnModelCreating(ModelBuilder builder)
{

    builder.Entity<User>().Property(t => t.Email).HasColumnAnnotation("Index", new IndexAnnotation(new IndexAttribute("IX_EmailIndex") { IsUnique = true }));

}

Order by multiple columns with Doctrine

You have to add the order direction right after the column name:

$qb->orderBy('column1 ASC, column2 DESC');

As you have noted, multiple calls to orderBy do not stack, but you can make multiple calls to addOrderBy:

$qb->addOrderBy('column1', 'ASC')
   ->addOrderBy('column2', 'DESC');

Log exception with traceback

Heres a simple example taken from the python 2.6 documentation:

import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG,)

logging.debug('This message should go to the log file')

How can you check for a #hash in a URL using JavaScript?

Put the following:

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>

Bootstrap 3.0: How to have text and input on same line?

In Bootstrap 4 for Horizontal element you can use .row with .col-*-* classes to specify the width of your labels and controls. see this link.

And if you want to display a series of labels, form controls, and buttons on a single horizontal row you can use .form-inline for more info this link

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

\t is a tab character. Use a raw string instead:

test_file=open(r'c:\Python27\test.txt','r')

or double the slashes:

test_file=open('c:\\Python27\\test.txt','r')

or use forward slashes instead:

test_file=open('c:/Python27/test.txt','r')

Setting up enviromental variables in Windows 10 to use java and javac

Its still the same concept, you'll need to setup path variable so that windows is aware of the java executable and u can run it from command prompt conveniently

Details from the java's own page: https://java.com/en/download/help/path.xml That article applies to: •Platform(s): Solaris SPARC, Solaris x86, Red Hat Linux, SUSE Linux, Windows 8, Windows 7, Vista, Windows XP, Windows 10

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

Route::group(['middleware' => 'web'], function () {
Route::auth();

Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);

Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
    Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
    Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});

List file names based on a filename pattern and file content?

Grep DOES NOT use "wildcards" for search – that's shell globbing, like *.jpg. Grep uses "regular expressions" for pattern matching. While in the shell '*' means "anything", in grep it means "match the previous item zero or more times".

More information and examples here: http://www.regular-expressions.info/reference.html

To answer of your question - you can find files matching some pattern with grep:

find /somedir -type f -print | grep 'LMN2011' # that will show files whose names contain LMN2011

Then you can search their content (case insensitive):

find /somedir -type f -print | grep -i 'LMN2011' | xargs grep -i 'LMN20113456'

If the paths can contain spaces, you should use the "zero end" feature:

find /somedir -type f -print0 | grep -iz 'LMN2011' | xargs -0 grep -i 'LMN20113456'

Console app arguments, how arguments are passed to Main method

The main method of the runtime engine looks something like int main(int argc, char *argv[]), where argc is a count of the number of arguments and argv is an array of pointers to each. The runtime engine converts this into a form that is more natural to c#.

Prior to that main method being called, everything is in assembly language. It has access to the command line arguments (because the operating system makes that available to every process that starts), but that assembly language needs to convert a single string of the full command line into multiple substrings (using whitespace to separate them) before it's ready to pass them into main().

How to get text of an input text box during onKeyPress?

easy...

In your keyPress event handler, write

void ValidateKeyPressHandler(object sender, KeyPressEventArgs e)
{
    var tb = sender as TextBox;
    var startPos = tb.SelectionStart;
    var selLen= tb.SelectionLength;

    var afterEditValue = tb.Text.Remove(startPos, selLen)
                .Insert(startPos, e.KeyChar.ToString()); 
    //  ... more here
}

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

Even though utf8_decode is a useful solution, I prefer to correct the encoding errors on the table itself. In my opinion it is better to correct the bad characters themselves than making "hacks" in the code. Simply do a replace on the field on the table. To correct the bad encoded characters from OP :

update <table> set <field> = replace(<field>, "ë", "ë")
update <table> set <field> = replace(<field>, "Ã", "à")
update <table> set <field> = replace(<field>, "ì", "ì")
update <table> set <field> = replace(<field>, "ù", "ù")

Where <table> is the name of the mysql table and <field> is the name of the column in the table. Here is a very good check-list for those typically bad encoded windows-1252 to utf-8 characters -> Debugging Chart Mapping Windows-1252 Characters to UTF-8 Bytes to Latin-1 Characters.

Remember to backup your table before trying to replace any characters with SQL!

[I know this is an answer to a very old question, but was facing the issue once again. Some old windows machine didnt encoded the text correct before inserting it to the utf8_general_ci collated table.]

Changing the tmp folder of mysql

You should edit your my.cnf

tmpdir = /whatewer/you/want

and after that restart mysql

P.S. Don't forget give write permissions to /whatewer/you/want for mysql user

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

I resolved this problem, searching the dll's file in C:\Windows\assembly\GAC_MSIL\ and copied to bin directory of the proyect deployed. That work for me.

How to make Twitter Bootstrap tooltips have multiple lines?

You can use white-space:pre-wrap on the tooltip. This will make the tooltip respect new lines. Lines will still wrap if they are longer than the default max-width of the container.

.tooltip-inner {
    white-space:pre-wrap;
}

http://jsfiddle.net/chad/TSZSL/52/

If you want to prevent text from wrapping, do the following instead.

.tooltip-inner {
    white-space:pre;
    max-width:none;
}

http://jsfiddle.net/chad/TSZSL/53/

Neither of these will work with a \n in the html, they must actually be actual newlines. Alternatively, you can use encoded newlines &#013;, but that's probably even less desirable than using <br>'s.

Count number of objects in list

Advice for R newcomers like me : beware, the following is a list of a single object :

> mylist <- list (1:10)
> length (mylist)
[1] 1

In such a case you are not looking for the length of the list, but of its first element :

> length (mylist[[1]])
[1] 10

This is a "true" list :

> mylist <- list(1:10, rnorm(25), letters[1:3])
> length (mylist)
[1] 3

Also, it seems that R considers a data.frame as a list :

> df <- data.frame (matrix(0, ncol = 30, nrow = 2))
> typeof (df)
[1] "list"

In such a case you may be interested in ncol() and nrow() rather than length() :

> ncol (df)
[1] 30
> nrow (df)
[1] 2

Though length() will also work (but it's a trick when your data.frame has only one column) :

> length (df)
[1] 30
> length (df[[1]])
[1] 2

With Twitter Bootstrap, how can I customize the h1 text color of one page and leave the other pages to be default?

in bootstrap 3 here are the classes to change the text color:

<p class="text-muted">...</p> //grey
<p class="text-primary">...</p> //light blue
<p class="text-success">...</p> //green
<p class="text-info">...</p> //blue
<p class="text-warning">...</p> //orangish,yellow
<p class="text-danger">...</p> //red

Documentation under Helper classes - Contextual colors.

How to have click event ONLY fire on parent DIV, not children?

I had the same problem and came up with this solution (based on the other answers)

 $( ".newsletter_background" ).click(function(e) {
    if (e.target == this) {
        $(".newsletter_background").hide();
    } 
});

Basically it says if the target is the div then run the code otherwise do nothing (don't hide it)

Angular checkbox and ng-click

cardeal's answer was really helpful. Took it a little further and figured it may help others some where down the line. Here is the fiddle:

https://jsfiddle.net/vtL5x0wh/

And the code:

<body ng-app="checkboxExample">
  <script>
  angular.module('checkboxExample', [])
    .controller('ExampleController', ['$scope', function($scope) {

    $scope.value0 = "none";
    $scope.value1 = "none";
    $scope.value2 = "none";
    $scope.value3 = "none";

    $scope.checkboxModel = {
        critical1: {selected: true, id: 'C1', error:'critical' , score:20},
        critical2: {selected: false, id: 'C2', error:'critical' , score:30},
        critical3: {selected: false, id: 'C3', error:'critical' , score:40},

       myClick : function($event) { 
          $scope.value0 = $event.selected;
          $scope.value1 = $event.id;
          $scope.value2 = $event.error;
          $scope.value3 = $event.score;
        }
    };

   }]);
</script>
<form name="myForm" ng-controller="ExampleController">
  <label>


    Value1:
    <input type="checkbox" ng-model="checkboxModel.critical1.selected" ng-change="checkboxModel.myClick(checkboxModel.critical1)">
  </label><br/>
  <label>Value2:
    <input type="checkbox" ng-model="checkboxModel.critical2.selected" ng-change="checkboxModel.myClick(checkboxModel.critical2)">
   </label><br/>
     <label>Value3:
    <input type="checkbox" ng-model="checkboxModel.critical3.selected" ng-change="checkboxModel.myClick(checkboxModel.critical3)">
   </label><br/><br/><br/><br/>
  <tt>selected = {{value0}}</tt><br/>
  <tt>id = {{value1}}</tt><br/>
  <tt>error = {{value2}}</tt><br/>
  <tt>score = {{value3}}</tt><br/>
 </form>

Use sed to replace all backslashes with forward slashes

$ echo "C:\Windows\Folder\File.txt" | sed -e 's/\\/\//g'
C:/Windows/Folder/File.txt

The sed command in this case is 's/OLD_TEXT/NEW_TEXT/g'.

The leading 's' just tells it to search for OLD_TEXT and replace it with NEW_TEXT.

The trailing 'g' just says to replace all occurrences on a given line, not just the first.

And of course you need to separate the 's', the 'g', the old, and the new from each other. This is where you must use forward slashes as separators.

For your case OLD_TEXT == '\' and NEW_TEXT == '/'. But you can't just go around typing slashes and expecting things to work as expected be taken literally while using them as separators at the same time. In general slashes are quite special and must be handled as such. They must be 'escaped' (i.e. preceded) by a backslash.

So for you, OLD_TEXT == '\\' and NEW_TEXT == '\/'. Putting these inside the 's/OLD_TEXT/NEW_TEXT/g' paradigm you get
's/\\/\//g'. That reads as
's / \\ / \/ / g' and after escapes is
's / \ / / / g' which will replace all backslashes with forward slashes.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

JQuery Number Formatting

http://jquerypriceformat.com/#examples

https://github.com/flaviosilveira/Jquery-Price-Format

html input runing for live chance.

<input type="text" name="v7"  class="priceformat"/>
<input type="text" name="v8"  class="priceformat"/>


$('.priceformat').each(function( index ) {
    $(this).priceFormat({ prefix: '',  thousandsSeparator: '' });
});

//5000.00

//5.000,00

//5,000.00

How do you get the logical xor of two variables in Python?

This is how I would code up any truth table. For xor in particular we have:

| a | b  | xor   |             |
|---|----|-------|-------------|
| T | T  | F     |             |
| T | F  | T     | a and not b |
| F | T  | T     | not a and b |
| F | F  | F     |             |

Just look at the T values in the answer column and string together all true cases with logical or. So, this truth table may be produced in case 2 or 3. Hence,

xor = lambda a, b: (a and not b) or (not a and b)

Meaning of "[: too many arguments" error from if [] (square brackets)

Some times If you touch the keyboard accidentally and removed a space.

if [ "$myvar" = "something"]; then
    do something
fi

Will trigger this error message. Note the space before ']' is required.

C++ getters/setters coding style

Avoid public variables, except for classes that are essentially C-style structs. It's just not a good practice to get into.

Once you've defined the class interface, you might never be able to change it (other than adding to it), because people will build on it and rely on it. Making a variable public means that you need to have that variable, and you need to make sure it has what the user needs.

Now, if you use a getter, you're promising to supply some information, which is currently kept in that variable. If the situation changes, and you'd rather not maintain that variable all the time, you can change the access. If the requirements change (and I've seen some pretty odd requirements changes), and you mostly need the name that's in this variable but sometimes the one in that variable, you can just change the getter. If you made the variable public, you'd be stuck with it.

This won't always happen, but I find it a lot easier just to write a quick getter than to analyze the situation to see if I'd regret making the variable public (and risk being wrong later).

Making member variables private is a good habit to get into. Any shop that has code standards is probably going to forbid making the occasional member variable public, and any shop with code reviews is likely to criticize you for it.

Whenever it really doesn't matter for ease of writing, get into the safer habit.

Date format in dd/MM/yyyy hh:mm:ss

This will be varchar but should format as you need.

RIGHT('0' + LTRIM(DAY(d)), 2) + '/'
+ RIGHT('0' + LTRIM(MONTH(d)), 2) + '/'
+ LTRIM(YEAR(d)) + ' '
+ RIGHT('0' + LTRIM(DATEPART(HOUR, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(MINUTE, d)), 2) + ':'
+ RIGHT('0' + LTRIM(DATEPART(SECOND, d)), 2)

Where d is your datetime field or variable.

Save current directory in variable using Bash?

On a BASH shell, you can very simply run:

export PATH=$PATH:`pwd`/somethingelse

No need to save the current working directory into a variable...

Make var_dump look pretty

You could use this one debugVar() instead of var_dump()

Check out: https://github.com/E1NSER/php-debug-function

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

Counting number of lines, words, and characters in a text file

in.next(); is consuming all the lines in the first while(). After the end of your first while loop, there are no more characters to be read at the input stream.

You should nest your character and word-counting within a while loop counting lines.

How to replace text of a cell based on condition in excel

You can use the Conditional Formatting to replace text and NOT effect any formulas. Simply go to the Rule's format where you will see Number, Font, Border and Fill.
Go to the Number tab and select CUSTOM. Then simply type where it says TYPE: what you want to say in QUOTES.

Example.. "OTHER"

Is it possible to dynamically compile and execute C# code fragments?

I recently needed to spawn processes for unit testing. This post was useful as I created a simple class to do that with either code as a string or code from my project. To build this class, you'll need the ICSharpCode.Decompiler and Microsoft.CodeAnalysis NuGet packages. Here's the class:

using ICSharpCode.Decompiler;
using ICSharpCode.Decompiler.CSharp;
using ICSharpCode.Decompiler.TypeSystem;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

public static class CSharpRunner
{
   public static object Run(string snippet, IEnumerable<Assembly> references, string typeName, string methodName, params object[] args) =>
      Invoke(Compile(Parse(snippet), references), typeName, methodName, args);

   public static object Run(MethodInfo methodInfo, params object[] args)
   {
      var refs = methodInfo.DeclaringType.Assembly.GetReferencedAssemblies().Select(n => Assembly.Load(n));
      return Invoke(Compile(Decompile(methodInfo), refs), methodInfo.DeclaringType.FullName, methodInfo.Name, args);
   }

   private static Assembly Compile(SyntaxTree syntaxTree, IEnumerable<Assembly> references = null)
   {
      if (references is null) references = new[] { typeof(object).Assembly, typeof(Enumerable).Assembly };
      var mrefs = references.Select(a => MetadataReference.CreateFromFile(a.Location));
      var compilation = CSharpCompilation.Create(Path.GetRandomFileName(), new[] { syntaxTree }, mrefs, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary));

      using (var ms = new MemoryStream())
      {
         var result = compilation.Emit(ms);
         if (result.Success)
         {
            ms.Seek(0, SeekOrigin.Begin);
            return Assembly.Load(ms.ToArray());
         }
         else
         {
            throw new InvalidOperationException(string.Join("\n", result.Diagnostics.Where(diagnostic => diagnostic.IsWarningAsError || diagnostic.Severity == DiagnosticSeverity.Error).Select(d => $"{d.Id}: {d.GetMessage()}")));
         }
      }
   }

   private static SyntaxTree Decompile(MethodInfo methodInfo)
   {
      var decompiler = new CSharpDecompiler(methodInfo.DeclaringType.Assembly.Location, new DecompilerSettings());
      var typeInfo = decompiler.TypeSystem.MainModule.Compilation.FindType(methodInfo.DeclaringType).GetDefinition();
      return Parse(decompiler.DecompileTypeAsString(typeInfo.FullTypeName));
   }

   private static object Invoke(Assembly assembly, string typeName, string methodName, object[] args)
   {
      var type = assembly.GetType(typeName);
      var obj = Activator.CreateInstance(type);
      return type.InvokeMember(methodName, BindingFlags.Default | BindingFlags.InvokeMethod, null, obj, args);
   }

   private static SyntaxTree Parse(string snippet) => CSharpSyntaxTree.ParseText(snippet);
}

To use it, call the Run methods as below:

void Demo1()
{
   const string code = @"
   public class Runner
   {
      public void Run() { System.IO.File.AppendAllText(@""C:\Temp\NUnitTest.txt"", System.DateTime.Now.ToString(""o"") + ""\n""); }
   }";

   CSharpRunner.Run(code, null, "Runner", "Run");
}

void Demo2()
{
   CSharpRunner.Run(typeof(Runner).GetMethod("Run"));
}

public class Runner
{
   public void Run() { System.IO.File.AppendAllText(@"C:\Temp\NUnitTest.txt", System.DateTime.Now.ToString("o") + "\n"); }
}

How to use Visual Studio C++ Compiler?

You may be forgetting something. Before #include <iostream>, write #include <stdafx.h> and maybe that will help. Then, when you are done writing, click test, than click output from build, then when it is done processing/compiling, press Ctrl+F5 to open the Command Prompt and it should have the output and "press any key to continue."

Execute external program

borrowed this shamely from here

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

System.out.printf("Output of running %s is:", Arrays.toString(args));

while ((line = br.readLine()) != null) {
  System.out.println(line);
}

More information here

Other issues on how to pass commands here and here

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

The <Comment> tag contains two text nodes and two <br> nodes as children.

Your xpath expression was

//*[contains(text(),'ABC')]

To break this down,

  1. * is a selector that matches any element (i.e. tag) -- it returns a node-set.
  2. The [] are a conditional that operates on each individual node in that node set. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  3. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  4. contains is a function that operates on a string. If it is passed a node set, the node set is converted into a string by returning the string-value of the node in the node-set that is first in document order. Hence, it can match only the first text node in your <Comment> element -- namely BLAH BLAH BLAH. Since that doesn't match, you don't get a <Comment> in your results.

You need to change this to

//*[text()[contains(.,'ABC')]]
  1. * is a selector that matches any element (i.e. tag) -- it returns a node-set.
  2. The outer [] are a conditional that operates on each individual node in that node set -- here it operates on each element in the document.
  3. text() is a selector that matches all of the text nodes that are children of the context node -- it returns a node set.
  4. The inner [] are a conditional that operates on each node in that node set -- here each individual text node. Each individual text node is the starting point for any path in the brackets, and can also be referred to explicitly as . within the brackets. It matches if any of the individual nodes it operates on match the conditions inside the brackets.
  5. contains is a function that operates on a string. Here it is passed an individual text node (.). Since it is passed the second text node in the <Comment> tag individually, it will see the 'ABC' string and be able to match it.

How to delete multiple files at once in Bash on Linux?

Bash supports all sorts of wildcards and expansions.

Your exact case would be handled by brace expansion, like so:

$ rm -rf abc.log.2012-03-{14,27,28}

The above would expand to a single command with all three arguments, and be equivalent to typing:

$ rm -rf abc.log.2012-03-14 abc.log.2012-03-27 abc.log.2012-03-28

It's important to note that this expansion is done by the shell, before rm is even loaded.

How to copy and paste worksheets between Excel workbooks?

I'm using this code, hope this helps!

Application.ScreenUpdating = False
Application.EnableEvents = False

Dim destination_wb As Workbook
Set destination_wb = Workbooks.Open(DESTINATION_WORKBOOK_NAME)

worksheet_to_copy.Copy Before:=destination_wb.Worksheets(1)
destination_wb.Worksheets(1).Name = worksheet_to_copy.Name
'Add the sheets count to the name to avoid repeated worksheet names error
'& destination_wb.Worksheets.Count


'optional
destination_wb.Worksheets(1).UsedRange.Columns.AutoFit

'I use this to avoid macro errors in destination_wb
Call DeleteAllVBACode(destination_wb)

'Delete source worksheet
Application.DisplayAlerts = False
worksheet_to_copy.Delete
Application.DisplayAlerts = True

destination_wb.Save
destination_wb.Close

Application.EnableEvents = True
Application.ScreenUpdating = True

' From http://www.cpearson.com/Excel/vbe.aspx           

Public Sub DeleteAllVBACode(libro As Workbook)
    Dim VBProj As VBProject
    Dim VBComp As VBComponent
    Dim CodeMod As CodeModule

    Set VBProj = libro.VBProject

    For Each VBComp In VBProj.VBComponents
        If VBComp.Type = vbext_ct_Document Then
            Set CodeMod = VBComp.CodeModule
            With CodeMod
                .DeleteLines 1, .CountOfLines
            End With
        Else
            VBProj.VBComponents.Remove VBComp
        End If
    Next VBComp
End Sub