Programs & Examples On #Hardcoded

Parameters or variables in a program are considered as hard-coded, if they represent a constant value that can't be changed by configuration or via any kind of interface. The only way to change them is to modify the program itself.

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

When you call "https://darkorbit.com/" your server figures that it's missing "www" so it redirects the call to "http://www.darkorbit.com/" and then to "https://www.darkorbit.com/", your WebView call is blocked at the first redirection as it's a "http" call. You can call "https://www.darkorbit.com/" instead and it will solve the issue.

How to import JSON File into a TypeScript file?

Aonepathan's one-liner was working for me until a recent typescript update.

I found Jecelyn Yeen's post which suggests posting this snippet into your TS Definition file

add file typings.d.ts to the project's root folder with below content

declare module "*.json" {
    const value: any;
    export default value;
}

and then import your data like this:

import * as data from './example.json';

update July 2019:

Typescript 2.9 (docs) introduced a better, smarter solution. Steps:

  1. Add resolveJsonModule support with this line in your tsconfig.json file:
"compilerOptions": {
    ...
    "resolveJsonModule": true
  }

the import statement can now assumes a default export:

import data from './example.json';

and intellisense will now check the json file to see whether you can use Array etc. methods. pretty cool.

Get ConnectionString from appsettings.json instead of being hardcoded in .NET Core 2.0 App

It's not fancy I known but you could use a callback class, create a hostbuilder and set the configuration to a static property.

For asp core 2.2:

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System;

namespace Project
{
    sealed class Program
    {
        #region Variables
        /// <summary>
        /// Last loaded configuration
        /// </summary>
        private static IConfiguration _Configuration;
        #endregion

        #region Properties
        /// <summary>
        /// Default application configuration
        /// </summary>
        internal static IConfiguration Configuration
        {
            get
            {
                // None configuration yet?
                if (Program._Configuration == null)
                {
                    // Create the builder using a callback class
                    IWebHostBuilder builder = WebHost.CreateDefaultBuilder().UseStartup<CallBackConfiguration>();

                    // Build everything but do not initialize it
                    builder.Build();
                }

                // Current configuration
                return Program._Configuration;
            }

            // Update configuration
            set => Program._Configuration = value;
        }
        #endregion

        #region Public
        /// <summary>
        /// Start the webapp
        /// </summary>
        public static void Main(string[] args)
        {
            // Create the builder using the default Startup class
            IWebHostBuilder builder = WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();

            // Build everything and run it
            using (IWebHost host = builder.Build())
                host.Run();
        }
        #endregion


        #region CallBackConfiguration
        /// <summary>
        /// Aux class to callback configuration
        /// </summary>
        private class CallBackConfiguration
        {
            /// <summary>
            /// Callback with configuration
            /// </summary>
            public CallBackConfiguration(IConfiguration configuration)
            {
                // Update the last configuration
                Program.Configuration = configuration;
            }

            /// <summary>
            /// Do nothing, just for compatibility
            /// </summary>
            public void Configure(IApplicationBuilder app, IHostingEnvironment env)
            {
                //
            }
        }
        #endregion
    }
}

So now on you just use the static Program.Configuration at any other class you need it.

Can't access 127.0.0.1

Just one command did the work

netsh http add iplisten 127.0.0.1

Referencing value in a closed Excel workbook using INDIRECT?

OK,

Here's a dinosaur method for you on Office 2010.

Write the full address you want using concatenate (the "&" method of combining text).

Do this for all the addresses you need. It should look like:

="="&"'\FULL NETWORK ADDRESS including [Spreadsheet Name]"&W3&"'!$w4"

The W3 is a dynamic reference to what sheet I am using, the W4 is the cell I want to get from the sheet.

Once you have this, start up a macro recording session. Copy the cell and paste it into another. I pasted it into a merged cell and it gave me the classic "Same size" error. But one thing it did was paste the resulting text from my concatenate (including that extra "=").

Copy over however many you did this for. Then, go into each pasted cell, select he text and just hit enter. It updates it to an active direct reference.

Once you have finished, put the cursor somewhere nice and stop the macro. Assign it to a button and you are done.

It is a bit of a PITA to do this the first time, but once you have done it, you have just made the square peg fit that daamned round hole.

PHP: maximum execution time when importing .SQL data file

The following might help you:

ini_set('max_execution_time', 100000);

And in your mysql - max_allowed_packet=100M in some cases where queries are too long sql also produce and error "MySQL server has gone away";

Change the values to whatever you need.

Passing data between controllers in Angular JS?

I think the

best way

is to use $localStorage. (Works all the time)

app.controller('ProductController', function($scope, $localStorage) {
    $scope.setSelectedProduct = function(selectedObj){
        $localStorage.selectedObj= selectedObj;
    };
});

Your cardController will be

app.controller('CartController', function($scope,$localStorage) { 
    $scope.selectedProducts = $localStorage.selectedObj;
    $localStorage.$reset();//to remove
});

You can also add

if($localStorage.selectedObj){
    $scope.selectedProducts = $localStorage.selectedObj;
}else{
    //redirect to select product using $location.url('/select-product')
}

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

found this and it worked for me.

strSQL = "SELECT * FROM DataTable" 

'Where DataTable is the Named range

How can I run SQL statements on a named range within an excel sheet?

Bootstrap 3 scrollable div for table

You can use too

style="overflow-y: scroll; height:150px; width: auto;"

It's works for me

How to get resources directory path programmatically

import org.springframework.core.io.ClassPathResource;

...

File folder = new ClassPathResource("sql").getFile();
File[] listOfFiles = folder.listFiles();

It is worth noting that this will limit your deployment options, ClassPathResource.getFile() only works if the container has exploded (unzipped) your war file.

Using setDate in PreparedStatement

tl;dr

With JDBC 4.2 or later and java 8 or later:

myPreparedStatement.setObject( … , myLocalDate  )

…and…

myResultSet.getObject( … , LocalDate.class )

Details

The Answer by Vargas is good about mentioning java.time types but refers only to converting to java.sql.Date. No need to convert if your driver is updated.

java.time

The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat. The Joda-Time team also advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.

LocalDate

In java.time, the java.time.LocalDate class represents a date-only value without time-of-day and without time zone.

If using a JDBC driver compliant with JDBC 4.2 or later spec, no need to use the old java.sql.Date class. You can pass/fetch LocalDate objects directly to/from your database via PreparedStatement::setObject and ResultSet::getObject.

LocalDate localDate = LocalDate.now( ZoneId.of( "America/Montreal" ) );
myPreparedStatement.setObject( 1 , localDate  );

…and…

LocalDate localDate = myResultSet.getObject( 1 , LocalDate.class );

Before JDBC 4.2, convert

If your driver cannot handle the java.time types directly, fall back to converting to java.sql types. But minimize their use, with your business logic using only java.time types.

New methods have been added to the old classes for conversion to/from java.time types. For java.sql.Date see the valueOf and toLocalDate methods.

java.sql.Date sqlDate = java.sql.Date.valueOf( localDate );

…and…

LocalDate localDate = sqlDate.toLocalDate();

Placeholder value

Be wary of using 0000-00-00 as a placeholder value as shown in your Question’s code. Not all databases and other software can handle going back that far in time. I suggest using something like the commonly-used Unix/Posix epoch reference date of 1970, 1970-01-01.

LocalDate EPOCH_DATE = LocalDate.ofEpochDay( 0 ); // 1970-01-01 is day 0 in Epoch counting.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

AngularJS: factory $http.get JSON file

++ This worked for me. It's vanilla javascirpt and good for use cases such as de-cluttering when testing with ngMocks library:

<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!--  Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>

This is your javascript file that contains the JSON data

// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
     "Title": "Star Wars",
     "Year": "1983",
     "Rated": "N/A",
     "Released": "01 May 1983",
     "Runtime": "N/A",
     "Genre": "Action, Adventure, Sci-Fi",
     "Director": "N/A",
     "Writer": "N/A",
     "Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
     "Plot": "N/A",
     "Language": "English",
     "Country": "USA",
     "Awards": "N/A",
     "Poster": "N/A",
     "Metascore": "N/A",
     "imdbRating": "7.9",
     "imdbVotes": "342",
     "imdbID": "tt0251413",
     "Type": "game",
     "Response": "True"
};

Finally, work with the JSON data anywhere in your code

// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;

Note:- This is great for testing and even karma.conf.js accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development environment.

// extract from karma.conf.js
files: [
     'json-data/JSONSearchResultHardcodedData.js',
     'json-data/JSONFindByIdResults.js'
     ...
]

Hope this helps.

++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733

UPDATE

An easier way that worked for me is just include a function at the bottom of the code returning whatever JSON.

// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
      return {
         "Title": "Bri Squared",
         "Year": "2011",
         "Rated": "N/A",
         "Released": "N/A",
         "Runtime": "N/A",
         "Genre": "Comedy",
         "Director": "Joy Gohring",
         "Writer": "Briana Lane",
         "Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
         "Plot": "N/A",
         "Language": "English",
         "Country": "USA",
         "Awards": "N/A",
         "Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ@@._V1_SX300.jpg",
         "Metascore": "N/A",
         "imdbRating": "8.2",
         "imdbVotes": "5",
         "imdbID": "tt1937109",
         "Type": "movie",
         "Response": "True"
   }
}

Java - Search for files in a directory

public class searchingFile 
{
     static String path;//defining(not initializing) these variables outside main 
     static String filename;//so that recursive function can access them
     static int counter=0;//adding static so that can be accessed by static methods 

    public static void main(String[] args) //main methods begins
    {
        Scanner sc=new Scanner(System.in);
        System.out.println("Enter the path : ");
        path=sc.nextLine(); //storing path in path variable
        System.out.println("Enter file name : ");
        filename=sc.nextLine(); //storing filename in filename variable
        searchfile(path);//calling our recursive function and passing path as argument
        System.out.println("Number of locations file found at : "+counter);//Printing occurences

    }

    public static String searchfile(String path)//declaring recursive function having return 
                                                //type and argument both strings

    {
        File file=new File(path);//denoting the path
        File[] filelist=file.listFiles();//storing all the files and directories in array

    for (int i = 0; i < filelist.length; i++) //for loop for accessing all resources
    {
        if(filelist[i].getName().equals(filename))//if loop is true if resource name=filename
        {
            System.out.println("File is present at : "+filelist[i].getAbsolutePath());
            //if loop is true,this will print it's location
            counter++;//counter increments if file found
        }
        if(filelist[i].isDirectory())// if resource is a directory,we want to inside that folder
        {
            path=filelist[i].getAbsolutePath();//this is the path of the subfolder
            searchfile(path);//this path is again passed into the searchfile function 
                             //and this countinues untill we reach a file which has
                             //no sub directories

        }
    }
    return path;// returning path variable as it is the return type and also 
                // because function needs path as argument.

    }   
}

Android: How do bluetooth UUIDs work?

UUID is just a number. It has no meaning except you create on the server side of an Android app. Then the client connects using that same UUID.

For example, on the server side you can first run uuid = UUID.randomUUID() to generate a random number like fb36491d-7c21-40ef-9f67-a63237b5bbea. Then save that and then hard code that into your listener program like this:

 UUID uuid = UUID.fromString("fb36491d-7c21-40ef-9f67-a63237b5bbea"); 

Your Android server program will listen for incoming requests with that UUID like this:

    BluetoothServerSocket server = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("anyName", uuid);

BluetoothSocket socket = server.accept();

Java Spring - How to use classpath to specify a file location?

Are we talking about standard java.io.FileReader? Won't work, but it's not hard without it.

/src/main/resources maven directory contents are placed in the root of your CLASSPATH, so you can simply retrieve it using:

InputStream is = getClass().getResourceAsStream("/storedProcedures.sql");

If the result is not null (resource not found), feel free to wrap it in a reader:

Reader reader = new InputStreamReader(is);

SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application

One of my SQL jobs had the same issue. It involved uploadaing data from one server to another. The error occurred because I was using sql Server Agent Service Account. I created a Credential using a UserId (that uses Window authentication) common to all servers. Then created a Proxy using this credential. Used the proxy in sql server job and it is running fine.

How to pass command line argument to gnuplot?

You may use trick in unix/linux environment:

  1. in gnuplot program: plot "/dev/stdin" ...

  2. In command line: gnuplot program.plot < data.dat

How to implement band-pass Butterworth filter with Scipy.signal.butter

You could skip the use of buttord, and instead just pick an order for the filter and see if it meets your filtering criterion. To generate the filter coefficients for a bandpass filter, give butter() the filter order, the cutoff frequencies Wn=[low, high] (expressed as the fraction of the Nyquist frequency, which is half the sampling frequency) and the band type btype="band".

Here's a script that defines a couple convenience functions for working with a Butterworth bandpass filter. When run as a script, it makes two plots. One shows the frequency response at several filter orders for the same sampling rate and cutoff frequencies. The other plot demonstrates the effect of the filter (with order=6) on a sample time series.

from scipy.signal import butter, lfilter


def butter_bandpass(lowcut, highcut, fs, order=5):
    nyq = 0.5 * fs
    low = lowcut / nyq
    high = highcut / nyq
    b, a = butter(order, [low, high], btype='band')
    return b, a


def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
    b, a = butter_bandpass(lowcut, highcut, fs, order=order)
    y = lfilter(b, a, data)
    return y


if __name__ == "__main__":
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.signal import freqz

    # Sample rate and desired cutoff frequencies (in Hz).
    fs = 5000.0
    lowcut = 500.0
    highcut = 1250.0

    # Plot the frequency response for a few different orders.
    plt.figure(1)
    plt.clf()
    for order in [3, 6, 9]:
        b, a = butter_bandpass(lowcut, highcut, fs, order=order)
        w, h = freqz(b, a, worN=2000)
        plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)

    plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
             '--', label='sqrt(0.5)')
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('Gain')
    plt.grid(True)
    plt.legend(loc='best')

    # Filter a noisy signal.
    T = 0.05
    nsamples = T * fs
    t = np.linspace(0, T, nsamples, endpoint=False)
    a = 0.02
    f0 = 600.0
    x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
    x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
    x += a * np.cos(2 * np.pi * f0 * t + .11)
    x += 0.03 * np.cos(2 * np.pi * 2000 * t)
    plt.figure(2)
    plt.clf()
    plt.plot(t, x, label='Noisy signal')

    y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
    plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
    plt.xlabel('time (seconds)')
    plt.hlines([-a, a], 0, T, linestyles='--')
    plt.grid(True)
    plt.axis('tight')
    plt.legend(loc='upper left')

    plt.show()

Here are the plots that are generated by this script:

Frequency response for several filter orders

enter image description here

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

JPA or JDBC, how are they different?

JDBC is the predecessor of JPA.

JDBC is a bridge between the Java world and the databases world. In JDBC you need to expose all dirty details needed for CRUD operations, such as table names, column names, while in JPA (which is using JDBC underneath), you also specify those details of database metadata, but with the use of Java annotations.

So JPA creates update queries for you and manages the entities that you looked up or created/updated (it does more as well).

If you want to do JPA without a Java EE container, then Spring and its libraries may be used with the very same Java annotations.

What does the 'u' symbol mean in front of string values?

The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.

You can create a Unicode string multiple ways:

>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'

But the real reason is to represent something like this (translation here):

>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????

For the most part, Unicode and non-Unicode strings are interoperable on Python 2.

There are other symbols you will see, such as the "raw" symbol r for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.

>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'

Unicode and non-Unicode strings can be equal on Python 2:

>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True

but not on Python 3:

>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False

selecting an entire row based on a variable excel vba

I solved the problem for me by addressing also the worksheet first:

ws.rows(x & ":" & y).Select

without the reference to the worksheet (ws) I got an error.

How to use System.Net.HttpClient to post a complex type?

The generic HttpRequestMessage<T> has been removed. This :

new HttpRequestMessage<Widget>(widget)

will no longer work.

Instead, from this post, the ASP.NET team has included some new calls to support this functionality:

HttpClient.PostAsJsonAsync<T>(T value) sends “application/json”
HttpClient.PostAsXmlAsync<T>(T value) sends “application/xml”

So, the new code (from dunston) becomes:

Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268");
client.PostAsJsonAsync("api/test", widget)
    .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );

Get img src with PHP

There could be two easy solutions:

  1. HTML it self is an xml so you can use any XML parsing method if u load the tag as XML and get its attribute tottally dynamically even dom data attribute (like data-time or anything).....
  2. Use any html parser for php like http://mbe.ro/2009/06/21/php-html-to-array-working-one/ or php parse html to array Google this

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

hardcoded string "row three", should use @string resource

You can go to Design mode and select "Fix" at the bottom of the warning. Then a pop up will appear (seems like it's going to register the new string) and voila, the error is fixed.

Increasing Google Chrome's max-connections-per-server limit to more than 6

I don't know that you can do it in Chrome outside of Windows -- some Googling shows that Chrome (and therefore possibly Chromium) might respond well to a certain registry hack.

However, if you're just looking for a simple solution without modifying your code base, have you considered Firefox? In the about:config you can search for "network.http.max" and there are a few values in there that are definitely worth looking at.

Also, for a device that will not be moving (i.e. it is mounted in a fixed location) you should consider not using Wi-Fi (even a Home-Plug would be a step up as far as latency / stability / dropped connections go).

jquery remove "selected" attribute of option?

This works:

$("#myselect").find('option').removeAttr("selected");

or

$("#myselect").find('option:selected').removeAttr("selected");

jsFiddle

MySQL Trigger after update only if row has changed

Use the following query to see which rows have changes:

(select * from inserted) except (select * from deleted)

The results of this query should consist of all the new records that are different from the old ones.

SQL 'like' vs '=' performance

You are asking the wrong question. In databases is not the operator performance that matters, is always the SARGability of the expression, and the coverability of the overall query. Performance of the operator itself is largely irrelevant.

So, how do LIKE and = compare in terms of SARGability? LIKE, when used with an expression that does not start with a constant (eg. when used LIKE '%something') is by definition non-SARGabale. But does that make = or LIKE 'something%' SARGable? No. As with any question about SQL performance the answer does not lie with the query of the text, but with the schema deployed. These expression may be SARGable if an index exists to satisfy them.

So, truth be told, there are small differences between = and LIKE. But asking whether one operator or other operator is 'faster' in SQL is like asking 'What goes faster, a red car or a blue car?'. You should eb asking questions about the engine size and vechicle weight, not about the color... To approach questions about optimizing relational tables, the place to look is your indexes and your expressions in the WHERE clause (and other clauses, but it usually starts with the WHERE).

How can I pass an argument to a PowerShell script?

Call the script from a batch file (*.bat) or CMD

PowerShell Core

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param1 Hello -Param2 World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "path-to-script/Script.ps1 -Param1 Hello -Param2 World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello -Param2 World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello World"

pwsh.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param2 World Hello"

PowerShell

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param1 Hello -Param2 World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "path-to-script/Script.ps1 -Param1 Hello -Param2 World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello -Param2 World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 Hello World"

powershell.exe -NoLogo -ExecutionPolicy Bypass -Command "./Script.ps1 -Param2 World Hello"

Call from PowerShell

PowerShell Core or Windows PowerShell

& path-to-script/Script.ps1 -Param1 Hello -Param2 World
& ./Script.ps1 -Param1 Hello -Param2 World

Script.ps1 - Script Code

param(
    [Parameter(Mandatory=$True, Position=0, ValueFromPipeline=$false)]
    [System.String]
    $Param1,

    [Parameter(Mandatory=$True, Position=1, ValueFromPipeline=$false)]
    [System.String]
    $Param2
)

Write-Host $Param1
Write-Host $Param2

How can I create a blank/hardcoded column in a sql query?

Thank you, in PostgreSQL this works for boolean

SELECT
hat,
shoe,
boat,
false as placeholder
FROM
objects

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

I was able to generate

static {
    WSDL_LOCATION = null;
}

by configuring pom file to have a null for wsdlurl:

    <plugin>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-codegen-plugin</artifactId>
        <executions>
            <execution>
                <id>generate-sources</id>
                <phase>generate-sources</phase>
                <configuration>
                    <sourceRoot>${basedir}/target/generated/src/main/java</sourceRoot>
                    <wsdlOptions>
                        <wsdlOption>
                            <wsdl>${basedir}/src/main/resources/service.wsdl</wsdl>
                            <extraargs>
                                <extraarg>-client</extraarg>
                                <extraarg>-wsdlLocation</extraarg>
                                <wsdlurl />
                            </extraargs>
                        </wsdlOption>
                    </wsdlOptions>
                </configuration>
                <goals>
                    <goal>wsdl2java</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

getString Outside of a Context or Activity

In MyApplication, which extends Application:

public static Resources resources;

In MyApplication's onCreate:

resources = getResources();

Now you can use this field from anywhere in your application.

How do you use NSAttributedString?

- (void)changeColorWithString:(UILabel *)uilabel stringToReplace:(NSString *) stringToReplace uiColor:(UIColor *) uiColor{
    NSMutableAttributedString *text =
    [[NSMutableAttributedString alloc]
     initWithAttributedString: uilabel.attributedText];

    [text addAttribute: NSForegroundColorAttributeName value:uiColor range:[uilabel.text rangeOfString:stringToReplace]];

    [uilabel setAttributedText: text];

}

Convert list of ASCII codes to string (byte array) in Python

This is reviving an old question, but in Python 3, you can just use bytes directly:

>>> bytes([17, 24, 121, 1, 12, 222, 34, 76])
b'\x11\x18y\x01\x0c\xde"L'

Specify system property to Maven project

If your test and webapp are in the same Maven project, you can use a property in the project POM. Then you can filter certain files which will allow Maven to set the property in those files. There are different ways to filter, but the most common is during the resources phase - http://books.sonatype.com/mvnref-book/reference/resource-filtering-sect-description.html

If the test and webapp are in different Maven projects, you can put the property in settings.xml, which is in your maven repository folder (C:\Documents and Settings\username.m2) on Windows. You will still need to use filtering or some other method to read the property into your test and webapp.

What is the easiest way to initialize a std::vector with hardcoded elements?

If you don't want to use boost, but want to enjoy syntax like

std::vector<int> v;
v+=1,2,3,4,5;

just include this chunk of code

template <class T> class vector_inserter{
public:
    std::vector<T>& v;
    vector_inserter(std::vector<T>& v):v(v){}
    vector_inserter& operator,(const T& val){v.push_back(val);return *this;}
};
template <class T> vector_inserter<T> operator+=(std::vector<T>& v,const T& x){
    return vector_inserter<T>(v),x;
}

Python recursive folder read

If you prefer an (almost) Oneliner:

from pathlib import Path

lookuppath = '.' #use your path
filelist = [str(item) for item in Path(lookuppath).glob("**/*") if Path(item).is_file()]

In this case you will get a list with just the paths of all files located recursively under lookuppath. Without str() you will get PosixPath() added to each path.

JAX-WS and BASIC authentication, when user names and passwords are in a database

BindingProvider.USERNAME_PROPERTY and BindingProvider.PASSWORD_PROPERTY are matching HTTP Basic Authentication mechanism that enable authentication process at the HTTP level and not at the application nor servlet level.

Basically, only the HTTP server will know the username and the password (and eventually application according to HTTP/application server specification, such with Apache/PHP). With Tomcat/Java, add a login config BASIC in your web.xml and appropriate security-constraint/security-roles (roles that will be later associated to users/groups of real users).

<login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>YourRealm</realm-name>
</login-config>

Then, connect the realm at the HTTP server (or application server) level with the appropriate user repository. For tomcat you may look at JAASRealm, JDBCRealm or DataSourceRealm that may suit your needs.

http://tomcat.apache.org/tomcat-6.0-doc/realm-howto.html

How to list the files inside a JAR file?

I've ported acheron55's answer to Java 7 and closed the FileSystem object. This code works in IDE's, in jar files and in a jar inside a war on Tomcat 7; but note that it does not work in a jar inside a war on JBoss 7 (it gives FileSystemNotFoundException: Provider "vfs" not installed, see also this post). Furthermore, like the original code, it is not thread safe, as suggested by errr. For these reasons I have abandoned this solution; however, if you can accept these issues, here is my ready-made code:

import java.io.IOException;
import java.net.*;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Collections;

public class ResourceWalker {

    public static void main(String[] args) throws URISyntaxException, IOException {
        URI uri = ResourceWalker.class.getResource("/resources").toURI();
        System.out.println("Starting from: " + uri);
        try (FileSystem fileSystem = (uri.getScheme().equals("jar") ? FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap()) : null)) {
            Path myPath = Paths.get(uri);
            Files.walkFileTree(myPath, new SimpleFileVisitor<Path>() { 
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    System.out.println(file);
                    return FileVisitResult.CONTINUE;
                }
            });
        }
    }
}

How do you get the current project directory from C# code when creating a custom MSBuild task?

Try this, its simple

HttpContext.Current.Server.MapPath("~/FolderName/");

How do I set a textbox's value using an anchor with jQuery?

Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')

Numeric for loop in Django templates

Unfortunately, that's not supported in the Django template language. There are a couple of suggestions, but they seem a little complex. I would just put a variable in the context:

...
render_to_response('foo.html', {..., 'range': range(10), ...}, ...)
...

and in the template:

{% for i in range %}
     ...
{% endfor %}

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

Python: read all text file lines in loop

Just iterate over each line in the file. Python automatically checks for the End of file and closes the file for you (using the with syntax).

with open('fileName', 'r') as f:
    for line in f:
       if 'str' in line:
           break

c# replace \" characters

Where do these characters occur? Do you see them if you examine the XML data in, say, notepad? Or do you see them when examining the XML data in the debugger. If it is the latter, they are only escape characters for the " characters, and so part of the actual XML data.

Modifying a query string without reloading the page

I've used the following JavaScript library with great success:

https://github.com/balupton/jquery-history

It supports the HTML5 history API as well as a fallback method (using #) for older browsers.

This library is essentially a polyfill around `history.pushState'.

How to load a jar file at runtime

This works for me:

File file  = new File("c:\\myjar.jar");

URL url = file.toURL();  
URL[] urls = new URL[]{url};

ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.mypackage.myclass");

How to create a user in Django?

Bulk user creation with set_password

I you are creating several test users, bulk_create is much faster, but we can't use create_user with it.

set_password is another way to generate the hashed passwords:

def users_iterator():
    for i in range(nusers):
        is_superuser = (i == 0)
        user = User(
            first_name='First' + str(i),
            is_staff=is_superuser,
            is_superuser=is_superuser,
            last_name='Last' + str(i),
            username='user' + str(i),
        )
        user.set_password('asdfqwer')
        yield user

class Command(BaseCommand):
    def handle(self, **options):
        User.objects.bulk_create(iter(users_iterator()))

Question specific about password hashing: How to use Bcrypt to encrypt passwords in Django

Tested in Django 1.9.

How to show what a commit did?

This is one way I know of. With git, there always seems to be more than one way to do it.

git log -p commit1 commit2

How are booleans formatted in Strings in Python?

If you want True False use:

"%s %s" % (True, False)

because str(True) is 'True' and str(False) is 'False'.

or if you want 1 0 use:

"%i %i" % (True, False)

because int(True) is 1 and int(False) is 0.

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

There is an issue in php version less than 5.2.6. You may need to upgrade the version of php.

Stopping a thread after a certain amount of time

This will work if you are not blocking.

If you are planing on doing sleeps, its absolutely imperative that you use the event to do the sleep. If you leverage the event to sleep, if someone tells you to stop while "sleeping" it will wake up. If you use time.sleep() your thread will only stop after it wakes up.

import threading
import time

duration = 2

def main():
    t1_stop = threading.Event()
    t1 = threading.Thread(target=thread1, args=(1, t1_stop))

    t2_stop = threading.Event()
    t2 = threading.Thread(target=thread2, args=(2, t2_stop))

    time.sleep(duration)
    # stops thread t2
    t2_stop.set()

def thread1(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

def thread2(arg1, stop_event):
    while not stop_event.is_set():
        stop_event.wait(timeout=5)

JavaScript pattern for multiple constructors

Going further with eruciform's answer, you can chain your new call into your init method.

function Foo () {
    this.bar = 'baz';
}

Foo.prototype.init_1 = function (bar) {
    this.bar = bar;
    return this;
};

Foo.prototype.init_2 = function (baz) {
    this.bar = 'something to do with '+baz;
    return this;
};

var a = new Foo().init_1('constructor 1');
var b = new Foo().init_2('constructor 2');

How to set image in circle in swift

You can simple create extension:

import UIKit

extension UIImageView {

   func setRounded() {
      let radius = CGRectGetWidth(self.frame) / 2
      self.layer.cornerRadius = radius
      self.layer.masksToBounds = true
   }
}

and use it as below:

imageView.setRounded()

Can't push image to Amazon ECR - fails with "no basic auth credentials"

If it helps anyone...

My problem was that I had to use the --profile option in order to authenticate with the proper profile from the credentials file.

Next, I had ommitted the --region [region_name] command, which also gave the "no basic auth credentials" error.

The solution for me was changing my command from this:

aws ecr get-login

To this:

aws --profile [profile_name] ecr get-login --region [region_name]

Example:

aws --profile foo ecr get-login --region us-east-1

Hope that helps someone!

Is it possible to animate scrollTop with jQuery?

If you want to move down at the end of the page (so you don't need to scroll down to bottom) , you can use:

$('body').animate({ scrollTop: $(document).height() });

How to avoid a System.Runtime.InteropServices.COMException?

I came across System.Runtime.InteropServices.COMException while opening a project solution. Sometimes user doesn't have enough priveleges to run some COM Methods. I ran Visual Studio as Administrator and the exception was gone.

Using PowerShell credentials without being prompted for a password

Solution

$userName = 'test-domain\test-login'
$password = 'test-password'

$pwdSecureString = ConvertTo-SecureString -Force -AsPlainText $password
$credential = New-Object -TypeName System.Management.Automation.PSCredential `
    -ArgumentList $userName, $pwdSecureString

For Build Machines
In the previous code replace user name and password values by secret ("hidden from logs") environment variables of your build-machine

Test results by

'# Results'
$credential.GetNetworkCredential().Domain
$credential.GetNetworkCredential().UserName
$credential.GetNetworkCredential().Password

and you'll see

# Results
test-domain
test-login
test-password

How to find the duration of difference between two dates in java?

You can create a method like

public long getDaysBetweenDates(Date d1, Date d2){
return TimeUnit.MILLISECONDS.toDays(d1.getTime() - d2.getTime());
}

This method will return the number of days between the 2 days.

SVN: Is there a way to mark a file as "do not commit"?

Subversion does not have a built-in "do not commit" / "ignore on commit" feature, as of February 2016 / version 1.9. This answer is a non-ideal command-line workaround

As the OP states, TortoiseSVN has a built in changelist, "ignore-on-commit", which is automatically excluded from commits. The command-line client does not have this, so you need to use multiple changelists to accomplish this same behavior (with caveats):

  • one for work you want to commit [work]
  • one for things you want to ignore [ignore-on-commit]

Since there's precedent with TortoiseSVN, I use "ignore-on-commit" in my examples for the files I don't want to commit. I'll use "work" for the files I do, but you could pick any name you wanted.

First, add all files to a changelist named "work". This must be run from the root of your working copy:

svn cl work . -R

This will add all files in the working copy recursively to the changelist named "work". There is a disadvantage to this - as new files are added to the working copy, you'll need to specifically add the new files or they won't be included. Second, if you have to run this again you'll then need to re-add all of your "ignore-on-commit" files again. Not ideal - you could start maintaining your own 'ignore' list in a file as others have done.

Then, for the files you want to exclude:

svn cl ignore-on-commit path\to\file-to-ignore

Because files can only be in one changelist, running this addition after your previous "work" add will remove the file you want to ignore from the "work" changelist and put it in the "ignore-on-commit" changelist.

When you're ready to commit your modified files you do wish to commit, you'd then simply add "--cl work" to your commit:

svn commit --cl work -m "message"

Here's what a simple example looks like on my machine:

D:\workspace\trunk>svn cl work . -R
Skipped '.'
Skipped 'src'
Skipped 'src\conf'
A [work] src\conf\db.properties
Skipped 'src\java'
Skipped 'src\java\com'
Skipped 'src\java\com\corp'
Skipped 'src\java\com\corp\sample'
A [work] src\java\com\corp\sample\Main.java
Skipped 'src\java\com\corp\sample\controller'
A [work] src\java\com\corp\sample\controller\Controller.java
Skipped 'src\java\com\corp\sample\model'
A [work] src\java\com\corp\sample\model\Model.java
Skipped 'src\java\com\corp\sample\view'
A [work] src\java\com\corp\sample\view\View.java
Skipped 'src\resource'
A [work] src\resource\icon.ico
Skipped 'src\test'

D:\workspace\trunk>svn cl ignore-on-commit src\conf\db.properties
D [work] src\conf\db.properties
A [ignore-on-commit] src\conf\db.properties

D:\workspace\trunk>svn status

--- Changelist 'work':
        src\java\com\corp\sample\Main.java
        src\java\com\corp\sample\controller\Controller.java
        src\java\com\corp\sample\model\Model.java
M       src\java\com\corp\sample\view\View.java
        src\resource\icon.ico

--- Changelist 'ignore-on-commit':
M       src\conf\db.properties

D:\workspace\trunk>svn commit --cl work -m "fixed refresh issue"
Sending        src\java\com\corp\sample\view\View.java
Transmitting file data .done
Committing transaction...
Committed revision 9.

An alternative would be to simply add every file you wish to commit to a 'work' changelist, and not even maintain an ignore list, but this is a lot of work, too. Really, the only simple, ideal solution is if/when this gets implemented in SVN itself. There's a longstanding issue about this in the Subversion issue tracker, SVN-2858, in the event this changes in the future.

Local package.json exists, but node_modules missing

npm start runs a script that the app maker built for easy starting of the app npm install installs all the packages in package.json

run npm install first

then run npm start

Extracting text from a PDF file using PDFMiner in python?

terrific answer from DuckPuncher, for Python3 make sure you install pdfminer2 and do:

import io

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage


def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = io.StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos = set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages,
                                  password=password,
                                  caching=caching,
                                  check_extractable=True):
        interpreter.process_page(page)



    fp.close()
    device.close()
    text = retstr.getvalue()
    retstr.close()
    return text

Assembly - JG/JNLE/JL/JNGE after CMP

The command JG simply means: Jump if Greater. The result of the preceding instructions is stored in certain processor flags (in this it would test if ZF=0 and SF=OF) and jump instruction act according to their state.

Java: Multiple class declarations in one file

No. You can't. But it is very possible in Scala:

class Foo {val bar = "a"}
class Bar {val foo = "b"}

Div with margin-left and width:100% overflowing on the right side

I realise this is an old post but this might benefit somebody who, like me, has come to this page from a google search and is at their wits end.

None of the other answers given here worked for me and I had already given up hope, but today I was searching for a solution to another similar problem with divs, which I found answered multiple times on SO. The accepted answer worked for my div, and I had the sudden notion to try it for my previous textbox issue - and it worked! The solution:

add box-sizing: border-box to the style of the textbox.

To add this to all multi-line textboxes using CSS, add the following to your style sheet:

textarea
{
  box-sizing: border-box;
}

Thanks to thirtydot for the solution at

width: 100%-padding?

and

Content of div is longer then div itself when width is set to 100%?

NLTK and Stopwords Fail #lookuperror

I tried from ubuntu terminal and I don't know why the GUI didn't show up according to tttthomasssss answer. So I followed the comment from KLDavenport and it worked. Here is the summary:

Open your terminal/command-line and type python then

>>> import nltk .>>> nltk.download("stopwords")

This will store the stopwords corpus under the nltk_data. For my case it was /home/myusername/nltk_data/corpora/stopwords.

If you need another corpus then visit nltk data and find the corpus with their ID. Then use the ID to download like we did for stopwords.

How to check if a symlink exists

If you are testing for file existence you want -e not -L. -L tests for a symlink.

How exactly does the python any() function work?

It's because the iterable is

(x > 0 for x in list)

Note that x > 0 returns either True or False and thus you have an iterable of booleans.

PHPUnit assert that an exception was thrown?

You can use assertException extension to assert more than one exception during one test execution.

Insert method into your TestCase and use:

public function testSomething()
{
    $test = function() {
        // some code that has to throw an exception
    };
    $this->assertException( $test, 'InvalidArgumentException', 100, 'expected message' );
}

I also made a trait for lovers of nice code..

jQuery ajax success error

Try to set response dataType property directly:

dataType: 'text'

and put

die(''); 

in the end of your php file. You've got error callback cause jquery cannot parse your response. In anyway, you may use a "complete:" callback, just to make sure your request has been processed.

How to initialize a static array?

If you are creating an array then there is no difference, however, the following is neater:

String[] suit = {
  "spades", 
  "hearts", 
  "diamonds", 
  "clubs"  
};

But, if you want to pass an array into a method you have to call it like this:

myMethod(new String[] {"spades", "hearts"});

myMethod({"spades", "hearts"}); //won't compile!

CSS Div Background Image Fixed Height 100% Width

But the thing is that the .chapter class is not dynamic you're declaring a height:1200px

so it's better to use background:cover and set with media queries specific height's for popular resolutions.

How to run a program in Atom Editor?

You can try to use the runner in atom Hit Ctrl+R (Alt+R on Win/Linux) to launch the runner for the active window. Hit Ctrl+Shift+R (Alt+Shift+R on Win/Linux) to run the currently selected text in the active window. Hit Ctrl+Shift+C to kill a currently running process. Hit Escape to close the runner window

How to remove all the null elements inside a generic list in one go?

I do not know of any in-built method, but you could just use linq:

parameterList = parameterList.Where(x => x != null).ToList();

What is the max size of VARCHAR2 in PL/SQL and SQL?

Not sure what you meant with "Can I increase the size of this variable without worrying about the SQL limit?". As long you do not try to insert a more than 4000 VARCHAR2 into a VARCHAR2 SQL column there is nothing to worry about.

Here is the exact reference (this is 11g but true also for 10g)

http://docs.oracle.com/cd/E11882_01/appdev.112/e17126/datatypes.htm

VARCHAR2 Maximum Size in PL/SQL: 32,767 bytes Maximum Size in SQL 4,000 bytes

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

As stated on Installing MySQL-python on mac :

pip uninstall MySQL-python
brew install mysql
pip install MySQL-python

Then test it :

python -c "import MySQLdb"

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

I have build such kind of application using approximatively the same approach except :

  • I cache the generated image on the disk and always generate two to three images in advance in a separate thread.
  • I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.

Whenever the user start zooming, I acquire the CGPDFPage and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context is like :

CGAffineTransform currentCTM = CGContextGetCTM(context);    
if (currentCTM.a == 1.0 && baseImage) {
    //Calculate ideal scale
    CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
    CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height; 
    CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);

    CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
    CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
    CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
    @synchronized(issue) { 
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
        pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
        CGContextConcatCTM(context, pdfToPageTransform);    
        CGContextDrawPDFPage(context, pdfPage);
    }
}

issue is the object containg the CGPDFDocumentRef. I synchronize the part where I access the pdfDoc property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef object do some internal caching that I did not find how to get rid of.

Read tab-separated file line into array

If you really want to split every word (bash meaning) into a different array index completely changing the array in every while loop iteration, @ruakh's answer is the correct approach. But you can use the read property to split every read word into different variables column1, column2, column3 like in this code snippet

while IFS=$'\t' read -r column1 column2 column3 ; do
  printf "%b\n" "column1<${column1}>"
  printf "%b\n" "column2<${column2}>"
  printf "%b\n" "column3<${column3}>"
done < "myfile"

to reach a similar result avoiding array index access and improving your code readability by using meaningful variable names (of course using columnN is not a good idea to do so).

Spring MVC Controller redirect using URL parameters instead of in response

You can have processForm() return a View object instead, and have it return the concrete type RedirectView which has a parameter for setExposeModelAttributes().

When you return a view name prefixed with "redirect:", Spring MVC transforms this to a RedirectView object anyway, it just does so with setExposeModelAttributes to true (which I think is an odd value to default to).

ld cannot find -l<library>

-Ldir
Add directory dir to the list of directories to be searched for -l.

Select All Rows Using Entity Framework

Old post I know, but using Select(x => x) can be useful to split the EF Core (or even just Linq) expression up into a query builder.

This is handy for adding dynamic conditions.

For example:

public async Task<User> GetUser(Guid userId, string userGroup, bool noTracking = false)
{
    IQueryable<User> queryable = _context.Users.Select(x => x);

    if(!string.IsNullOrEmpty(userGroup))
        queryable = queryable.Where(x => x.UserGroup == userGroup);

    if(noTracking)
        queryable = queryable.AsNoTracking();

    return await queryable.FirstOrDefaultAsync(x => x.userId == userId);
}

How to use MD5 in javascript to transmit a password

In response to jt. You are correct, the HTML with just the password is susceptible to the Man in the middle attack. However, you can seed it with a GUID from the server ...

$.post(
  'includes/login.php', 
  { user: username, pass: $.md5(password + GUID) },
   onLogin, 
  'json' );

This would defeat the Man-In-The middle ... in that the server would generate a new GUID for each attempt.

Is there a "goto" statement in bash?

I found out a way to do this using functions.

Say, for example, you have 3 choices: A, B, and C. A and Bexecute a command, but C gives you more info and takes you to the original prompt again. This can be done using functions.

Note that since the line containg function demoFunction is just setting up the function, you need to call demoFunction after that script so the function will actually run.

You can easily adapt this by writing multiple other functions and calling them if you need to "GOTO" another place in your shell script.

function demoFunction {
        read -n1 -p "Pick a letter to run a command [A, B, or C for more info] " runCommand

        case $runCommand in
            a|A) printf "\n\tpwd being executed...\n" && pwd;;
            b|B) printf "\n\tls being executed...\n" && ls;;
            c|C) printf "\n\toption A runs pwd, option B runs ls\n" && demoFunction;;
        esac
}

demoFunction

Create hyperlink to another sheet

I recorded a macro making a hiperlink. This resulted.

ActiveCell.FormulaR1C1 = "=HYPERLINK(""[Workbook.xlsx]Sheet1!A1"",""CLICK HERE"")"

How do I URl encode something in Node.js?

The built-in module querystring is what you're looking for:

var querystring = require("querystring");
var result = querystring.stringify({query: "SELECT name FROM user WHERE uid = me()"});
console.log(result);
#prints 'query=SELECT%20name%20FROM%20user%20WHERE%20uid%20%3D%20me()'

Python for and if on one line

You are producing a filtered list by using a list comprehension. i is still being bound to each and every element of that list, and the last element is still 'three', even if it was subsequently filtered out from the list being produced.

You should not use a list comprehension to pick out one element. Just use a for loop, and break to end it:

for elem in my_list:
    if elem == 'two':
        break

If you must have a one-liner (which would be counter to Python's philosophy, where readability matters), use the next() function and a generator expression:

i = next((elem for elem in my_list if elem == 'two'), None)

which will set i to None if there is no such matching element.

The above is not that useful a filter; your are essentially testing if the value 'two' is in the list. You can use in for that:

elem = 'two' if 'two' in my_list else None

Numpy: Divide each row by a vector element

As has been mentioned, slicing with None or with np.newaxes is a great way to do this. Another alternative is to use transposes and broadcasting, as in

(data.T - vector).T

and

(data.T / vector).T

For higher dimensional arrays you may want to use the swapaxes method of NumPy arrays or the NumPy rollaxis function. There really are a lot of ways to do this.

For a fuller explanation of broadcasting, see http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

Specify multiple attribute selectors in CSS

Just to add that there should be no space between the selector and the opening bracket.

td[someclass] 

will work. But

td [someclass] 

will not.

How do I see what character set a MySQL database / table / column is?

For columns:

SHOW FULL COLUMNS FROM table_name;

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Try the (unofficial) binaries in this site:

http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy

You can get the newest numpy x64 with or without Intel MKL libs for Python 2.7 or Python 3.

How can I store JavaScript variable output into a PHP variable?

You can solve this problem by using AJAX. You don't need to load JQuery for AJAX but it has a better error and success handling than native JS.

I would do it like so:

1) add an click eventlistener to all my anchors on the page. 2) on click, you can setup an ajax-request to your php, in the POST-DATA you set the anchor id or the text-value 3) the php gets the value and you can setup a request to your database. Then you return the value which you need and echo it to the ajax-request. 4) your success function of the ajax-request is doing some stuff

For more information about ajax-requests look back here:

-> Ajax-Request NATIVE https://blog.garstasio.com/you-dont-need-jquery/ajax/

A simple JQuery examle:

$("button").click(function(){
  $.ajax({url: "demo_test.txt", success: function(result){
    $("#div1").html(result);
  }});
});

How can I transform string to UTF-8 in C#?

@anothershrubery answer worked for me. I've made an enhancement using StringEntensions Class so I can easily convert any string at all in my program.

Method:

public static class StringExtensions
{
    public static string ToUTF8(this string text)
    {
        return Encoding.UTF8.GetString(Encoding.Default.GetBytes(text));
    }
}

Usage:

string myString = "Acción";
string strConverted = myString.ToUTF8();

Or simply:

string strConverted = "Acción".ToUTF8();

Disable native datepicker in Google Chrome

The code above doesn't set the value of the input element nor does it fire a change event. The code below works in Chrome and Firefox (not tested in other browsers):

$('input[type="date"]').click(function(e){
     e.preventDefault();
}).datepicker({
    onSelect: function(dateText){
        var d = new Date(dateText),
        dv = d.getFullYear().toString().pad(4)+'-'+(d.getMonth()+1).toString().pad(2)+'-'+d.getDate().toString().pad(2);
        $(this).val(dv).trigger('change');
    }
});

pad is a simple custom String method to pad strings with zeros (required)

Detect element content changes with jQuery

The browser will not fire the onchange event for <div> elements.

I think the reasoning behind this is that these elements won't change unless modified by javascript. If you are already having to modify the element yourself (rather than the user doing it), then you can just call the appropriate accompanying code at the same time that you modify the element, like so:

 $("#content").html('something').each(function() { });

You could also manually fire an event like this:

 $("#content").html('something').change();

If neither of these solutions work for your situation, could you please give more information on what you are specifically trying to accomplish?

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

You might be launching your application from a Product file which is not linked to the plugin file. Reset your workspace and launch using the MANIFEST.MF > Overview > Testing > Launch.

jQuery textbox change event

You can achieve it:

 $(document).ready(function(){              
     $('#textBox').keyup(function () {alert('changed');});
 });

or with change (handle copy paste with right click):

 $(document).ready(function(){              
     $('#textBox2').change(function () {alert('changed');});
 });

Here is Demo

Calculate distance between two points in google maps V3

//JAVA
    public Double getDistanceBetweenTwoPoints(Double latitude1, Double longitude1, Double latitude2, Double longitude2) {
    final int RADIUS_EARTH = 6371;

    double dLat = getRad(latitude2 - latitude1);
    double dLong = getRad(longitude2 - longitude1);

    double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(getRad(latitude1)) * Math.cos(getRad(latitude2)) * Math.sin(dLong / 2) * Math.sin(dLong / 2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    return (RADIUS_EARTH * c) * 1000;
    }

    private Double getRad(Double x) {
    return x * Math.PI / 180;
    }

How do I programmatically click a link with javascript?

For me, I managed to make it work that way. I deployed the automatic click in 5000 milliseconds and then closed the loop after 1000 milliseconds. Then there was only 1 automatic click.

<script> var myVar = setInterval(function ({document.getElementById("test").click();}, 500)); setInterval(function () {clearInterval(myVar)}, 1000));</script>

How to make borders collapse (on a div)?

here is a demo

first you need to correct your syntax error its

display: table-cell;

not diaplay: table-cell;

   .container {
    display: table;
    border-collapse:collapse
}
.column {
    display:table-row;
}
.cell {
    display: table-cell;
    border: 1px solid red;
    width: 120px;
    height: 20px;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
}

Adding data attribute to DOM

in Jquery "data" doesn't refresh by default :

alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').data("myval","20"); //setter
alert($('#outer').html());

You'd use "attr" instead for live update:

alert($('#outer').html());
var a = $('#mydiv').data('myval'); //getter
$('#mydiv').attr("data-myval","20"); //setter
alert($('#outer').html());

sorting dictionary python 3

Maybe not that good but I've figured this:

def order_dic(dic):
    ordered_dic={}
    key_ls=sorted(dic.keys())
    for key in key_ls:
        ordered_dic[key]=dic[key]
    return ordered_dic

Where does the slf4j log file get saved?

It does not write to a file by default. You would need to configure something like the RollingFileAppender and have the root logger write to it (possibly in addition to the default ConsoleAppender).

Use Expect in a Bash script to provide a password to an SSH command

Also make sure to use

send -- "$PWD\r"

instead, as passwords starting with a dash (-) will fail otherwise.

The above won't interpret a string starting with a dash as an option to the send command.

Convert timestamp in milliseconds to string formatted time in Java

    long hours = TimeUnit.MILLISECONDS.toHours(timeInMilliseconds);
    long minutes = TimeUnit.MILLISECONDS.toMinutes(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours));
    long seconds = TimeUnit.MILLISECONDS
            .toSeconds(timeInMilliseconds - TimeUnit.HOURS.toMillis(hours) - TimeUnit.MINUTES.toMillis(minutes));
    long milliseconds = timeInMilliseconds - TimeUnit.HOURS.toMillis(hours)
            - TimeUnit.MINUTES.toMillis(minutes) - TimeUnit.SECONDS.toMillis(seconds);
    return String.format("%02d:%02d:%02d:%d", hours, minutes, seconds, milliseconds);

Global variable Python classes

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,  # 1
print shape.lolwut,  # 1

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

GridView sorting: SortDirection always Ascending

It can be done without the use of View State or Session. Current order can be determined based on value in first and last row in the column we sort by:

        protected void gvItems_Sorting(object sender, GridViewSortEventArgs e)
    {
        GridView grid = sender as GridView; // get reference to grid
        SortDirection currentSortDirection = SortDirection.Ascending; // default order

        // get column index by SortExpression
        int columnIndex = grid.Columns.IndexOf(grid.Columns.OfType<DataControlField>()
                                      .First(x => x.SortExpression == e.SortExpression));

        // sort only if grid has more than 1 row
        if (grid.Rows.Count > 1)
        {
            // get cells
            TableCell firstCell = grid.Rows[0].Cells[columnIndex];
            TableCell lastCell = grid.Rows[grid.Rows.Count - 1].Cells[columnIndex];

            // if field type of the cell is 'TemplateField' Text property is always empty.
            // Below assumes that value is binded to Label control in 'TemplateField'.
            string firstCellValue = firstCell.Controls.Count == 0 ? firstCell.Text : ((Label)firstCell.Controls[1]).Text;
            string lastCellValue = lastCell.Controls.Count == 0 ? lastCell.Text : ((Label)lastCell.Controls[1]).Text;

            DateTime tmpDate;
            decimal tmpDecimal;

            // try to determinate cell type to ensure correct ordering
            // by date or number
            if (DateTime.TryParse(firstCellValue, out tmpDate)) // sort as DateTime
            {
                currentSortDirection = 
                    DateTime.Compare(Convert.ToDateTime(firstCellValue), 
                                     Convert.ToDateTime(lastCellValue)) < 0 ? 
                                            SortDirection.Ascending : SortDirection.Descending;
            }
            else if (Decimal.TryParse(firstCellValue, out tmpDecimal)) // sort as any numeric type
            {
                currentSortDirection = Decimal.Compare(Convert.ToDecimal(firstCellValue), 
                                                       Convert.ToDecimal(lastCellValue)) < 0 ? 
                                                       SortDirection.Ascending : SortDirection.Descending;
            }
            else // sort as string
            {
                currentSortDirection = string.CompareOrdinal(firstCellValue, lastCellValue) < 0 ? 
                                                             SortDirection.Ascending : SortDirection.Descending;
            }
        }

        // then bind GridView using correct sorting direction (in this example I use Linq)
        if (currentSortDirection == SortDirection.Descending)
        {
            grid.DataSource = myItems.OrderBy(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));
        }
        else
        {
            grid.DataSource = myItems.OrderByDescending(x => x.GetType().GetProperty(e.SortExpression).GetValue(x, null));
        }

        grid.DataBind();
    }

Laravel is there a way to add values to a request array

The best one I have used and researched on it is $request->merge([]) (Check My Piece of Code):

public function index(Request $request) {
    not_permissions_redirect(have_premission(2));
    $filters = (!empty($request->all())) ? true : false;
    $request->merge(['type' => 'admin']);
    $users = $this->service->getAllUsers($request->all());
    $roles = $this->roles->getAllAdminRoles();
    return view('users.list', compact(['users', 'roles', 'filters']));
}

Check line # 3 inside the index function.

"if not exist" command in batch file

if not exist "%USERPROFILE%\.qgis-custom\" (
    mkdir "%USERPROFILE%\.qgis-custom" 2>nul
    if not errorlevel 1 (
        xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
    )
)

You have it almost done. The logic is correct, just some little changes.

This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).

If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.

If everyting is ok, files are copied.

All paths are quoted to avoid problems with spaces.

It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files

mkdir "%USERPROFILE%\.qgis-custom" 2>nul 
if not errorlevel 1 (
    xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)

In both code samples, files are not copied if the folder is not being created during the script execution.

EDITED - As dbenham comments, the same code can be written as a single line

md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e

The code after the && will only be executed if the previous command does not set errorlevel. If mkdir fails, xcopy is not executed.

Date difference in minutes in Python

from datetime import datetime

fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2010-01-01 17:31:22', fmt)
d2 = datetime.strptime('2010-01-03 17:31:22', fmt)

print (d2-d1).days * 24 * 60

Determine the number of lines within a text file

try {
    string path = args[0];
    FileStream fh = new FileStream(path, FileMode.Open, FileAccess.Read);
    int i;
    string s = "";
    while ((i = fh.ReadByte()) != -1)
        s = s + (char)i;

    //its for reading number of paragraphs
    int count = 0;
    for (int j = 0; j < s.Length - 1; j++) {
            if (s.Substring(j, 1) == "\n")
                count++;
    }

    Console.WriteLine("The total searches were :" + count);

    fh.Close();

} catch(Exception ex) {
    Console.WriteLine(ex.Message);
}         

Good Patterns For VBA Error Handling

The code below shows an alternative that ensures there is only one exit point for the sub/function.

sub something()
    on error goto errHandler

    ' start of code
    ....
    ....
    'end of code

    ' 1. not needed but signals to any other developer that looks at this
    ' code that you are skipping over the error handler...
    ' see point 1...
    err.clear

errHandler:
    if err.number <> 0 then
        ' error handling code
    end if
end sub

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

there may be more than 1 IBAction for a button in your view controller try finding out those and removing all previous item for that button in your controller and create new button .It will solve your problem.

SVN "Already Locked Error"

I had the same problem: I can't commit a lot of files at once.


The commit works by:

  1. Running a "clean up" from Tortoise SVN

  2. Commit each file separate. Create new root folder and commit each file or folder.


** If the error returns you should repeat action no.1-2 **

C# using streams

There is only one basic type of Stream. However in various circumstances some members will throw an exception when called because in that context the operation was not available.

For example a MemoryStream is simply a way to moves bytes into and out of a chunk of memory. Hence you can call Read and Write on it.

On the other hand a FileStream allows you to read or write (or both) from/to a file. Whether you can actually Read or Write depends on how the file was opened. You can't Write to a file if you only opened it for Read access.

move div with CSS transition

Something like this?

DEMO

And the code I used:

.box{
    position: relative;
    overflow: hidden;
}

.box:hover .hidden{

    left: 0px;
}

.box .hidden {    
    background: yellow;
    height: 300px;    
    position: absolute; 
    top: 0;
    left: -500px;    
    width: 500px;
    opacity: 1;    
    -webkit-transition: all 0.7s ease-out;
       -moz-transition: all 0.7s ease-out;
        -ms-transition: all 0.7s ease-out;
         -o-transition: all 0.7s ease-out;
            transition: all 0.7s ease-out;
}

I may also add that it's possible to move an elment using transform: translate(); , which in this case could work something like this - DEMO nr2

How to give spacing between buttons using bootstrap

You can achieved by use bootstrap Spacing. Bootstrap Spacing includes a wide range of shorthand responsive margin and padding. In below example mr-1 set the margin or padding to $spacer * .25.

Example:

<button class="btn btn-outline-primary mr-1" href="#">Sign up</button>
<button class="btn btn-outline-primary" href="#">Login</button>

You can read more at Bootstrap Spacing.

PHP - Getting the index of a element from a array

I recently had to figure this out for myself and ended up on a solution inspired by @Zahymaka 's answer, but solving the 2x looping of the array.

What you can do is create an array with all your keys, in the order they exist, and then loop through that.

        $keys=array_keys($items);
        foreach($keys as $index=>$key){
                    echo "position: $index".PHP_EOL."item: ".PHP_EOL;
                    var_dump($items[$key]);
                    ...
        }

PS: I know this is very late to the party, but since I found myself searching for this, maybe this could be helpful to someone else

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

adding the following lines to my /etc/environment file worked

LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

I have encountered this error while updating records from table which has trigger enabled. For example - I have trigger 'Trigger1' on table 'Table1'. When I tried to update the 'Table1' using the update query - it throws the same error. THis is because if you are updating more than 1 record in your query, then 'Trigger1' will throw this error as it doesn't support updating multiple entries if it is enabled on same table. I tried disabling trigger before update and then performed update operation and it was completed without any error.

DISABLE TRIGGER Trigger1 ON Table1;
Update query --------
Enable TRIGGER Trigger1 ON Table1;

AngularJS resource promise

You could also do:

Regions.query({}, function(response) {
    $scope.regions = response;
    // Do stuff that depends on $scope.regions here
});

How to restore the permissions of files and directories within git if they have been modified?

Git doesn't store file permissions other than executable scripts. Consider using something like git-cache-meta to save file ownership and permissions.

Git can only store two types of modes: 755 (executable) and 644 (not executable). If your file was 444 git would store it has 644.

Jquery Ajax Posting json to webservice

You mentioned using json2.js to stringify your data, but the POSTed data appears to be URLEncoded JSON You may have already seen it, but this post about the invalid JSON primitive covers why the JSON is being URLEncoded.

I'd advise against passing a raw, manually-serialized JSON string into your method. ASP.NET is going to automatically JSON deserialize the request's POST data, so if you're manually serializing and sending a JSON string to ASP.NET, you'll actually end up having to JSON serialize your JSON serialized string.

I'd suggest something more along these lines:

var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },
               { "position": "235.1944023323615", "markerPosition": "19" },
               { "position": "42.5978231292517", "markerPosition": "-3" }];

$.ajax({
    type: "POST",
    url: "/webservices/PodcastService.asmx/CreateMarkers",
    // The key needs to match your method's input parameter (case-sensitive).
    data: JSON.stringify({ Markers: markers }),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(data){alert(data);},
    error: function(errMsg) {
        alert(errMsg);
    }
});

The key to avoiding the invalid JSON primitive issue is to pass jQuery a JSON string for the data parameter, not a JavaScript object, so that jQuery doesn't attempt to URLEncode your data.

On the server-side, match your method's input parameters to the shape of the data you're passing in:

public class Marker
{
  public decimal position { get; set; }
  public int markerPosition { get; set; }
}

[WebMethod]
public string CreateMarkers(List<Marker> Markers)
{
  return "Received " + Markers.Count + " markers.";
}

You can also accept an array, like Marker[] Markers, if you prefer. The deserializer that ASMX ScriptServices uses (JavaScriptSerializer) is pretty flexible, and will do what it can to convert your input data into the server-side type you specify.

How can I check if a JSON is empty in NodeJS?

Object.keys(myObj).length === 0;

As there is need to just check if Object is empty it will be better to directly call a native method Object.keys(myObj).length which returns the array of keys by internally iterating with for..in loop.As Object.hasOwnProperty returns a boolean result based on the property present in an object which itself iterates with for..in loop and will have time complexity O(N2).

On the other hand calling a UDF which itself has above two implementations or other will work fine for small object but will block the code which will have severe impact on overall perormance if Object size is large unless nothing else is waiting in the event loop.

Length of a JavaScript object

Object.keys does not return the right result in case of object inheritance. To properly count object properties, including inherited ones, use for-in. For example, by the following function (related question):

var objLength = (o,i=0) => { for(p in o) i++; return i }

_x000D_
_x000D_
var myObject = new Object();
myObject["firstname"] = "Gareth";
myObject["lastname"] = "Simpson";
myObject["age"] = 21;

var child = Object.create(myObject);
child["sex"] = "male";

var objLength = (o,i=0) => { for(p in o) i++; return i }

console.log("Object.keys(myObject):", Object.keys(myObject).length, "(OK)");
console.log("Object.keys(child)   :", Object.keys(child).length, "(wrong)");
console.log("objLength(child)     :", objLength(child), "(OK)");
_x000D_
_x000D_
_x000D_

Rails Active Record find(:all, :order => ) issue

I just ran into the same problem, but I manage to have my query working in SQLite like this:

@shows = Show.order("datetime(date) ASC, attending DESC")

I hope this might help someone save some time

JSON Parse File Path

Loading local JSON file

Use something like this

$.getJSON("../../data/file.json", function(json) {
    console.log(json); // this will show the info in firebug console 
    alert(json);
});

Delete all files of specific type (extension) recursively down a directory using a batch file

You can use wildcards with the del command, and /S to do it recursively.

del /S *.jpg

Addendum

@BmyGuest asked why a downvoted answer (del /s c:\*.blaawbg) was any different than my answer.

There's a huge difference between running del /S *.jpg and del /S C:\*.jpg. The first command is executed from the current location, whereas the second is executed on the whole drive.

In the scenario where you delete jpg files using the second command, some applications might stop working, and you'll end up losing all your family pictures. This is utterly annoying, but your computer will still be able to run.

However, if you are working on some project, and want to delete all your dll files in myProject\dll, and run the following batch file:

@echo off

REM This short script will only remove dlls from my project... or will it?

cd \myProject\dll
del /S /Q C:\*.dll

Then you end up removing all dll files form your C:\ drive. All of your applications stop working, your computer becomes useless, and at the next reboot you are teleported in the fourth dimension where you will be stuck for eternity.

The lesson here is not to run such command directly at the root of a drive (or in any other location that might be dangerous, such as %windir%) if you can avoid it. Always run them as locally as possible.

Addendum 2

The wildcard method will try to match all file names, in their 8.3 format, and their "long name" format. For example, *.dll will match project.dll and project.dllold, which can be surprising. See this answer on SU for more detailed information.

Jquery, checking if a value exists in array or not

http://api.jquery.com/jQuery.inArray/

if ($.inArray('example', myArray) != -1)
{
  // found it
}

git: diff between file in local repo and origin

I tried a couple of solution but I thing easy way like this (you are in the local folder):

#!/bin/bash
git fetch

var_local=`cat .git/refs/heads/master`
var_remote=`git log origin/master -1 | head -n1 | cut -d" " -f2`

if [ "$var_remote" = "$var_local" ]; then
    echo "Strings are equal." #1
else
    echo "Strings are not equal." #0 if you want
fi

Then you did compare local git and remote git last commit number....

How can I call a method in Objective-C?

Use this:

[self score]; you don't need @sel for calling directly

Importing class/java files in Eclipse

First, you don't need the .class files if they are compiled from your .java classes.

To import your files, you need to create an empty Java project. They you either import them one by one (New -> File -> Advanced -> Link file) or directly copy them into their corresponding folder/package and refresh the project.

ruby 1.9: invalid byte sequence in UTF-8

Before you use scan, make sure that the requested page's Content-Type header is text/html, since there can be links to things like images which are not encoded in UTF-8. The page could also be non-html if you picked up a href in something like a <link> element. How to check this varies on what HTTP library you are using. Then, make sure the result is only ascii with String#ascii_only? (not UTF-8 because HTML is only supposed to be using ascii, entities can be used otherwise). If both of those tests pass, it is safe to use scan.

Can dplyr package be used for conditional mutating?

Use ifelse

df %>%
  mutate(g = ifelse(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               ifelse(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA)))

Added - if_else: Note that in dplyr 0.5 there is an if_else function defined so an alternative would be to replace ifelse with if_else; however, note that since if_else is stricter than ifelse (both legs of the condition must have the same type) so the NA in that case would have to be replaced with NA_real_ .

df %>%
  mutate(g = if_else(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4), 2,
               if_else(a == 0 | a == 1 | a == 4 | a == 3 |  c == 4, 3, NA_real_)))

Added - case_when Since this question was posted dplyr has added case_when so another alternative would be:

df %>% mutate(g = case_when(a == 2 | a == 5 | a == 7 | (a == 1 & b == 4) ~ 2,
                            a == 0 | a == 1 | a == 4 | a == 3 |  c == 4 ~ 3,
                            TRUE ~ NA_real_))

Added - arithmetic/na_if If the values are numeric and the conditions (except for the default value of NA at the end) are mutually exclusive, as is the case in the question, then we can use an arithmetic expression such that each term is multiplied by the desired result using na_if at the end to replace 0 with NA.

df %>%
  mutate(g = 2 * (a == 2 | a == 5 | a == 7 | (a == 1 & b == 4)) +
             3 * (a == 0 | a == 1 | a == 4 | a == 3 |  c == 4),
         g = na_if(g, 0))

How do I center content in a div using CSS?

By using transform: works like a charm!

<div class="parent">
    <span>center content using transform</span>
    </div>

    //CSS
    .parent {
        position: relative;
        height: 200px;
        border: 1px solid;
    }
    .parent span {
        position: absolute;
        top: 50%;
        left: 50%;
        -webkit-transform: translate(-50%, -50%);
        transform: translate(-50%, -50%);
    }

How to replace all special character into a string using C#

You can use a regular expresion to for example replace all non-alphanumeric characters with commas:

s = Regex.Replace(s, "[^0-9A-Za-z]+", ",");

Note: The + after the set will make it replace each group of non-alphanumeric characters with a comma. If you want to replace each character with a comma, just remove the +.

Sorting a vector in descending order

Actually, the first one is a bad idea. Use either the second one, or this:

struct greater
{
    template<class T>
    bool operator()(T const &a, T const &b) const { return a > b; }
};

std::sort(numbers.begin(), numbers.end(), greater());

That way your code won't silently break when someone decides numbers should hold long or long long instead of int.

Preventing console window from closing on Visual Studio C/C++ Console application

Right click on your project

Properties > Configuration Properties > Linker > System

Select Console (/SUBSYSTEM:CONSOLE) in SubSystem option or you can just type Console in the text field!

Now try it...it should work

Disable color change of anchor tag when visited

For :hover to override :visited, and to make sure :visited is the same as the initial color, :hover must come after :visited.

So if you want to disable the color change, a:visited must come before a:hover. Like this:

a { color: gray; }
a:visited { color: orange; }
a:hover { color: red; }

To disable :visited change you would style it with non-pseudo class:

a, a:visited { color: gray; }
a:hover { color: red; }

What is the @Html.DisplayFor syntax for?

After looking for an answer for myself for some time, i could find something. in general if we are using it for just one property it appears same even if we do a "View Source" of generated HTML Below is generated HTML for example, when i want to display only Name property for my class

    <td>
    myClassNameProperty
    </td>
   <td>
    myClassNameProperty, This is direct from Item
    </td>

This is the generated HTML from below code

<td>
@Html.DisplayFor(modelItem=>item.Genre.Name)            
</td>

<td>
@item.Genre.Name, This is direct from Item
</td>

At the same time now if i want to display all properties in one statement for my class "Genre" in this case, i can use @Html.DisplayFor() to save on my typing, for least

i can write @Html.DisplayFor(modelItem=>item.Genre) in place of writing a separate statement for each property of Genre as below

@item.Genre.Name
@item.Genre.Id
@item.Genre.Description

and so on depending on number of properties.

How to specify the private SSH-key to use when executing shell command on Git?

The problem is when you have different remote repositories on the same host (say github.com), and you want to interact with them using different ssh keys (i.e. different GitHub accounts).

In order to do that:

  1. First you should declare your different keys in ~/.ssh/config file.

    # Key for usual repositories on github.com
    Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_rsa
    
    # Key for a particular repository on github.com
    Host XXX
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_other_rsa
    

    By doing this you associate the second key with a new friendly name "XXX" for github.com.

  2. Then you must change the remote origin of your particular repository, so that it uses the friendly name you've just defined.

    Go to your local repository folder within a command prompt, and display the current remote origin:

    >git remote -v
    origin  [email protected]:myuser/myrepo.git (fetch)
    origin  [email protected]:myuser/myrepo.git (push)
    

    Then change origin with:

    >git remote set-url origin git@XXX:myuser/myrepo.git
    >git remote -v
    origin  git@XXX:myuser/myrepo.git (fetch)
    origin  git@XXX:myuser/myrepo.git (push)
    

    Now you can push, fetch... with the right key automatically.

Set the default value in dropdownlist using jQuery

$("#dropdownList option[text='it\'s me']").attr("selected","selected"); 

Select where count of one field is greater than one

As OMG Ponies stated, the having clause is what you are after. However, if you were hoping that you would get discrete rows instead of a summary (the "having" creates a summary) - it cannot be done in a single statement. You must use two statements in that case.

Getting attribute of element in ng-click function in angularjs

Addition to the answer of Brett DeWoody: (which is updated now)

var dataValue = obj.srcElement.attributes.data.nodeValue;

Works fine in IE(9+) and Chrome, but Firefox does not know the srcElement property. I found:

var dataValue = obj.currentTarget.attributes.data.nodeValue;

Works in IE, Chrome and FF, I did not test Safari.

In nodeJs is there a way to loop through an array without using array size?

To print 'item1' , 'item2', this code would work.

var myarray = ['hello', ' hello again'];

for (var item in myarray) {
    console.log(myarray[item])
}

ASP.NET Background image

body {
    background-image: url('../images/background.jpg');
    background-repeat: no-repeat;
    background-size: cover; /* will auto resize to fill the screen */
}

SQL Server default character encoding

If you need to know the default collation for a newly created database use:

SELECT SERVERPROPERTY('Collation')

This is the server collation for the SQL Server instance that you are running.

How to get the location of the DLL currently executing?

Reflection is your friend, as has been pointed out. But you need to use the correct method;

Assembly.GetEntryAssembly()     //gives you the entrypoint assembly for the process.
Assembly.GetCallingAssembly()   // gives you the assembly from which the current method was called.
Assembly.GetExecutingAssembly() // gives you the assembly in which the currently executing code is defined
Assembly.GetAssembly( Type t )  // gives you the assembly in which the specified type is defined.

How do I do a multi-line string in node.js?

Vanilla Javascipt does not support multi-line strings. Language pre-processors are turning out to be feasable these days.

CoffeeScript, the most popular of these has this feature, but it's not minimal, it's a new language. Google's traceur compiler adds new features to the language as a superset, but I don't think multi-line strings are one of the added features.

I'm looking to make a minimal superset of javascript that supports multiline strings and a couple other features. I started this little language a while back before writing the initial compiler for coffeescript. I plan to finish it this summer.

If pre-compilers aren't an option, there is also the script tag hack where you store your multi-line data in a script tag in the html, but give it a custom type so that it doesn't get evaled. Then later using javascript, you can extract the contents of the script tag.

Also, if you put a \ at the end of any line in source code, it will cause the the newline to be ignored as if it wasn't there. If you want the newline, then you have to end the line with "\n\".

Tomcat request timeout

With Tomcat 7, you can add the StuckThreadDetectionValve which will enable you to identify threads that are "stuck". You can set-up the valve in the Context element of the applications where you want to do detecting:

<Context ...>
  ...
  <Valve 
    className="org.apache.catalina.valves.StuckThreadDetectionValve"
    threshold="60" />
  ...
</Context>

This would write a WARN entry into the tomcat log for any thread that takes longer than 60 seconds, which would enable you to identify the applications and ban them because they are faulty.

Based on the source code you may be able to write your own valve that attempts to stop the thread, however this would have knock on effects on the thread pool and there is no reliable way of stopping a thread in Java without the cooperation of that thread...

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

How to have git log show filenames like svn log -v

For full path names of changed files:

git log --name-only

For full path names and status of changed files:

git log --name-status

For abbreviated pathnames and a diffstat of changed files:

git log --stat

There's a lot more options, check out the docs.

Select Specific Columns from Spark DataFrame

There are multiple options (especially in Scala) to select a subset of columns of that Dataframe. The following lines will all select the two columns colA and colB:

import spark.implicits._
import org.apache.spark.sql.functions.{col, column, expr}

inputDf.select(col("colA"), col("colB"))
inputDf.select(inputDf.col("colA"), inputDf.col("colB"))
inputDf.select(column("colA"), column("colB"))
inputDf.select(expr("colA"), expr("colB"))

// only available in Scala
inputDf.select($"colA", $"colB")
inputDf.select('colA, 'colB) // makes use of Scala's Symbol

// selecting columns based on a given iterable of Strings
val selectedColumns: Seq[Column] = Seq("colA", "colB").map(c => col(c))
inputDf.select(selectedColumns: _*)

// select the first or last 2 columns
inputDf.selectExpr(inputDf.columns.take(2): _*)
inputDf.selectExpr(inputDf.columns.takeRight(2): _*)

The usage of $ is possible as Scala provides an implicit class that converts a String into a Column using the method $:

implicit class StringToColumn(val sc : scala.StringContext) extends scala.AnyRef {
  def $(args : scala.Any*) : org.apache.spark.sql.ColumnName = { /* compiled code */ }
}

Typically, when you want to derive one DataFrame to multiple DataFrames it might improve your performance if you persist the original DataFrame before creating the others. At the end you can unpersist the original DataFrame.

Keep in mind that Columns are not resolved at compile time but only when it is compared to the column names of your catalog which happens during analyser phase of the query execution. In case you need stronger type safety you could create a Dataset.

For completeness, here is the csv to try out above code:

// csv file:
// colA,colB,colC
// 1,"foo","bar"

val inputDf = spark.read.format("csv").option("header", "true").load(csvFilePath)

// resulting DataFrame schema
root
 |-- colA: string (nullable = true)
 |-- colB: string (nullable = true)
 |-- colC: string (nullable = true)

How does Python manage int and long?

From python 3.x, the unified integer libries are even more smarter than older versions. On my (i7 Ubuntu) box I got the following,

>>> type(math.factorial(30))
<class 'int'>

For implementation details refer Include/longintrepr.h, Objects/longobject.c and Modules/mathmodule.c files. The last file is a dynamic module (compiled to an so file). The code is well commented to follow.

MySQL vs MongoDB 1000 reads

Do you have concurrency, i.e simultaneous users ? If you just run 1000 times the query straight, with just one thread, there will be almost no difference. Too easy for these engines :)

BUT I strongly suggest that you build a true load testing session, which means using an injector such as JMeter with 10, 20 or 50 users AT THE SAME TIME so you can really see a difference (try to embed this code inside a web page JMeter could query).

I just did it today on a single server (and a simple collection / table) and the results are quite interesting and surprising (MongoDb was really faster on writes & reads, compared to MyISAM engine and InnoDb engine).

This really should be part of your test : concurrency & MySQL engine. Then, data/schema design & application needs are of course huge requirements, beyond response times. Let me know when you get results, I'm also in need of inputs about this!

Can I escape a double quote in a verbatim string literal?

This should help clear up any questions you may have: C# literals

Here is a table from the linked content:

Regular literal Verbatim literal Resulting string
"Hello" @"Hello" Hello
"Backslash: \\" @"Backslash: \" Backslash: \
"Quote: \"" @"Quote: """ Quote: "
"CRLF:\r\nPost CRLF" @"CRLF:
Post CRLF"
CRLF:
Post CRLF

How to make a vertical SeekBar in Android?

Note, it appears to me that if you change the width the thumb width does not change correctly. I didn't take the time to fix it right, i just fixed it for my case. Here is what i did. Couldn't figure out how to contact the original creator.

public void setThumb(Drawable thumb) {
    if (thumb != null) {
        thumb.setCallback(this);

        // Assuming the thumb drawable is symmetric, set the thumb offset
        // such that the thumb will hang halfway off either edge of the
        // progress bar.
        //This was orginally divided by 2, seems you have to adjust here when you adjust width.
        mThumbOffset = (int)thumb.getIntrinsicHeight();
    }

Excel 2010 VBA Referencing Specific Cells in other worksheets

Sub Results2()

    Dim rCell As Range
    Dim shSource As Worksheet
    Dim shDest As Worksheet
    Dim lCnt As Long

    Set shSource = ThisWorkbook.Sheets("Sheet1")
    Set shDest = ThisWorkbook.Sheets("Sheet2")

    For Each rCell In shSource.Range("A1", shSource.Cells(shSource.Rows.Count, 1).End(xlUp)).Cells
        lCnt = lCnt + 1
        shDest.Range("A4").Offset(0, lCnt * 4).Formula = "=" & rCell.Address(False, False, , True) & "+" & rCell.Offset(0, 1).Address(False, False, , True)
    Next rCell

End Sub

This loops through column A of sheet1 and creates a formula in sheet2 for every cell. To find the last cell in Sheet1, I start at the bottom (shSource.Rows.Count) and .End(xlUp) to get the last cell in the column that's not blank.

To create the elements of the formula, I use the Address property of the cell on Sheet. I'm using three of the arguments to Address. The first two are RowAbsolute and ColumnAbsolute, both set to false. I don't care about the third argument, but I set the fourth argument (External) to True so that it includes the sheet name.

I prefer to go from Source to Destination rather than the other way. But that's just a personal preference. If you want to work from the destination,

Sub Results3()

    Dim i As Long, lCnt As Long
    Dim sh As Worksheet

    lCnt = Application.WorksheetFunction.CountA(ThisWorkbook.Sheets("Sheet1").Columns(1))
    Set sh = ThisWorkbook.Sheets("Sheet2")

    Const sSOURCE As String = "Sheet1!"

    For i = 1 To lCnt
        sh.Range("A1").Offset(0, 4 * (i - 1)).Formula = "=" & sSOURCE & "A" & i & " + " & sSOURCE & "B" & i
    Next i

End Sub

JavaFX and OpenJDK

Also answering this question:

Where can I get pre-built JavaFX libraries for OpenJDK (Windows)

On Linux its not really a problem, but on Windows its not that easy, especially if you want to distribute the JRE.

You can actually use OpenJFX with OpenJDK 8 on windows, you just have to assemble it yourself:

Download the OpenJDK from here: https://github.com/AdoptOpenJDK/openjdk8-releases/releases/tag/jdk8u172-b11

Download OpenJFX from here: https://github.com/SkyLandTW/OpenJFX-binary-windows/releases/tag/v8u172-b11

copy all the files from the OpenFX zip on top of the JDK, voila, you have an OpenJDK with JavaFX.

Update:

Fortunately from Azul there is now a OpenJDK+OpenJFX build which can be downloaded at their community page: https://www.azul.com/downloads/zulu-community/?&version=java-8-lts&os=windows&package=jdk-fx

How to read a value from the Windows registry

const CString REG_SW_GROUP_I_WANT = _T("SOFTWARE\\My Corporation\\My Package\\Group I want");
const CString REG_KEY_I_WANT= _T("Key Name");

CRegKey regKey;
DWORD   dwValue = 0;

if(ERROR_SUCCESS != regKey.Open(HKEY_LOCAL_MACHINE, REG_SW_GROUP_I_WANT))
{
  m_pobLogger->LogError(_T("CRegKey::Open failed in Method"));
  regKey.Close();
  goto Function_Exit;
}
if( ERROR_SUCCESS != regKey.QueryValue( dwValue, REG_KEY_I_WANT))
{
  m_pobLogger->LogError(_T("CRegKey::QueryValue Failed in Method"));
  regKey.Close();
  goto Function_Exit;
}

// dwValue has the stuff now - use for further processing

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

I think this will work even though this was forever ago.

SELECT employee_number, Row_Number()  
   OVER (PARTITION BY course_code ORDER BY course_completion_date DESC ) as rownum
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
   AND rownum = 1

If you want to get the last Id if the date is the same then you can use this assuming your primary key is Id.

SELECT employee_number, Row_Number()  
   OVER (PARTITION BY course_code ORDER BY course_completion_date DESC, Id Desc) as rownum    FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
   AND rownum = 1

PHP, pass array through POST

http://php.net/manual/en/reserved.variables.post.php

The first comment answers this.

<form ....>
<input name="person[0][first_name]" value="john" />
<input name="person[0][last_name]" value="smith" />
...
<input name="person[1][first_name]" value="jane" />
<input name="person[1][last_name]" value="jones" />
</form>

<?php
var_dump($_POST['person']);

array (
0 => array('first_name'=>'john','last_name'=>'smith'),
1 => array('first_name'=>'jane','last_name'=>'jones'),
)
?>

The name tag can work as an array.

Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

Inside the simple_html_dom.php change the value of the $offset variable from -1 to 0. this error usually happens when you migrate to PHP 7.

HtmlDomParser::file_get_html uses a default offset of -1, passing in 0 should fix your problem.

How do format a phone number as a String in Java?

Using StringBuilder for performance.

long number = 12345678L;

System.out.println(getPhoneFormat(String.valueOf(number)));

public static String getPhoneFormat(String number)
{
    if (number == null || number.isEmpty() || number.length() < 6 || number.length() > 15)
    {
        return number;
    }

    return new StringBuilder("(").append(number.substring(0, 3))
            .append(") ").append(number.substring(3, 6))
            .append("-").append(number.substring(6))
            .toString();

}

How to do multiline shell script in Ansible

https://support.ansible.com/hc/en-us/articles/201957837-How-do-I-split-an-action-into-a-multi-line-format-

mentions YAML line continuations.

As an example (tried with ansible 2.0.0.2):

---
- hosts: all
  tasks:
    - name: multiline shell command
      shell: >
        ls --color
        /home
      register: stdout

    - name: debug output
      debug: msg={{ stdout }}

The shell command is collapsed into a single line, as in ls --color /home

How can I center <ul> <li> into div

Another option is:

HTML

<nav>
  <ul class = "main-nav"> 
   <li> Productos </li>
   <li> Catalogo </li>
   <li> Contact </li>  
   <li> Us </li>
  </ul>
</nav>    

CSS:

nav {
  text-align: center;
}

nav .main-nav li {
  float: left;
  width: 20%;
  margin-right: 5%;
  font-size: 36px;
  text-align: center;
}

Laravel Eloquent ORM Transactions

If any exception occurs, the transaction will rollback automatically.

Laravel Basic transaction format

    try{
    DB::beginTransaction();

    /* 
    * SQL operation one 
    * SQL operation two
    ..................     
    ..................     
    * SQL operation n */


    DB::commit();
   /* Transaction successful. */
}catch(\Exception $e){       

    DB::rollback();
    /* Transaction failed. */
}

Remove characters from a String in Java

Strings in java are immutable. That means you need to create a new string or overwrite your old string to achieve the desired affect:

id = id.replace(".xml", "");

How to implement a Boolean search with multiple columns in pandas

You need to enclose multiple conditions in braces due to operator precedence and use the bitwise and (&) and or (|) operators:

foo = df[(df['column1']==value) | (df['columns2'] == 'b') | (df['column3'] == 'c')]

If you use and or or, then pandas is likely to moan that the comparison is ambiguous. In that case, it is unclear whether we are comparing every value in a series in the condition, and what does it mean if only 1 or all but 1 match the condition. That is why you should use the bitwise operators or the numpy np.all or np.any to specify the matching criteria.

There is also the query method: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.query.html

but there are some limitations mainly to do with issues where there could be ambiguity between column names and index values.

Div width 100% minus fixed amount of pixels

The usual way to do it is as outlined by Guffa, nested elements. It's a bit sad having to add extra markup to get the hooks you need for this, but in practice a wrapper div here or there isn't going to hurt anyone.

If you must do it without extra elements (eg. when you don't have control of the page markup), you can use box-sizing, which has pretty decent but not complete or simple browser support. Likely more fun than having to rely on scripting though.

XPath: difference between dot and text()

There is a difference between . and text(), but this difference might not surface because of your input document.

If your input document looked like (the simplest document one can imagine given your XPath expressions)

Example 1

<html>
  <a>Ask Question</a>
</html>

Then //a[text()="Ask Question"] and //a[.="Ask Question"] indeed return exactly the same result. But consider a different input document that looks like

Example 2

<html>
  <a>Ask Question<other/>
  </a>
</html>

where the a element also has a child element other that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"] still returns the a element, while //a[.="Ask Question"] does not return anything!


This is because the meaning of the two predicates (everything between [ and ]) is different. [text()="Ask Question"] actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"] means: return true if the string value of an element is identical to "Ask Question".

In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other element is between "Ask Question" and a newline character that also counts as text content.

To make an even clearer example, consider as an input document:

Example 3

<a>Ask Question<other/>more text</a>

Here, the a element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a. You can test this by running //a/text() on this document, which will return (individual results separated by ----):

Ask Question
-----------------------
more text

So, in such a scenario, text() returns a set of individual nodes, while . in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text'] which will successfully return the a element.


Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()) is given a sequence of nodes, it will only process the first node and silently ignore the rest.

List Directories and get the name of the Directory

Listing the entries in the current directory (for directories in os.listdir(os.getcwd()):) and then interpreting those entries as subdirectories of an entirely different directory (dir = os.path.join('/home/user/workspace', directories)) is one thing that looks fishy.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

Add this to you PHP file or main controller

header("Access-Control-Allow-Origin: http://localhost:9000");

What's the best practice using a settings file in Python?

Yaml and Json are the simplest and most commonly used file formats to store settings/config. PyYaml can be used to parse yaml. Json is already part of python from 2.5. Yaml is a superset of Json. Json will solve most uses cases except multi line strings where escaping is required. Yaml takes care of these cases too.

>>> import json
>>> config = {'handler' : 'adminhandler.py', 'timeoutsec' : 5 }
>>> json.dump(config, open('/tmp/config.json', 'w'))
>>> json.load(open('/tmp/config.json'))   
{u'handler': u'adminhandler.py', u'timeoutsec': 5}

Display date/time in user's locale format and time offset

Seems the most foolproof way to start with a UTC date is to create a new Date object and use the setUTC… methods to set it to the date/time you want.

Then the various toLocale…String methods will provide localized output.

Example:

_x000D_
_x000D_
// This would come from the server._x000D_
// Also, this whole block could probably be made into an mktime function._x000D_
// All very bare here for quick grasping._x000D_
d = new Date();_x000D_
d.setUTCFullYear(2004);_x000D_
d.setUTCMonth(1);_x000D_
d.setUTCDate(29);_x000D_
d.setUTCHours(2);_x000D_
d.setUTCMinutes(45);_x000D_
d.setUTCSeconds(26);_x000D_
_x000D_
console.log(d);                        // -> Sat Feb 28 2004 23:45:26 GMT-0300 (BRT)_x000D_
console.log(d.toLocaleString());       // -> Sat Feb 28 23:45:26 2004_x000D_
console.log(d.toLocaleDateString());   // -> 02/28/2004_x000D_
console.log(d.toLocaleTimeString());   // -> 23:45:26
_x000D_
_x000D_
_x000D_

Some references:

Problem with SMTP authentication in PHP using PHPMailer, with Pear Mail works

This isn't on the code parter it's on the server side Contact your Server Manager or fix it from server if you own it If you use CPANEL/WHM GO TO WHM/SMTP RESTRICTIONS AND DISABLE IT

How to use Elasticsearch with MongoDB?

Since mongo-connector now appears dead, my company decided to build a tool for using Mongo change streams to output to Elasticsearch.

Our initial results look promising. You can check it out at https://github.com/electionsexperts/mongo-stream. We're still early in development, and would welcome suggestions or contributions.

ES6 Map in Typescript

Not sure if this is official but this worked for me in typescript 2.7.1:

class Item {
   configs: Map<string, string>;
   constructor () {
     this.configs = new Map();
   }
}

In simple Map<keyType, valueType>

Finding what branch a Git commit came from

While Dav is correct that the information isn't directly stored, that doesn't mean you can't ever find out. Here are a few things you can do.

Find branches the commit is on

git branch -a --contains <commit>

This will tell you all branches which have the given commit in their history. Obviously this is less useful if the commit's already been merged.

Search the reflogs

If you are working in the repository in which the commit was made, you can search the reflogs for the line for that commit. Reflogs older than 90 days are pruned by git-gc, so if the commit's too old, you won't find it. That said, you can do this:

git reflog show --all | grep a871742

to find commit a871742. Note that you MUST use the abbreviatd 7 first digits of the commit. The output should be something like this:

a871742 refs/heads/completion@{0}: commit (amend): mpc-completion: total rewrite

indicating that the commit was made on the branch "completion". The default output shows abbreviated commit hashes, so be sure not to search for the full hash or you won't find anything.

git reflog show is actually just an alias for git log -g --abbrev-commit --pretty=oneline, so if you want to fiddle with the output format to make different things available to grep for, that's your starting point!

If you're not working in the repository where the commit was made, the best you can do in this case is examine the reflogs and find when the commit was first introduced to your repository; with any luck, you fetched the branch it was committed to. This is a bit more complex, because you can't walk both the commit tree and reflogs simultaneously. You'd want to parse the reflog output, examining each hash to see if it contains the desired commit or not.

Find a subsequent merge commit

This is workflow-dependent, but with good workflows, commits are made on development branches which are then merged in. You could do this:

git log --merges <commit>..

to see merge commits that have the given commit as an ancestor. (If the commit was only merged once, the first one should be the merge you're after; otherwise you'll have to examine a few, I suppose.) The merge commit message should contain the branch name that was merged.

If you want to be able to count on doing this, you may want to use the --no-ff option to git merge to force merge commit creation even in the fast-forward case. (Don't get too eager, though. That could become obfuscating if overused.) VonC's answer to a related question helpfully elaborates on this topic.

d3.select("#element") not working when code above the html element

Not enough reputation to comment yet so I'll just put this here:

To expand on Micah's answer - the browser runs your code top to bottom, so if you write:

<div id="chart"></div>
<script>var svg = d3.select("#chart").append("svg:svg");</script>

The browser will create a div with id "chart", and then run your script, which will try to find that div, and, hurray, success.

Otherwise if you write:

<script>var svg = d3.select("#chart").append("svg:svg");</script>
<div id="chart"></div>

The browser runs your script, and tries to find a div with id chart, but it hasn't been created yet so it fails.

THEN the browser creates a div with id "chart".

How to convert WebResponse.GetResponseStream return into a string?

You should create a StreamReader around the stream, then call ReadToEnd.

You should consider calling WebClient.DownloadString instead.

Arguments to main in C

The signature of main is:

int main(int argc, char **argv);

argc refers to the number of command line arguments passed in, which includes the actual name of the program, as invoked by the user. argv contains the actual arguments, starting with index 1. Index 0 is the program name.

So, if you ran your program like this:

./program hello world

Then:

  • argc would be 3.
  • argv[0] would be "./program".
  • argv[1] would be "hello".
  • argv[2] would be "world".

How to check if a variable is an integer in JavaScript?

Be careful while using

num % 1

empty string ('') or boolean (true or false) will return as integer. You might not want to do that

false % 1 // true
'' % 1 //true

Number.isInteger(data)

Number.isInteger(22); //true
Number.isInteger(22.2); //false
Number.isInteger('22'); //false

build in function in the browser. Dosnt support older browsers

Alternatives:

Math.round(num)=== num

However, Math.round() also will fail for empty string and boolean

set the iframe height automatically

Solomon's answer about bootstrap inspired me to add the CSS the bootstrap solution uses, which works really well for me.

.iframe-embed {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
    border: 0;
}
.iframe-embed-wrapper {
    position: relative;
    display: block;
    height: 0;
    padding: 0;
    overflow: hidden;
}
.iframe-embed-responsive-16by9 {
    padding-bottom: 56.25%;
}
<div class="iframe-embed-wrapper iframe-embed-responsive-16by9">
    <iframe class="iframe-embed" src="vid.mp4"></iframe>
</div>

How do the major C# DI/IoC frameworks compare?

Well, after looking around the best comparison I've found so far is:

It was a poll taken in March 2010.

One point of interest to me is that people who've used a DI/IoC Framework and liked/disliked it, StructureMap appears to come out on top.

Also from the poll, it seems that Castle.Windsor and StructureMap seem to be most highly favoured.

Interestingly, Unity and Spring.Net seem to be the popular options which are most generally disliked. (I was considering Unity out of laziness (and Microsoft badge/support), but I'll be looking more closely at Castle Windsor and StructureMap now.)

Of course this probably (?) doesn't apply to Unity 2.0 which was released in May 2010.

Hopefully someone else can provide a comparison based on direct experience.

Best way to test for a variable's existence in PHP; isset() is clearly broken

If the variable you are checking would be in the global scope you could do:

array_key_exists('v', $GLOBALS) 

How do I compare strings in Java?

If you're like me, when I first started using Java, I wanted to use the "==" operator to test whether two String instances were equal, but for better or worse, that's not the correct way to do it in Java.

In this tutorial I'll demonstrate several different ways to correctly compare Java strings, starting with the approach I use most of the time. At the end of this Java String comparison tutorial I'll also discuss why the "==" operator doesn't work when comparing Java strings.

Option 1: Java String comparison with the equals method Most of the time (maybe 95% of the time) I compare strings with the equals method of the Java String class, like this:

if (string1.equals(string2))

This String equals method looks at the two Java strings, and if they contain the exact same string of characters, they are considered equal.

Taking a look at a quick String comparison example with the equals method, if the following test were run, the two strings would not be considered equal because the characters are not the exactly the same (the case of the characters is different):

String string1 = "foo";
String string2 = "FOO";

if (string1.equals(string2))
{
    // this line will not print because the
    // java string equals method returns false:
    System.out.println("The two strings are the same.")
}

But, when the two strings contain the exact same string of characters, the equals method will return true, as in this example:

String string1 = "foo";
String string2 = "foo";

// test for equality with the java string equals method
if (string1.equals(string2))
{
    // this line WILL print
    System.out.println("The two strings are the same.")
}

Option 2: String comparison with the equalsIgnoreCase method

In some string comparison tests you'll want to ignore whether the strings are uppercase or lowercase. When you want to test your strings for equality in this case-insensitive manner, use the equalsIgnoreCase method of the String class, like this:

String string1 = "foo";
String string2 = "FOO";

 // java string compare while ignoring case
 if (string1.equalsIgnoreCase(string2))
 {
     // this line WILL print
     System.out.println("Ignoring case, the two strings are the same.")
 }

Option 3: Java String comparison with the compareTo method

There is also a third, less common way to compare Java strings, and that's with the String class compareTo method. If the two strings are exactly the same, the compareTo method will return a value of 0 (zero). Here's a quick example of what this String comparison approach looks like:

String string1 = "foo bar";
String string2 = "foo bar";

// java string compare example
if (string1.compareTo(string2) == 0)
{
    // this line WILL print
    System.out.println("The two strings are the same.")
}

While I'm writing about this concept of equality in Java, it's important to note that the Java language includes an equals method in the base Java Object class. Whenever you're creating your own objects and you want to provide a means to see if two instances of your object are "equal", you should override (and implement) this equals method in your class (in the same way the Java language provides this equality/comparison behavior in the String equals method).

You may want to have a look at this ==, .equals(), compareTo(), and compare()

How to convert byte array to string

Depending on the encoding you wish to use:

var str = System.Text.Encoding.Default.GetString(result);

Force HTML5 youtube video

I've found the solution :

You have to add the html5=1 in the src attribute of the iframe :

<iframe src="http://www.youtube.com/embed/dP15zlyra3c?html5=1"></iframe>

The video will be displayed as HTML5 if available, or fallback into flash player.

MySQL: Set user variable from result of query

Yes, but you need to move the variable assignment into the query:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

Test case:

CREATE TABLE user (`user` int, `group` int);
INSERT INTO user VALUES (123456, 5);
INSERT INTO user VALUES (111111, 5);

Result:

SET @user := 123456;
SELECT @group := `group` FROM user WHERE user = @user;
SELECT * FROM user WHERE `group` = @group;

+--------+-------+
| user   | group |
+--------+-------+
| 123456 |     5 |
| 111111 |     5 |
+--------+-------+
2 rows in set (0.00 sec)

Note that for SET, either = or := can be used as the assignment operator. However inside other statements, the assignment operator must be := and not = because = is treated as a comparison operator in non-SET statements.


UPDATE:

Further to comments below, you may also do the following:

SET @user := 123456;
SELECT `group` FROM user LIMIT 1 INTO @group; 
SELECT * FROM user WHERE `group` = @group;

How to set cursor to input box in Javascript?

You have not provided enough code to help You likely submit the form and reload the page OR you have an object on the page like an embedded PDF that steals the focus.

Here is the canonical plain javascript method of validating a form It can be improved with onubtrusive JS which will remove the inline script, but this is the starting point DEMO

function validate(formObj) {
  document.getElementById("errorMsg").innerHTML = "";    
  var quantity = formObj.quantity;
  if (isNaN(quantity)) {
    quantity.value="";
    quantity.focus();
    document.getElementById("errorMsg").innerHTML = "Only numeric value is allowed";
    return false;
  }
  return true; // allow submit
}   

Here is the HTML

<form onsubmit="return validate(this)">
    <input type="text" name="quantity" value="" />
    <input type="submit" />
</form>    
<span id="errorMsg"></span>

What exactly does Perl's "bless" do?

For example, if you can be confident that any Bug object is going to be a blessed hash, you can (finally!) fill in the missing code in the Bug::print_me method:

 package Bug;
 sub print_me
 {
     my ($self) = @_;
     print "ID: $self->{id}\n";
     print "$self->{descr}\n";
     print "(Note: problem is fatal)\n" if $self->{type} eq "fatal";
 }

Now, whenever the print_me method is called via a reference to any hash that's been blessed into the Bug class, the $self variable extracts the reference that was passed as the first argument and then the print statements access the various entries of the blessed hash.

git am error: "patch does not apply"

What is a patch?

A patch is little more (see below) than a series of instructions: "add this here", "remove that there", "change this third thing to a fourth". That's why git tells you:

The copy of the patch that failed is found in:
c:/.../project2/.git/rebase-apply/patch

You can open that patch in your favorite viewer or editor, open the files-to-be-changed in your favorite editor, and "hand apply" the patch, using what you know (and git does not) to figure out how "add this here" is to be done when the files-to-be-changed now look little or nothing like what they did when they were changed earlier, with those changes delivered to you as a patch.

A little more

A three-way merge introduces that "little more" information than the plain "series of instructions": it tells you what the original version of the file was as well. If your repository has the original version, your git can compare what you did to a file, to what the patch says to do to the file.

As you saw above, if you request the three-way merge, git can't find the "original version" in the other repository, so it can't even attempt the three-way merge. As a result you get no conflict markers, and you must do the patch-application by hand.

Using --reject

When you have to apply the patch by hand, it's still possible that git can apply most of the patch for you automatically and leave only a few pieces to the entity with the ability to reason about the code (or whatever it is that needs patching). Adding --reject tells git to do that, and leave the "inapplicable" parts of the patch in rejection files. If you use this option, you must still hand-apply each failing patch, and figure out what to do with the rejected portions.

Once you have made the required changes, you can git add the modified files and use git am --continue to tell git to commit the changes and move on to the next patch.

What if there's nothing to do?

Since we don't have your code, I can't tell if this is the case, but sometimes, you wind up with one of the patches saying things that amount to, e.g., "fix the spelling of a word on line 42" when the spelling there was already fixed.

In this particular case, you, having looked at the patch and the current code, should say to yourself: "aha, this patch should just be skipped entirely!" That's when you use the other advice git already printed:

If you prefer to skip this patch, run "git am --skip" instead.

If you run git am --skip, git will skip over that patch, so that if there were five patches in the mailbox, it will end up adding just four commits, instead of five (or three instead of five if you skip twice, and so on).

Bootstrap table without stripe / borders

Most examples seem to be too specific and/or bloated.

Here was my trimmed down solution using Bootstrap 4.0.0 (4.1 includes .table-borderless but still alpha)...

.table-borderless th{border:0;}
.table-borderless td{border:0;}

Similar to many proposed solutions, but minimal bytes

Note: Ended up here because I was viewing BS4.1 references and couldn't figure out why .table-borderless was not working with my 4.0 sources (eg: operator error, duh)

Comparing floating point number to zero

2 + 2 = 5(*)

(for some floating-precision values of 2)

This problem frequently arises when we think of"floating point" as a way to increase precision. Then we run afoul of the "floating" part, which means there is no guarantee of which numbers can be represented.

So while we might easily be able to represent "1.0, -1.0, 0.1, -0.1" as we get to larger numbers we start to see approximations - or we should, except we often hide them by truncating the numbers for display.

As a result, we might think the computer is storing "0.003" but it may instead be storing "0.0033333333334".

What happens if you perform "0.0003 - 0.0002"? We expect .0001, but the actual values being stored might be more like "0.00033" - "0.00029" which yields "0.000004", or the closest representable value, which might be 0, or it might be "0.000006".

With current floating point math operations, it is not guaranteed that (a / b) * b == a.

#include <stdio.h>

// defeat inline optimizations of 'a / b * b' to 'a'
extern double bodge(int base, int divisor) {
    return static_cast<double>(base) / static_cast<double>(divisor);
}

int main() {
    int errors = 0;
    for (int b = 1; b < 100; ++b) {
        for (int d = 1; d < 100; ++d) {
            // b / d * d ... should == b
            double res = bodge(b, d) * static_cast<double>(d);
            // but it doesn't always
            if (res != static_cast<double>(b))
                ++errors;
        }
    }
    printf("errors: %d\n", errors);
}

ideone reports 599 instances where (b * d) / d != b using just the 10,000 combinations of 1 <= b <= 100 and 1 <= d <= 100 .

The solution described in the FAQ is essentially to apply a granularity constraint - to test if (a == b +/- epsilon).

An alternative approach is to avoid the problem entirely by using fixed point precision or by using your desired granularity as the base unit for your storage. E.g. if you want times stored with nanosecond precision, use nanoseconds as your unit of storage.

C++11 introduced std::ratio as the basis for fixed-point conversions between different time units.

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

Simply follow the code

public static String getFormatedDate(String strDate,StringsourceFormate,
                                     String destinyFormate) {
    SimpleDateFormat df;
    df = new SimpleDateFormat(sourceFormate);
    Date date = null;
    try {
        date = df.parse(strDate);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    df = new SimpleDateFormat(destinyFormate);
    return df.format(date);

}

and pass the value into the function like that,

getFormatedDate("21:30:00", "HH:mm", "hh:mm aa");

or checkout this documentation SimpleDateFormat for StringsourceFormate and destinyFormate.

How do you use youtube-dl to download live streams (that are live)?

Before, this could be downloaded with streamlink but YouTube changed HLS rewinding with DASH. Therefore the way to do it below (that Prashant Adlinge commented) no longer works for YouTube:

streamlink --hls-live-restart STREAMURL best

More info here

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

Try change update="insTable:display" to update="display". I believe you cannot prefix the id with the form ID like that.

Switching from zsh to bash on OSX, and back again?

You can just use exec to replace your current shell with a new shell:

Switch to bash:

exec bash

Switch to zsh:

exec zsh

This won't affect new terminal windows or anything, but it's convenient.

Manage toolbar's navigation and back button from fragment in android

Add a toolbar to your xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment title"/>

</android.support.v7.widget.Toolbar>

Then inside your onCreateView method in the Fragment:

Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         getActivity().onBackPressed();
    }
});

How do I kill this tomcat process in Terminal?

In tomcat/bin/catalina.sh

add the following line after just after the comment section ends:

CATALINA_PID=someFile.txt

then, to kill a running instance of Tomcat, you can use:

kill -9 `cat someFile.txt`

FB OpenGraph og:image not pulling images (possibly https?)

tl;dr – be patient

I ended up here because I was seeing blank images served from a https site. The problem was quite a different one though:

When content is shared for the first time, the Facebook crawler will scrape and cache the metadata from the URL shared. The crawler has to see an image at least once before it can be rendered. This means that the first person who shares a piece of content won't see a rendered image

[https://developers.facebook.com/docs/sharing/best-practices/#precaching]

While testing, it took facebook around 10 minutes to finally show the rendered image. So while I was scratching my head and throwing random og tags at facebook (and suspecting the https problem mentioned here), all I had to do was wait.

As this might really stop people from sharing your links for the first time, FB suggests two ways to circumvent this behavior: a) running the OG Debugger on all your links: the image will be cached and ready for sharing after ~10 minutes or b) specifying og:image:width and og:image:height. (Read more in the above link)

Still wondering though what takes them so long ...

How to add a Browse To File dialog to a VB.NET application

You should use the OpenFileDialog class like this

Dim fd As OpenFileDialog = New OpenFileDialog() 
Dim strFileName As String

fd.Title = "Open File Dialog"
fd.InitialDirectory = "C:\"
fd.Filter = "All files (*.*)|*.*|All files (*.*)|*.*"
fd.FilterIndex = 2
fd.RestoreDirectory = True

If fd.ShowDialog() = DialogResult.OK Then
   strFileName = fd.FileName
End If

Then you can use the File class.

Using Jquery AJAX function with datatype HTML

var datos = $("#id_formulario").serialize();
$.ajax({         
    url: "url.php",      
    type: "POST",                   
    dataType: "html",                 
    data: datos,                 
    success: function (prueba) { 
        alert("funciona!");
    }//FIN SUCCES

});//FIN  AJAX

How to restore to a different database in sql server?

  • I have the same error as this topic when I restore a new database using an old database. (using .bak gives the same error)

  • I Changed the name of old database by name of new database (same this picture). It worked.

enter image description here

Cannot ignore .idea/workspace.xml - keeps popping up

Ignore the files ending with .iws, and the workspace.xml and tasks.xml files in your .gitignore Reference

Add ... if string is too long PHP

Use wordwrap() to truncate the string without breaking words if the string is longer than 50 characters, and just add ... at the end:

$str = $input;
if( strlen( $input) > 50) {
    $str = explode( "\n", wordwrap( $input, 50));
    $str = $str[0] . '...';
}

echo $str;

Otherwise, using solutions that do substr( $input, 0, 50); will break words.

How to sort by dates excel?

The hashes are just because your column width is not enough to display the "number".

About the sorting, you should review how you system region and language is configured. For the US region, Excel date input should be "5/17/2012" not "17/05/2012" (this 17-may-12).

Regards

How to read file contents into a variable in a batch file?

To get all the lines of the file loaded into the variable, Delayed Expansion is needed, so do the following:

SETLOCAL EnableDelayedExpansion

for /f "Tokens=* Delims=" %%x in (version.txt) do set Build=!Build!%%x

There is a problem with some special characters, though especially ;, % and !

How do I delete multiple rows in Entity Framework (without foreach)

Best : in EF6 => .RemoveRange()

Example:

db.Table.RemoveRange(db.Table.Where(x => Field == "Something"));

git add, commit and push commands in one?

Set as an alias in bash:

$ alias lazygit="git add .; git commit -a -m '...'; git push;";

Call it:

$ lazygit

(To make this alias permanent, you'd have to include it in your .bashrc or .bash_profile)

Generate a random point within a circle (uniformly)

I don't know if this question is still open for a new solution with all the answer already given, but I happened to have faced exactly the same question myself. I tried to "reason" with myself for a solution, and I found one. It might be the same thing as some have already suggested here, but anyway here it is:

in order for two elements of the circle's surface to be equal, assuming equal dr's, we must have dtheta1/dtheta2 = r2/r1. Writing expression of the probability for that element as P(r, theta) = P{ r1< r< r1 + dr, theta1< theta< theta + dtheta1} = f(r,theta)*dr*dtheta1, and setting the two probabilities (for r1 and r2) equal, we arrive to (assuming r and theta are independent) f(r1)/r1 = f(r2)/r2 = constant, which gives f(r) = c*r. And the rest, determining the constant c follows from the condition on f(r) being a PDF.

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

Although this question has an accepted answer but I think this is a much cleaner way to achieve the desired output

<select required>
<option value="">Select</option>
<option>English</option>
<option>Spanish</option>
</select>

The required attribute in makes it mandatory to select an option from the list.

value="" inside the option tag combined with the required attribute in select tag makes selection of 'Select' option not permissible, thus achieving the required output

How to set Angular 4 background image?

This works for me:

put this in your markup:

<div class="panel panel-default" [ngStyle]="{'background-image': getUrl()}">

then in component:

getUrl()
{
  return "url('http://estringsoftware.com/wp-content/uploads/2017/07/estring-header-lowsat.jpg')";
}

What's the proper value for a checked attribute of an HTML checkbox?

<input ... checked />
<input ... checked="checked" />

Those are equally valid. And in JavaScript:

input.checked = true;
input.setAttribute("checked");
input.setAttribute("checked","checked");

PostgreSQL: Why psql can't connect to server?

In my case I had this error, /var/run/postgresql/.s.PGSQL.5433 (note, one number up from the file it was looking for, .s.PGSQL.5432) was present. Tried the instructions at the top of this page but nothing worked.

Turns out there was an old directory for PostGreSQL 12 config files in /etc/postgresql/12, which I deleted, which solved the issue.

How do I use Apache tomcat 7 built in Host Manager gui?

I'm not sure about Tomcat 7, but with Tomcat 6... once you start Tomcat: By going into the bin directory and starting startup.bat (win) or startup.sh (Unix/osx) it will spin up a local instance of the server running usually on port 8080 by default. Then by going to http://localhost:8080/ and seeing that it is running, there is a link to the manager. If that page is not there, you can try loading the manager by going directly to manager/html, and that will load the Host Manager gui.

http://localhost:8080/manager/html

Make sure Tomcat is running first and that 8080 is the right port. These are just the defaults that tomcat usually runs with.

To login you need to edit the conf/tomcat-users.xml, and create a Manager GUI role

<role rolename="manager-gui"/>

and add that to a user

<user username="admin" password="password" roles="manager-gui"/>

Then when you go to Manager GUI app at http://localhost:8080/manager/html it will prompt you for a username/password, which you added to that config file.

How do I determine height and scrolling position of window in jQuery?

If you need to scroll to a point of an element. You can use Jquery function to scroll it up/down.

$('html, body').animate({
                scrollTop: $("#div1").offset().top
            }, 'slow');

Constants in Kotlin -- what's a recommended way to create them?

First of all, the naming convention in Kotlin for constants is the same than in java (e.g : MY_CONST_IN_UPPERCASE).

How should I create it ?

1. As a top level value (recommended)

You just have to put your const outside your class declaration.

Two possibilities : Declare your const in your class file (your const have a clear relation with your class)

private const val CONST_USED_BY_MY_CLASS = 1

class MyClass { 
    // I can use my const in my class body 
}

Create a dedicated constants.kt file where to store those global const (Here you want to use your const widely across your project) :

package com.project.constants
const val URL_PATH = "https:/"

Then you just have to import it where you need it :

import com.project.constants

MyClass {
    private fun foo() {
        val url = URL_PATH
        System.out.print(url) // https://
    }
}

2. Declare it in a companion object (or an object declaration)

This is much less cleaner because under the hood, when bytecode is generated, a useless object is created :

MyClass {
    companion object {
        private const val URL_PATH = "https://"
        const val PUBLIC_URL_PATH = "https://public" // Accessible in other project files via MyClass.PUBLIC_URL_PATH
    }
}

Even worse if you declare it as a val instead of a const (compiler will generate a useless object + a useless function) :

MyClass {
    companion object {
        val URL_PATH = "https://"
    }
}

Note :

In kotlin, const can just hold primitive types. If you want to pass a function to it, you need add the @JvmField annotation. At compile time, it will be transform as a public static final variable. But it's slower than with a primitive type. Try to avoid it.

@JvmField val foo = Foo()

Read environment variables in Node.js

process.env.ENV_VARIABLE

Where ENV_VARIABLE is the name of the variable you wish to access.

See Node.js docs for process.env.

How can I create an object and add attributes to it?

The mock module is basically made for that.

import mock
obj = mock.Mock()
obj.a = 5

Composer: file_put_contents(./composer.json): failed to open stream: Permission denied

I had this problem to install laravel/lumen.

It can be resolved with the following command:

$ sudo chown -R $USER ~/.composer/

How do I change the database name using MySQL?

You can change the database name using MySQL interface.

Go to http://www.hostname.com/phpmyadmin

Go to database which you want to rename. Next, go to the operation tab. There you will find the input field to rename the database.

Read a XML (from a string) and get some fields - Problems reading XML

Or use the XmlSerializer class.

XmlSerializer xs = new XmlSerializer(objectType);
obj = xs.Deserialize(new StringReader(yourXmlString));

javascript, for loop defines a dynamic variable name

I think you could do it by creating parameters in an object maybe?

var myObject = {}; for(var i=0;i<myArray.length;i++) {     myObject[ myArray[i] ]; } 

If you don't set them to anything, you'll just have an object with some parameters that are undefined. I'd have to write this myself to be sure though.

How to make a drop down list in yii2?

If you made it to the bottom of the list. Save some php code and just bring everything back from the DB as you need like this:

 $items = Standard::find()->select(['name'])->indexBy('s_id')->column();

JQuery addclass to selected div, remove class if another div is selected

It's all about the selector. You can change your code to be something like this:

<div class="formbuilder">
    <div class="active">Heading</div>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
</div>

Then use this javascript:

$(document).ready(function () {
    $('.formbuilder div').on('click', function () {
        $('.formbuilder div').removeClass('active');
        $(this).addClass('active');
    });
});

The example in a working jsfiddle

See this api about the selector I used: http://api.jquery.com/descendant-selector/

What does --net=host option in Docker command really do?

  1. you can create your own new network like --net="anyname"
  2. this is done to isolate the services from different container.
  3. suppose the same service are running in different containers, but the port mapping remains same, the first container starts well , but the same service from second container will fail. so to avoid this, either change the port mappings or create a network.

How to detect if a string contains at least a number?

The simplest method is to use LIKE:

SELECT CASE WHEN 'FDAJLK' LIKE '%[0-9]%' THEN 'True' ELSE 'False' END;  -- False
SELECT CASE WHEN 'FDAJ1K' LIKE '%[0-9]%' THEN 'True' ELSE 'False' END;  -- True

Pandas DataFrame to List of Lists

You could access the underlying array and call its tolist method:

>>> df = pd.DataFrame([[1,2,3],[3,4,5]])
>>> lol = df.values.tolist()
>>> lol
[[1L, 2L, 3L], [3L, 4L, 5L]]

How to update parent's state in React?

I found the following working solution to pass onClick function argument from child to the parent component:

Version with passing a method()

//ChildB component
class ChildB extends React.Component {

    render() {

        var handleToUpdate  =   this.props.handleToUpdate;
        return (<div><button onClick={() => handleToUpdate('someVar')}>
            Push me
          </button>
        </div>)
    }
}

//ParentA component
class ParentA extends React.Component {

    constructor(props) {
        super(props);
        var handleToUpdate  = this.handleToUpdate.bind(this);
        var arg1 = '';
    }

    handleToUpdate(someArg){
            alert('We pass argument from Child to Parent: ' + someArg);
            this.setState({arg1:someArg});
    }

    render() {
        var handleToUpdate  =   this.handleToUpdate;

        return (<div>
                    <ChildB handleToUpdate = {handleToUpdate.bind(this)} /></div>)
    }
}

if(document.querySelector("#demo")){
    ReactDOM.render(
        <ParentA />,
        document.querySelector("#demo")
    );
}

Look at JSFIDDLE

Version with passing an Arrow function

//ChildB component
class ChildB extends React.Component {

    render() {

        var handleToUpdate  =   this.props.handleToUpdate;
        return (<div>
          <button onClick={() => handleToUpdate('someVar')}>
            Push me
          </button>
        </div>)
    }
}

//ParentA component
class ParentA extends React.Component { 
    constructor(props) {
        super(props);
    }

    handleToUpdate = (someArg) => {
            alert('We pass argument from Child to Parent: ' + someArg);
    }

    render() {
        return (<div>
            <ChildB handleToUpdate = {this.handleToUpdate} /></div>)
    }
}

if(document.querySelector("#demo")){
    ReactDOM.render(
        <ParentA />,
        document.querySelector("#demo")
    );
}

Look at JSFIDDLE

How to select all instances of a variable and edit variable name in Sublime

To me, this is the biggest mistake in Sublime. Alt+F3 is hard to reach/remember, and Ctrl+Shift+G makes no sense considering Ctrl+D is "add next instance to selection".

Add this to your User Key Bindings (Preferences > Key Bindings):

{ "keys": ["ctrl+shift+d"], "command": "find_all_under" },

Now you can highlight something, press Ctrl+Shift+D, and it will add every other instance in the file to the selection.

How do I find the authoritative name-server for a domain name?

I have found that for some domains, the above answers do not work. The quickest way I have found is to first check for an NS record. If that doesn't exist, check for an SOA record. If that doesn't exist, recursively resolve the name using dig and take the last NS record returned. An example that fits this is analyticsdcs.ccs.mcafee.com.

  1. Check for an NS record

host -t NS analyticsdcs.ccs.mcafee.com.

  1. If no NS found, check for an SOA record

host -t SOA analyticsdcs.ccs.mcafee.com.

  1. If neither NS or SOA, do full recursive and take the last NS returned

dig +trace analyticsdcs.ccs.mcafee.com. | grep -w 'IN[[:space:]]*NS' | tail -1

  1. Test that the name server returned works

host analyticsdcs.ccs.mcafee.com. gtm2.mcafee.com.

Reading file using fscanf() in C

First of all, you're testing fp twice. so printf("Error Reading File\n"); never gets executed.

Then, the output of fscanf should be equal to 2 since you're reading two values.

How do I determine if a port is open on a Windows server?

Use this if you want to see all the used and listening ports on a Windows server:

netstat -an |find /i "listening"

See all open, listening, established ports:

netstat -a

Trigger event when user scroll to specific element - with jQuery

This should be what you need.

Javascript:

$(window).scroll(function() {
    var hT = $('#circle').offset().top,
        hH = $('#circle').outerHeight(),
        wH = $(window).height(),
        wS = $(this).scrollTop();
    console.log((hT - wH), wS);
    if (wS > (hT + hH - wH)) {
        $('.count').each(function() {
            $(this).prop('Counter', 0).animate({
                Counter: $(this).text()
            }, {
                duration: 900,
                easing: 'swing',
                step: function(now) {
                    $(this).text(Math.ceil(now));
                }
            });
        }); {
            $('.count').removeClass('count').addClass('counted');
        };
    }
});

CSS:

#circle
{
    width: 100px;
    height: 100px;
    background: blue;
    -moz-border-radius: 50px;
    -webkit-border-radius: 50px;
    border-radius: 50px;
    float:left;
    margin:5px;
}
.count, .counted
{
  line-height: 100px;
  color:white;
  margin-left:30px;
  font-size:25px;
}
#talkbubble {
   width: 120px;
   height: 80px;
   background: green;
   position: relative;
   -moz-border-radius:    10px;
   -webkit-border-radius: 10px;
   border-radius:         10px;
   float:left;
   margin:20px;
}
#talkbubble:before {
   content:"";
   position: absolute;
   right: 100%;
   top: 15px;
   width: 0;
   height: 0;
   border-top: 13px solid transparent;
   border-right: 20px solid green;
   border-bottom: 13px solid transparent;
}

HTML:

<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="talkbubble"><span class="count">145</span></div>
<div style="clear:both"></div>
<div id="circle"><span class="count">1234</span></div>

Check this bootply: http://www.bootply.com/atin_agarwal2/cJBywxX5Qp

What is the JSF resource library for and how should it be used?

Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.

Real world examples

To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency or UIViewRoot#addComponentResource()) the following way:

<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />

It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.

Easier identifying

This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.

Also, when you're using a custom ResourceHandler, you can also apply more finer grained control over resources coming from a specific library when library is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler and GraphicResourceHandler; check the createResource() method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource or GraphicResource for the purpose.

Noted should be that RichFaces did it wrong. It didn't use any library at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.

Your own webapp

Your own webapp does not necessarily need a resource library. You'd best just omit it.

<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />

Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml template file:

<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />

And a /WEB-INF/templates/admin.xhtml template file:

<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />

For a real world example, check the OmniFaces showcase source code.

Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):

<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />

Library versioning

Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)* pattern to denote the resource library version.

WebContent
 |-- resources
 |    `-- default
 |         `-- 1_0
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

When using this markup:

<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />

This will generate the following HTML with the library version as v parameter:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_0" alt="" />

So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler will automatically serve the resource from the highest version number, according to numerical ordering rules.

So, when copying/renaming resources/default/1_0/* folder into resources/default/1_1/* like follows:

WebContent
 |-- resources
 |    `-- default
 |         |-- 1_0
 |         |    :
 |         |
 |         `-- 1_1
 |              |-- css
 |              |    `-- style.css
 |              |-- img
 |              |    `-- logo.png
 |              `-- js
 |                   `-- script.js
 :

Then the last markup example would generate the following HTML:

<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&amp;v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&amp;v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&amp;v=1_1" alt="" />

This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.

Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler. See also How to use JSF versioning for resources in jar.

See also:

Simplest way to do a recursive self-join?

Check following to help the understand the concept of CTE recursion

DECLARE
@startDate DATETIME,
@endDate DATETIME

SET @startDate = '11/10/2011'
SET @endDate = '03/25/2012'

; WITH CTE AS (
    SELECT
        YEAR(@startDate) AS 'yr',
        MONTH(@startDate) AS 'mm',
        DATENAME(mm, @startDate) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        @startDate 'new_date'
    UNION ALL
    SELECT
        YEAR(new_date) AS 'yr',
        MONTH(new_date) AS 'mm',
        DATENAME(mm, new_date) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        DATEADD(d,1,new_date) 'new_date'
    FROM CTE
    WHERE new_date < @endDate
    )
SELECT yr AS 'Year', mon AS 'Month', count(dd) AS 'Days'
FROM CTE
GROUP BY mon, yr, mm
ORDER BY yr, mm
OPTION (MAXRECURSION 1000)