Programs & Examples On #Surface toolkit

How to force reloading a page when using browser back button?

You can use pageshow event to handle situation when browser navigates to your page through history traversal:

window.addEventListener( "pageshow", function ( event ) {
  var historyTraversal = event.persisted || 
                         ( typeof window.performance != "undefined" && 
                              window.performance.navigation.type === 2 );
  if ( historyTraversal ) {
    // Handle page restore.
    window.location.reload();
  }
});

Note that HTTP cache may be involved too. You need to set proper cache related HTTP headers on server to cache only those resources that need to be cached. You can also do forced reload to instuct browser to ignore HTTP cache: window.location.reload( true ). But I don't think that it is best solution.

For more information check:

How can I merge two commits into one if I already started rebase?

Rebase: You Ain't Gonna Need It:

A simpler way for most frequent scenario.

In most cases:

Actually if all you want is just simply combine several recent commits into one but do not need drop, reword and other rebase work.

you can simply do:

git reset --soft "HEAD~n"
  • Assuming ~n is number of commits to softly un-commit (i.e. ~1, ~2,...)

Then, use following command to modify the commit message.

git commit --amend

which is pretty much the same as a long range of squash and one pick.

And it works for n commits but not just two commits as above answer prompted.

UITableView load more when scrolling to bottom like Facebook application

You can do that by adding a check on where you're at in the cellForRowAtIndexPath: method. This method is easy to understand and to implement :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Classic start method
    static NSString *cellIdentifier = @"MyCell";
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell)
    {
        cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainMenuCellIdentifier];
    }

    MyData *data = [self.dataArray objectAtIndex:indexPath.row];
    // Do your cell customisation
    // cell.titleLabel.text = data.title;

    BOOL lastItemReached = [data isEqual:[[self.dataArray] lastObject]]; 
    if (!lastItemReached && indexPath.row == [self.dataArray count] - 1)
    {
        [self launchReload];
    }
}

EDIT : added a check on last item to prevent recursion calls. You'll have to implement the method defining whether the last item has been reached or not.

EDIT2 : explained lastItemReached

Rails find_or_create_by more than one attribute?

For anyone else who stumbles across this thread but needs to find or create an object with attributes that might change depending on the circumstances, add the following method to your model:

# Return the first object which matches the attributes hash
# - or -
# Create new object with the given attributes
#
def self.find_or_create(attributes)
  Model.where(attributes).first || Model.create(attributes)
end

Optimization tip: regardless of which solution you choose, consider adding indexes for the attributes you are querying most frequently.

Save attachments to a folder and rename them

See ReceivedTime Property

http://msdn.microsoft.com/en-us/library/office/aa171873(v=office.11).aspx

You added another \ to the end of C:\Temp\ in the SaveAs File line. Could be a problem. Do a test first before adding a path separator.

dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  
saveFolder = "C:\Temp"

You have not set objAtt so there is no need for "Set objAtt = Nothing". If there was it would be just before End Sub not in the loop.


Public Sub saveAttachtoDisk (itm As Outlook.MailItem) 
    Dim objAtt As Outlook.Attachment 
    Dim saveFolder As String Dim dateFormat
    dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  saveFolder = "C:\Temp"
    For Each objAtt In itm.Attachments
        objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
    Next
End Sub

Re: It worked the first day I started tinkering but after that it stopped saving files.

This is usually due to Security settings. It is a "trap" set for first time users to allow macros then take it away. http://www.slipstick.com/outlook-developer/how-to-use-outlooks-vba-editor/

Drop columns whose name contains a specific string from pandas DataFrame

Here is one way to do this:

df = df[df.columns.drop(list(df.filter(regex='Test')))]

What are the date formats available in SimpleDateFormat class?

java.time

UPDATE

The other Questions are outmoded. The terrible legacy classes such as SimpleDateFormat were supplanted years ago by the modern java.time classes.

Custom

For defining your own custom formatting patterns, the codes in DateTimeFormatter are similar to but not exactly the same as the codes in SimpleDateFormat. Be sure to study the documentation. And search Stack Overflow for many examples.

DateTimeFormatter f = 
    DateTimeFormatter.ofPattern( 
        "dd MMM uuuu" , 
        Locale.ITALY 
    ) 
;

Standard ISO 8601

The ISO 8601 standard defines formats for many types of date-time values. These formats are designed for data-exchange, being easily parsed by machine as well as easily read by humans across cultures.

The java.time classes use ISO 8601 formats by default when generating/parsing strings. Simply call the toString & parse methods. No need to specify a formatting pattern.

Instant.now().toString()

2018-11-05T18:19:33.017554Z

For a value in UTC, the Z on the end means UTC, and is pronounced “Zulu”.

Localize

Rather than specify a formatting pattern, you can let java.time automatically localize for you. Use the DateTimeFormatter.ofLocalized… methods.

Get current moment with the wall-clock time used by the people of a particular region (a time zone).

ZoneId z = ZoneId.of( "Africa/Tunis" );
ZonedDateTime zdt = ZonedDateTime.now( z );

Generate text in standard ISO 8601 format wisely extended to append the name of the time zone in square brackets.

zdt.toString(): 2018-11-05T19:20:23.765293+01:00[Africa/Tunis]

Generate auto-localized text.

Locale locale = Locale.CANADA_FRENCH;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.FULL ).withLocale( locale );

String output = zdt.format( f );

output: lundi 5 novembre 2018 à 19:20:23 heure normale d’Europe centrale

Generally a better practice to auto-localize rather than fret with hard-coded formatting patterns.


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.

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

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

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. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?

C default arguments

No.

Not even the very latest C99 standard supports this.

Styling the last td in a table with css

You can use relative rules:

table td + td + td + td + td {
  border: none;
}

This only works if the number of columns isn't determined at runtime.

What's the difference between IFrame and Frame?

The difference is an iframe is able to "float" within content in a page, that is you can create an html page and position an iframe within it. This allows you to have a page and place another document directly in it. A frameset allows you to split the screen into different pages (horizontally and vertically) and display different documents in each part.

Read IFrames security summary.

Can you use @Autowired with static fields?

You can achieve this using XML notation and the MethodInvokingFactoryBean. For an example look here.

private static StaticBean staticBean;

public void setStaticBean(StaticBean staticBean) {
   StaticBean.staticBean = staticBean;
}

You should aim to use spring injection where possible as this is the recommended approach but this is not always possible as I'm sure you can imagine as not everything can be pulled from the spring container or you maybe dealing with legacy systems.

Note testing can also be more difficult with this approach.

Using Html.ActionLink to call action on different controller

With that parameters you're triggering the wrong overloaded function/method.

What worked for me:

<%= Html.ActionLink("Details", "Details", "Product", new { id=item.ID }, null) %>

It fires HtmlHelper.ActionLink(string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)

I'm using MVC 4.

Cheerio!

Deleting Objects in JavaScript

delete is not used for deleting an object in java Script.

delete used for removing an object key in your case

var obj = { helloText: "Hello World!" }; 
var foo = obj;
delete obj;

object is not deleted check obj still take same values delete usage:

delete obj.helloText

and then check obj, foo, both are empty object.

Parsing HTML using Python

Here you can read more about different HTML parsers in Python and their performance. Even though the article is a bit dated it still gives you a good overview.

Python HTML parser performance

I'd recommend BeautifulSoup even though it isn't built in. Just because it's so easy to work with for those kinds of tasks. Eg:

import urllib2
from BeautifulSoup import BeautifulSoup

page = urllib2.urlopen('http://www.google.com/')
soup = BeautifulSoup(page)

x = soup.body.find('div', attrs={'class' : 'container'}).text

Ansible: Store command's stdout in new variable?

You have to store the content as a fact:

- set_fact:
    string_to_echo: "{{ command_output.stdout }}"

JavaScript string with new line - but not using \n

you can use the following function:

  function nl2br (str, is_xhtml) {
     var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
     return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
  } 

like so:

var mystr="line\nanother line\nanother line";
mystr=nl2br(mystr);
alert(mystr);

this should alert line<br>another line<br>another line

the source of the function is from here: http://phpjs.org/functions/nl2br:480

this imitates the nl2br function in php...

How to verify if $_GET exists?

   if (isset($_GET["id"])){
        //do stuff
    }

Setting width/height as percentage minus pixels

Presuming 17px header height

List css:

height: 100%;
padding-top: 17px;

Header css:

height: 17px;
float: left;
width: 100%;

How to check a channel is closed or not without reading it?

From the documentation:

A channel may be closed with the built-in function close. The multi-valued assignment form of the receive operator reports whether a received value was sent before the channel was closed.

https://golang.org/ref/spec#Receive_operator

Example by Golang in Action shows this case:

// This sample program demonstrates how to use an unbuffered
// channel to simulate a game of tennis between two goroutines.
package main

import (
    "fmt"
    "math/rand"
    "sync"
    "time"
)

// wg is used to wait for the program to finish.
var wg sync.WaitGroup

func init() {
    rand.Seed(time.Now().UnixNano())
}

// main is the entry point for all Go programs.
func main() {
    // Create an unbuffered channel.
    court := make(chan int)
    // Add a count of two, one for each goroutine.
    wg.Add(2)
    // Launch two players.
    go player("Nadal", court)
    go player("Djokovic", court)
    // Start the set.
    court <- 1
    // Wait for the game to finish.
    wg.Wait()
}

// player simulates a person playing the game of tennis.
func player(name string, court chan int) {
    // Schedule the call to Done to tell main we are done.
    defer wg.Done()
    for {
        // Wait for the ball to be hit back to us.
        ball, ok := <-court
        fmt.Printf("ok %t\n", ok)
        if !ok {
            // If the channel was closed we won.
            fmt.Printf("Player %s Won\n", name)
            return
        }
        // Pick a random number and see if we miss the ball.
        n := rand.Intn(100)
        if n%13 == 0 {
            fmt.Printf("Player %s Missed\n", name)
            // Close the channel to signal we lost.
            close(court)
            return
        }

        // Display and then increment the hit count by one.
        fmt.Printf("Player %s Hit %d\n", name, ball)
        ball++
        // Hit the ball back to the opposing player.
        court <- ball
    }
}

How to increase number of threads in tomcat thread pool?

From Tomcat Documentation

maxConnections When this number has been reached, the server will accept, but not process, one further connection. once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. (The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.) For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO and NIO2 the default is 10000. For APR/native, the default is 8192. Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons.

maxThreads
The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.

How to update specific key's value in an associative array in PHP?

PHP array_walk() function is specifically for altering array.

Try this:

array_walk ( $data, function (&$key) { 
    $key["transaction_date"] = date('d/m/Y',$key["transaction_date"]); 
});

Ignoring upper case and lower case in Java

You ignore case when you treat the data, not when you retrieve/store it. If you want to store everything in lowercase use String#toLowerCase, in uppercase use String#toUpperCase.

Then when you have to actually treat it, you may use out of the bow methods, like String#equalsIgnoreCase(java.lang.String). If nothing exists in the Java API that fulfill your needs, then you'll have to write your own logic.

In Java, how can I determine if a char array contains a particular character?

From NumberKeyListener source code. This method they use to check if char is contained in defined array of accepted characters:

protected static boolean ok(char[] accept, char c) {
    for (int i = accept.length - 1; i >= 0; i--) {
        if (accept[i] == c) {
            return true;
        }
    }

    return false;
}

It is similar to @ÓscarLópez solution. Might be a bit faster cause of absence of foreach iterator.

How to push elements in JSON from javascript array

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

How to convert a list into data table

you can use this extension method and call it like this.

DataTable dt =   YourList.ToDataTable();

public static DataTable ToDataTable<T>(this List<T> iList)
        {
            DataTable dataTable = new DataTable();
            PropertyDescriptorCollection propertyDescriptorCollection =
                TypeDescriptor.GetProperties(typeof(T));
            for (int i = 0; i < propertyDescriptorCollection.Count; i++)
            {
                PropertyDescriptor propertyDescriptor = propertyDescriptorCollection[i];
                Type type = propertyDescriptor.PropertyType;

                if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
                    type = Nullable.GetUnderlyingType(type);


                dataTable.Columns.Add(propertyDescriptor.Name, type);
            }
            object[] values = new object[propertyDescriptorCollection.Count];
            foreach (T iListItem in iList)
            {
                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = propertyDescriptorCollection[i].GetValue(iListItem);
                }
                dataTable.Rows.Add(values);
            }
            return dataTable;
        }

Checking on a thread / remove from list

mythreads = threading.enumerate()

Enumerate returns a list of all Thread objects still alive. https://docs.python.org/3.6/library/threading.html

How to run ~/.bash_profile in mac terminal

If the problem is that you are not seeing your changes to the file take effect, just open a new terminal window, and it will be "sourced". You will be able to use the proper PATH etc with each subsequent terminal window.

T-SQL and the WHERE LIKE %Parameter% clause

It should be:

...
WHERE LastName LIKE '%' + @LastName + '%';

Instead of:

...
WHERE LastName LIKE '%@LastName%'

Difference Between One-to-Many, Many-to-One and Many-to-Many?

First of all, read all the fine print. Note that NHibernate (thus, I assume, Hibernate as well) relational mapping has a funny correspondance with DB and object graph mapping. For example, one-to-one relationships are often implemented as a many-to-one relationship.

Second, before we can tell you how you should write your O/R map, we have to see your DB as well. In particular, can a single Skill be possesses by multiple people? If so, you have a many-to-many relationship; otherwise, it's many-to-one.

Third, I prefer not to implement many-to-many relationships directly, but instead model the "join table" in your domain model--i.e., treat it as an entity, like this:

class PersonSkill 
{
    Person person;
    Skill skill;    
}

Then do you see what you have? You have two one-to-many relationships. (In this case, Person may have a collection of PersonSkills, but would not have a collection of Skills.) However, some will prefer to use many-to-many relationship (between Person and Skill); this is controversial.

Fourth, if you do have bidirectional relationships (e.g., not only does Person have a collection of Skills, but also, Skill has a collection of Persons), NHibernate does not enforce bidirectionality in your BL for you; it only understands bidirectionality of the relationships for persistence purposes.

Fifth, many-to-one is much easier to use correctly in NHibernate (and I assume Hibernate) than one-to-many (collection mapping).

Good luck!

This API project is not authorized to use this API. Please ensure that this API is activated in the APIs Console

I am late, but here's another gotcha : Google shows the API as enabled, but in fact they are not. Disable then re-enable it.

How to create a directory using Ansible

you can use the "file" module in this case, there are so many arguments that you can pass for a newly created directory like the owner, group, location, mode and so on.....

please refer to this document for the detailed explanation on the file module...

https://docs.ansible.com/ansible/latest/modules/file_module.html#file-module

remember this module is not just for creating the directory !!!

VBA Date as integer

Date is not an Integer in VB(A), it is a Double.

You can get a Date's value by passing it to CDbl().

CDbl(Now())      ' 40877.8052662037 

From the documentation:

The 1900 Date System

In the 1900 date system, the first day that is supported is January 1, 1900. When you enter a date, the date is converted into a serial number that represents the number of elapsed days starting with 1 for January 1, 1900. For example, if you enter July 5, 1998, Excel converts the date to the serial number 35981.

So in the 1900 system, 40877.805... represents 40,876 days after January 1, 1900 (29 November 2011), and ~80.5% of one day (~19:19h). There is a setting for 1904-based system in Excel, numbers will be off when this is in use (that's a per-workbook setting).

To get the integer part, use

Int(CDbl(Now())) ' 40877

which would return a LongDouble with no decimal places (i.e. what Floor() would do in other languages).

Using CLng() or Round() would result in rounding, which will return a "day in the future" when called after 12:00 noon, so don't do that.

How does the keyword "use" work in PHP and can I import classes with it?

use doesn't include anything. It just imports the specified namespace (or class) to the current scope

If you want the classes to be autoloaded - read about autoloading

ng-if, not equal to?

This is now possible as of AngularJS 1.5.10, using ng-switch-when-separator

_x000D_
_x000D_
var app = angular.module("app", []); _x000D_
_x000D_
app.controller("ctrl", function($scope) {_x000D_
    $scope.myDataSet = [{Name: 'Michelle', Gender: 'Female', DOB: '01/12/1986', Payment: [{Status: '0'}]},{Name: 'Steve', Gender: 'Male', DOB: '11/12/1982', Payment: [{Status: '1'}]},{Name: 'Dan', Gender: 'Male', DOB: '03/22/1976', Payment: [{Status: '2'}]},{Name: 'Doug', Gender: 'Male', DOB: '02/02/1980', Payment: [{Status: '3'}]},{Name: 'Mary', Gender: 'Female', DOB: '04/02/1976', Payment: [{Status: '4'}]},{Name: 'Cheyenne', Gender: 'Female', DOB: '07/10/1981', Payment: [{Status: '5'}]},{Name: 'Bob', Gender: 'Male', DOB: '02/16/1990', Payment: [{Status: '6'}]},{Name: 'Bad data', Gender: 'Blank', DOB: '01/01/1970', Payment: [{Status: '7'}]}];_x000D_
});
_x000D_
<script src="https://code.angularjs.org/1.5.10/angular.min.js"></script>_x000D_
<div ng-app="app" ng-controller="ctrl">_x000D_
    <div ng-repeat="details in myDataSet" ng-switch on="details.Payment[0].Status">_x000D_
_x000D_
        <p>{{ details.Name }}</p>_x000D_
        <p>{{ details.DOB  }}</p>_x000D_
_x000D_
        <div ng-switch-when="0">_x000D_
            <p>No payment</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="1|2" ng-switch-when-separator="|">_x000D_
            <p>Late</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="3|4|5" ng-switch-when-separator="|">_x000D_
            <p>Some payment made</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-when="6">_x000D_
            <p>Late and further taken out</p>_x000D_
        </div>_x000D_
_x000D_
        <div ng-switch-default>_x000D_
            <p>Error</p>_x000D_
        </div>_x000D_
        _x000D_
        <p>{{ details.Gender}}</p>_x000D_
_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Reading a List from properties file and load with spring annotation @Value

I think this is simpler for grabbing the array and stripping spaces:

@Value("#{'${my.array}'.replace(' ', '').split(',')}")
private List<String> array;

How can I define an array of objects?

 var xxxx : { [key:number]: MyType };

Git error on commit after merge - fatal: cannot do a partial commit during a merge

During a merge Git wants to keep track of the parent branches for all sorts of reasons. What you want to do is not a merge as git sees it. You will likely want to do a rebase or cherry-pick manually.

How to use mongoose findOne

You might want to consider using console.log with the built-in "arguments" object:

console.log(arguments); // would have shown you [0] null, [1] yourResult

This will always output all of your arguments, no matter how many arguments you have.

CodeIgniter htaccess and URL rewrite issues

There are 3 steps to remove index.php.

  1. Make below changes in application/config.php file

    $config['base_url'] = 'http://'.$_SERVER['SERVER_NAME'].'/Your Ci folder_name';
    $config['index_page'] = '';
    $config['uri_protocol'] = 'AUTO';
    
  2. Make .htaccess file in your root directory using below code

    RewriteEngine on
    RewriteCond $1 !^(index\.php|resources|robots\.txt)
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L,QSA]
    
  3. Enable the rewrite engine (if not already enabled)

    i. First, initiate it with the following command:

    a2enmod rewrite
    

    ii. Edit the file /etc/apache2/sites-enabled/000-default

    Change all AllowOverride None to AllowOverride All.

    Note: In latest version you need to change in /etc/apache2/apache2.conf file

    iii. Restart your server with the following command:

    sudo /etc/init.d/apache2 restart
    

Remove querystring from URL

var path = "path/to/myfile.png?foo=bar#hash";

console.log(
    path.replace(/(\?.*)|(#.*)/g, "")
);

Using msbuild to execute a File System Publish Profile

FYI: I had the same issue with Visual Studio 2015. After many of hours trying, I can now do msbuild myproject.csproj /p:DeployOnBuild=true /p:PublishProfile=myprofile.

I had to edit my .csproj file to get it working. It contained a line like this:

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" 
  Condition="false" />

I changed this line as follows:

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v14.0\WebApplications\Microsoft.WebApplication.targets" />

(I changed 10.0 to 14.0, not sure whether this was necessary. But I definitely had to remove the condition part.)

Converting unix timestamp string to readable date

quick and dirty one liner:

'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))

'2013-5-5-1-9-43'

jquery function setInterval

You can use it like this:

$(document).ready(function(){

    setTimeout("swapImages()",1000);

    function swapImages(){

        var active = $('.active'); 
        var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');

        active.removeClass('active');
        next.addClass('active');
        setTimeout("swapImages()",1000);
}

});

Using 'starts with' selector on individual class names

If an element has multiples classes "[class^='apple-']" dosen't work, e.g.

<div class="fruits apple-monkey"></div>

Windows 7 SDK installation failure

One of the things to also keep in mind is that when you have Visual Studio 2010 SP1 installed some C++ compilers and libraries may have been removed. There's been an update made available by Microsoft to make sure those are brought back to your system.

Install this update to restore the Visual C++ compilers and libraries that may have been removed when Visual Studio 2010 Service Pack 1 (SP1) was installed. The compilers and libraries are part of the Microsoft Windows Software Development Kit for Windows 7 and the .NET Framework 4 (later referred to as the Windows SDK 7.1).

Also, when you read the VS2010 SP1 README you'll also notice that some notes have been made in regards to the Windows 7 SDK (See section 2.2.1) installation. It may be that one of these conditions may apply to you and therefore may need to uncheck the C++ compiler-checkbox as the SDK installer will attempt to install an older version of compilers ÓR you may need to uninstall VS2010 SP1 and re-run the SDK 7.1 installation, repair or modification.

Condition 1: If the Visual C++ Compilers checkbox is selected when the Windows SDK 7.1 is installed, repaired, or modified after Visual Studio 2010 SP1 has been installed, the error may be encountered and some selected components may not be installed.

Workaround: Clear the Visual C++ Compilers checkbox before you run the Windows SDK 7.1 installation, repair, or modification.

Condition 2: If the Visual C++ Compilers checkbox is selected when the Windows SDK 7.1 is installed, repaired, or modified after Visual Studio 2010 has been installed but Visual Studio 2010 SP1 has not been uninstalled, the error may be encountered.

Workaround: Uninstall Visual Studio 2010 SP1 and then rerun the Windows SDK 7.1 installation, repair, or modification.

However, even then I found that I still needed to uninstall any existing Visual C++ 2010 redistributables, as has been suggested by mgrandi.

An unhandled exception occurred during the execution of the current web request. ASP.NET

Here is the code with line 156, it has try and catch above it

    /// <summary>
    /// Execute a SQL Query statement, using the default SQL connection for the application
    /// </summary>
    /// <param name="query">SQL query to execute</param>
    /// <returns>DataTable of results</returns>
    public static DataTable Query(string query)
    {
        DataTable results = new DataTable();
        string configConnectionString = "ApplicationServices";

        System.Configuration.Configuration WebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/Web.config");
        System.Configuration.ConnectionStringSettings connString;

        if (WebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
        {
            connString = WebConfig.ConnectionStrings.ConnectionStrings[configConnectionString];

            if (connString != null)
            {
                try
                {
                    using (SqlConnection conn = new SqlConnection(connString.ToString()))
                    using (SqlCommand cmd = new SqlCommand(query, conn))
                    using (SqlDataAdapter dataAdapter = new SqlDataAdapter(cmd))
                        dataAdapter.Fill(results);

                    return results;
                }
                catch (Exception ex)
                {
                    throw new SqlException(string.Format("SqlException occurred during query execution: ", ex));
                }
            }
            else
            {
                throw new SqlException(string.Format("Connection string for " + configConnectionString + "is null."));
            }
        }
        else
        {
            throw new SqlException(string.Format("No connection strings found in Web.config file."));
        }
    }

jQuery - Fancybox: But I don't want scrollbars!

My 2 cents, write

*{ margin:0; padding:0; }

in your target page main css, add a content div with the height size of all your elements, don't touch the .js, listo, saludos

How to join two tables by multiple columns in SQL?

No, just include the different fields in the "ON" clause of 1 inner join statement:

SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
    AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum

Python: Importing urllib.quote

urllib went through some changes in Python3 and can now be imported from the parse submodule

>>> from urllib.parse import quote  
>>> quote('"')                      
'%22'                               

Angular - Set headers for every request

I like the idea to override default options, this seems like a good solution.

However, if you are up to extending the Http class. Make sure to read this through!

Some answers here are actually showing incorrect overloading of request() method, which could lead to a hard-to-catch errors and weird behavior. I've stumbled upon this myself.

This solution is based on request() method implementation in Angular 4.2.x, but should be future-compatible:

import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';

import {
  ConnectionBackend, Headers,
  Http as NgHttp,
  Request,
  RequestOptions,
  RequestOptionsArgs,
  Response,
  XHRBackend
} from '@angular/http';


import {AuthenticationStateService} from '../authentication/authentication-state.service';


@Injectable()
export class Http extends NgHttp {

  constructor (
    backend: ConnectionBackend,
    defaultOptions: RequestOptions,
    private authenticationStateService: AuthenticationStateService
  ) {
    super(backend, defaultOptions);
  }


  request (url: string | Request, options?: RequestOptionsArgs): Observable<Response> {

    if ('string' === typeof url) {

      url = this.rewriteUrl(url);
      options = (options || new RequestOptions());
      options.headers = this.updateHeaders(options.headers);

      return super.request(url, options);

    } else if (url instanceof Request) {

      const request = url;
      request.url = this.rewriteUrl(request.url);
      request.headers = this.updateHeaders(request.headers);

      return super.request(request);

    } else {
      throw new Error('First argument must be a url string or Request instance');
    }

  }


  private rewriteUrl (url: string) {
    return environment.backendBaseUrl + url;
  }

  private updateHeaders (headers?: Headers) {

    headers = headers || new Headers();

    // Authenticating the request.
    if (this.authenticationStateService.isAuthenticated() && !headers.has('Authorization')) {
      headers.append('Authorization', 'Bearer ' + this.authenticationStateService.getToken());
    }

    return headers;

  }

}

Notice that I'm importing original class this way import { Http as NgHttp } from '@angular/http'; in order to prevent name clashes.

The problem addressed here is that request() method has two different call signatures. When Request object is passed instead of the URL string, the options argument is ignored by Angular. So both cases must be properly handled.

And here's the example of how to register this overridden class with DI container:

export const httpProvider = {
  provide: NgHttp,
  useFactory: httpFactory,
  deps: [XHRBackend, RequestOptions, AuthenticationStateService]
};


export function httpFactory (
  xhrBackend: XHRBackend,
  requestOptions: RequestOptions,
  authenticationStateService: AuthenticationStateService
): Http {
  return new Http(
    xhrBackend,
    requestOptions,
    authenticationStateService
  );
}

With such approach you can inject Http class normally, but your overridden class will be magically injected instead. This allows you to integrate your solution easily without changing other parts of the application (polymorphism in action).

Just add httpProvider to the providers property of your module metadata.

Can I run Keras model on gpu?

See if your script is running GPU in Task manager. If not, suspect your CUDA version is right one for the tensorflow version you are using, as the other answers suggested already.

Additionally, a proper CUDA DNN library for the CUDA version is required to run GPU with tensorflow. Download/extract it from here and put the DLL (e.g., cudnn64_7.dll) into CUDA bin folder (e.g., C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin).

Filter dict to contain only certain keys?

Given your original dictionary orig and the set of entries that you're interested in keys:

filtered = dict(zip(keys, [orig[k] for k in keys]))

which isn't as nice as delnan's answer, but should work in every Python version of interest. It is, however, fragile to each element of keys existing in your original dictionary.

How to convert String into Hashmap in java

You can do it in single line, for any object type not just Map.

(Since I use Gson quite liberally, I am sharing a Gson based approach)

Gson gson = new Gson();    
Map<Object,Object> attributes = gson.fromJson(gson.toJson(value),Map.class);

What it does is:

  1. gson.toJson(value) will serialize your object into its equivalent Json representation.
  2. gson.fromJson will convert the Json string to specified object. (in this example - Map)

There are 2 advantages with this approach:

  1. The flexibility to pass an Object instead of String to toJson method.
  2. You can use this single line to convert to any object even your own declared objects.

comparing 2 strings alphabetically for sorting purposes

Lets say that we have an array of objects:

{ name : String }

then we can sort our array as follows:

array.sort(function(a, b) {
    var orderBool = a.name > b.name;
    return orderBool ? 1 : -1;
});

Note: Be careful for upper letters, you may need to cast your string to lower case due to your purpose.

How to convert a string to lower case in Bash?

I know this is an oldish post but I made this answer for another site so I thought I'd post it up here:

UPPER -> lower: use python:

b=`echo "print '$a'.lower()" | python`

Or Ruby:

b=`echo "print '$a'.downcase" | ruby`

Or Perl:

b=`perl -e "print lc('$a');"`

Or PHP:

b=`php -r "print strtolower('$a');"`

Or Awk:

b=`echo "$a" | awk '{ print tolower($1) }'`

Or Sed:

b=`echo "$a" | sed 's/./\L&/g'`

Or Bash 4:

b=${a,,}

Or NodeJS:

b=`node -p "\"$a\".toLowerCase()"`

You could also use dd:

b=`echo "$a" | dd  conv=lcase 2> /dev/null`

lower -> UPPER:

use python:

b=`echo "print '$a'.upper()" | python`

Or Ruby:

b=`echo "print '$a'.upcase" | ruby`

Or Perl:

b=`perl -e "print uc('$a');"`

Or PHP:

b=`php -r "print strtoupper('$a');"`

Or Awk:

b=`echo "$a" | awk '{ print toupper($1) }'`

Or Sed:

b=`echo "$a" | sed 's/./\U&/g'`

Or Bash 4:

b=${a^^}

Or NodeJS:

b=`node -p "\"$a\".toUpperCase()"`

You could also use dd:

b=`echo "$a" | dd  conv=ucase 2> /dev/null`

Also when you say 'shell' I'm assuming you mean bash but if you can use zsh it's as easy as

b=$a:l

for lower case and

b=$a:u

for upper case.

git pull error "The requested URL returned error: 503 while accessing"

A 50X error is an internal server error. There's nothing wrong on your end, but something's up on the server's end.

http://www.checkupdown.com/status/E503.html

The Web server (running the Web site) is currently unable to handle the HTTP request due to a temporary overloading or maintenance of the server. The implication is that this is a temporary condition which will be alleviated after some delay.

Just be patient and wait. :-)

PHP salt and hash SHA256 for login password

I think @Flo254 chained $salt to $password1and stored them to $hashed variable. $hashed variable goes inside INSERT query with $salt.

How to use QueryPerformanceCounter?

I use these defines:

/** Use to init the clock */
#define TIMER_INIT \
    LARGE_INTEGER frequency; \
    LARGE_INTEGER t1,t2; \
    double elapsedTime; \
    QueryPerformanceFrequency(&frequency);


/** Use to start the performance timer */
#define TIMER_START QueryPerformanceCounter(&t1);

/** Use to stop the performance timer and output the result to the standard stream. Less verbose than \c TIMER_STOP_VERBOSE */
#define TIMER_STOP \
    QueryPerformanceCounter(&t2); \
    elapsedTime=(float)(t2.QuadPart-t1.QuadPart)/frequency.QuadPart; \
    std::wcout<<elapsedTime<<L" sec"<<endl;

Usage (brackets to prevent redefines):

TIMER_INIT

{
   TIMER_START
   Sleep(1000);
   TIMER_STOP
}

{
   TIMER_START
   Sleep(1234);
   TIMER_STOP
}

Output from usage example:

1.00003 sec
1.23407 sec

c++ and opencv get and set pixel color to Mat

just use a reference:

Vec3b & color = image.at<Vec3b>(y,x);
color[2] = 13;

Lua - Current time in milliseconds

In standard C lua, no. You will have to settle for seconds, unless you are willing to modify the lua interpreter yourself to have os.time use the resolution you want. That may be unacceptable, however, if you are writing code for other people to run on their own and not something like a web application where you have full control of the environment.

Edit: another option is to write your own small DLL in C that extends lua with a new function that would give you the values you want, and require that dll be distributed with your code to whomever is going to be using it.

How to convert a factor to integer\numeric without loss of information?

From the many answers I could read, the only given way was to expand the number of variables according to the number of factors. If you have a variable "pet" with levels "dog" and "cat", you would end up with pet_dog and pet_cat.

In my case I wanted to stay with the same number of variables, by just translating the factor variable to a numeric one, in a way that can applied to many variables with many levels, so that cat=1 and dog=0 for instance.

Please find the corresponding solution below:

crime <- data.frame(city = c("SF", "SF", "NYC"),
                    year = c(1990, 2000, 1990),
                    crime = 1:3)

indx <- sapply(crime, is.factor)

crime[indx] <- lapply(crime[indx], function(x){ 
  listOri <- unique(x)
  listMod <- seq_along(listOri)
  res <- factor(x, levels=listOri)
  res <- as.numeric(res)
  return(res)
}
)

What are the Ruby File.open modes and options?

In Ruby IO module documentation, I suppose.

Mode |  Meaning
-----+--------------------------------------------------------
"r"  |  Read-only, starts at beginning of file  (default mode).
-----+--------------------------------------------------------
"r+" |  Read-write, starts at beginning of file.
-----+--------------------------------------------------------
"w"  |  Write-only, truncates existing file
     |  to zero length or creates a new file for writing.
-----+--------------------------------------------------------
"w+" |  Read-write, truncates existing file to zero length
     |  or creates a new file for reading and writing.
-----+--------------------------------------------------------
"a"  |  Write-only, starts at end of file if file exists,
     |  otherwise creates a new file for writing.
-----+--------------------------------------------------------
"a+" |  Read-write, starts at end of file if file exists,
     |  otherwise creates a new file for reading and
     |  writing.
-----+--------------------------------------------------------
"b"  |  Binary file mode (may appear with
     |  any of the key letters listed above).
     |  Suppresses EOL <-> CRLF conversion on Windows. And
     |  sets external encoding to ASCII-8BIT unless explicitly
     |  specified.
-----+--------------------------------------------------------
"t"  |  Text file mode (may appear with
     |  any of the key letters listed above except "b").

Is putting a div inside an anchor ever correct?

If you change it to a block-style element, then no, it's no longer 'wrong', but it probably won't validate. But it doesn't make much sense to do what you're doing. You should either just keep the anchor tag as a block level element with no inner div, or put the div on the outside.

Where can I find jenkins restful api reference?

Additional Solution: use Restul api wrapper libraries written in Java / python / Ruby - An object oriented wrappers which aim to provide a more conventionally way of controlling a Jenkins server.

For documentation and links: Remote Access API

Android Text over image

You may want to take if from a diffrent side: It seems easier to have a TextView with a drawable on the background:

 <TextView
            android:id="@+id/text"
            android:background="@drawable/rounded_rectangle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        </TextView>

How do I declare a 2d array in C++ using new?

I have left you with a solution which works the best for me, in certain cases. Especially if one knows [the size of?] one dimension of the array. Very useful for an array of chars, for instance if we need an array of varying size of arrays of char[20].

int  size = 1492;
char (*array)[20];

array = new char[size][20];
...
strcpy(array[5], "hola!");
...
delete [] array;

The key is the parentheses in the array declaration.

Server cannot set status after HTTP headers have been sent IIS7.5

The HTTP server doesn't send the response header back to the client until you either specify an error or else you start sending data. If you start sending data back to the client, then the server has to send the response head (which contains the status code) first. Once the header has been sent, you can no longer put a status code in the header, obviously.

Here's the usual problem. You start up the page, and send some initial tags (i.e. <head>). The server then sends those tags to the client, after first sending the HTTP response header with an assumed SUCCESS status. Now you start working on the meat of the page and discover a problem. You can not send an error at this point because the response header, which would contain the error status, has already been sent.

The solution is this: Before you generate any content at all, check if there are going to be any errors. Only then, when you have assured that there will be no problems, can you then start sending content, like the tag.

In your case, it seems like you have a login page that processes a POST request from a form. You probably throw out some initial HTML, then check if the username and password are valid. Instead, you should authenticate the user/password first, before you generate any HTML at all.

How to select a schema in postgres when using psql?

key word :

SET search_path TO

example :

SET search_path TO your_schema_name;

CodeIgniter - Correct way to link to another page in a view

The best way is to use the following code:

<a href="<?php echo base_url() ?>directory_name/filename.php">Link</a>

Visual studio code CSS indentation and formatting

Go to Files menu -> Preference -> Extentions Then type CSS Formatter wait for it to load and click install

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

I think you can change the "Automatically detect settings" via the registry key name "AutoConfigURL". here is the code that I check in c#. Wish you luck.

    RegistryKey registry = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings", true);
                    if(registry.GetValue("AutoConfigURL") != null)
                    {
                        //Proxy Server disabled (Untick Proxy Server)
                        registry.DeleteValue("AutoConfigURL");
                    }

What does '--set-upstream' do?

git branch --set-upstream <remote-branch>

sets the default remote branch for the current local branch.

Any future git pull command (with the current local branch checked-out),
will attempt to bring in commits from the <remote-branch> into the current local branch.


One way to avoid having to explicitly type --set-upstream is to use its shorthand flag -u as follows:

git push -u origin local-branch

This sets the upstream association for any future push/pull attempts automatically.
For more details, checkout this detailed explanation about upstream branches and tracking.


To avoid confusion, recent versions of git deprecate this somewhat ambiguous --set-upstream option in favour of a more verbose --set-upstream-to option with identical syntax and behaviour

git branch --set-upstream-to <origin/remote-branch>

What is the difference between JVM, JDK, JRE & OpenJDK?

JRE executes the application but JVM reads the instructions line by line so it's interpreter.

JDK=JRE+Development Tools

JRE=JVM+Library Classes

Try-Catch-End Try in VBScript doesn't seem to work

VBScript doesn't have Try/Catch. (VBScript language reference. If it had Try, it would be listed in the Statements section.)

On Error Resume Next is the only error handling in VBScript. Sorry. If you want try/catch, JScript is an option. It's supported everywhere that VBScript is and has the same capabilities.

How to perform a sum of an int[] array

int sum=0;
for(int i:A)
  sum+=i;

How to create a custom exception type in Java?

Great answers about creating custom exception classes. If you intend to reuse the exception in question then I would follow their answers/advice. However, If you only need a quick exception thrown with a message then you can use the base exception class on the spot

String word=reader.readLine();

if(word.contains(" "))
  /*create custom exeception*/
  throw new Exception("My one time exception with some message!");
}

nodejs module.js:340 error: cannot find module

I had the same problem, but finally I tried copying the Node_modules folder in the same project folder, and it worked.

Using GCC to produce readable assembly?

If you give GCC the flag -fverbose-asm, it will

Put extra commentary information in the generated assembly code to make it more readable.

[...] The added comments include:

  • information on the compiler version and command-line options,
  • the source code lines associated with the assembly instructions, in the form FILENAME:LINENUMBER:CONTENT OF LINE,
  • hints on which high-level expressions correspond to the various assembly instruction operands.

Convert SVG to PNG in Python

Another solution I've just found here How to render a scaled SVG to a QImage?

from PySide.QtSvg import *
from PySide.QtGui import *


def convertSvgToPng(svgFilepath,pngFilepath,width):
    r=QSvgRenderer(svgFilepath)
    height=r.defaultSize().height()*width/r.defaultSize().width()
    i=QImage(width,height,QImage.Format_ARGB32)
    p=QPainter(i)
    r.render(p)
    i.save(pngFilepath)
    p.end()

PySide is easily installed from a binary package in Windows (and I use it for other things so is easy for me).

However, I noticed a few problems when converting country flags from Wikimedia, so perhaps not the most robust svg parser/renderer.

How to check if input date is equal to today's date?

Try using moment.js

moment('dd/mm/yyyy').isSame(Date.now(), 'day');

You can replace 'day' string with 'year, month, minute' if you want.

Numpy Resize/Rescale Image

SciPy's imresize() method was another resize method, but it will be removed starting with SciPy v 1.3.0 . SciPy refers to PIL image resize method: Image.resize(size, resample=0)

size – The requested size in pixels, as a 2-tuple: (width, height).
resample – An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation), PIL.Image.BICUBIC (cubic spline interpolation), or PIL.Image.LANCZOS (a high-quality downsampling filter). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST.

Link here: https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize

jQuery vs. javascript?

Jquery VS javascript, I am completely against the OP in this question. Comparison happens with two similar things, not in such case.

Jquery is Javascript. A javascript library to reduce vague coding, collection commonly used javascript functions which has proven to help in efficient and fast coding.

Javascript is the source, the actual scripts that browser responds to.

Creating an array of objects in Java

Yes it is correct in Java there are several steps to make an array of objects:

  1. Declaring and then Instantiating (Create memory to store '4' objects):

    A[ ] arr = new A[4];
    
  2. Initializing the Objects (In this case you can Initialize 4 objects of class A)

    arr[0] = new A();
    arr[1] = new A();
    arr[2] = new A();
    arr[3] = new A();
    

    or

    for( int i=0; i<4; i++ )
      arr[i] = new A();
    

Now you can start calling existing methods from the objects you just made etc.

For example:

  int x = arr[1].getNumber();

or

  arr[1].setNumber(x);

How can I clear previous output in Terminal in Mac OS X?

With Mac OS X v10.10 (Yosemite), use Option + Command + K to clear the scrollback in Terminal.app.

Write lines of text to a file in R

Actually you can do it with sink():

sink("outfile.txt")
cat("hello")
cat("\n")
cat("world")
sink()

hence do:

file.show("outfile.txt")
# hello
# world

How to overlay one div over another div

The new Grid CSS specification provides a far more elegant solution. Using position: absolute may lead to overlaps or scaling issues while Grid will save you from dirty CSS hacks.

Most minimal Grid Overlay example:

HTML

<div class="container">
  <div class="content">This is the content</div>
  <div class="overlay">Overlay - must be placed under content in the HTML</div>
</div>

CSS

.container {
  display: grid;
}

.content, .overlay {
  grid-area: 1 / 1;
}

That's it. If you don't build for Internet Explorer, your code will most probably work.

How to convert int to date in SQL Server 2008

You can't convert an integer value straight to a date but you can first it to a datetime then to a date type

select cast(40835 as datetime)

and then convert to a date (SQL 2008)

select cast(cast(40835 as datetime) as date)

cheers

Centering a background image, using CSS

if your not satisfied with the answers above then use this

    * {margin: 0;padding: 0;}

    html
    {
        height: 100%;
    }

    body
    {
        background-image: url("background.png");
        background-repeat: no-repeat;
        background-position: center center;
        background-size: 80%;
    }

postgresql - sql - count of `true` values

Cast the Boolean to an integer and sum.

SELECT count(*),sum(myCol::int);

You get 6,3.

Pandas read in table without headers

Make sure you specify pass header=None and add usecols=[3,6] for the 4th and 7th columns.

Extracting date from a string in Python

You could also try the dateparser module, which may be slower than datefinder on free text but which should cover more potential cases and date formats, as well as a significant number of languages.

How to read file from relative path in Java project? java.io.File cannot find the path specified

The following line can be used if we want to specify the relative path of the file.

File file = new File("./properties/files/ListStopWords.txt");  

How can I make text appear on next line instead of overflowing?

Well, you can stick one or more "soft hyphens" (&#173;) in your long unbroken strings. I doubt that old IE versions deal with that correctly, but what it's supposed to do is tell the browser about allowable word breaks that it can use if it has to.

Now, how exactly would you pick where to stuff those characters? That depends on the actual string and what it means, I guess.

Why can't I have abstract static methods in C#?

Another respondent (McDowell) said that polymorphism only works for object instances. That should be qualified; there are languages that do treat classes as instances of a "Class" or "Metaclass" type. These languages do support polymorphism for both instance and class (static) methods.

C#, like Java and C++ before it, is not such a language; the static keyword is used explicitly to denote that the method is statically-bound rather than dynamic/virtual.

How can I concatenate two arrays in Java?

I found a one-line solution from the good old Apache Commons Lang library.
ArrayUtils.addAll(T[], T...)

Code:

String[] both = ArrayUtils.addAll(first, second);

How to get an element's top position relative to the browser's viewport?

var element =  document.querySelector('selector');
var bodyRect = document.body.getBoundingClientRect(),
    elemRect = element.getBoundingClientRect(),
    offset   = elemRect.top - bodyRect.top;

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

I have other solution, my application need to be started when new object of MyApp is created, so it looks like:

function MyApp(objId){
     this.init=function(){
        //.........
     }
     this.run=function(){
          if(!document || !document.body || !window[objId]){
              window.setTimeout(objId+".run();",100);
              return;
          }
          this.init();
     };
     this.run();
}
//and i am starting it 
var app=new MyApp('app');

it is working on all browsers, that i know.

Can I check if Bootstrap Modal Shown / Hidden?

its an old question but anyway heres something i used incase someone was looking for the same thing

if (!$('#myModal').is(':visible')) {
    // if modal is not shown/visible then do something
}

UTF-8 output from PowerShell

Spent some time working on a solution to my issue and thought it may be of interest. I ran into a problem trying to automate code generation using PowerShell 3.0 on Windows 8. The target IDE was the Keil compiler using MDK-ARM Essential Toolchain 5.24.1. A bit different from OP, as I am using PowerShell natively during the pre-build step. When I tried to #include the generated file, I received the error

fatal error: UTF-16 (LE) byte order mark detected '..\GITVersion.h' but encoding is not supported

I solved the problem by changing the line that generated the output file from:

out-file -FilePath GITVersion.h -InputObject $result

to:

out-file -FilePath GITVersion.h -Encoding ascii -InputObject $result

How to find MySQL process list and to kill those processes?

Here is the solution:

  1. Login to DB;
  2. Run a command show full processlist;to get the process id with status and query itself which causes the database hanging;
  3. Select the process id and run a command KILL <pid>; to kill that process.

Sometimes it is not enough to kill each process manually. So, for that we've to go with some trick:

  1. Login to MySQL;
  2. Run a query Select concat('KILL ',id,';') from information_schema.processlist where user='user'; to print all processes with KILL command;
  3. Copy the query result, paste and remove a pipe | sign, copy and paste all again into the query console. HIT ENTER. BooM it's done.

Ways to circumvent the same-origin policy

The Reverse Proxy method

  • Method type: Ajax

Setting up a simple reverse proxy on the server, will allow the browser to use relative paths for the Ajax requests, while the server would be acting as a proxy to any remote location.

If using mod_proxy in Apache, the fundamental configuration directive to set up a reverse proxy is the ProxyPass. It is typically used as follows:

ProxyPass     /ajax/     http://other-domain.com/ajax/

In this case, the browser would be able to request /ajax/web_service.xml as a relative URL, but the server would serve this by acting as a proxy to http://other-domain.com/ajax/web_service.xml.

One interesting feature of the this method is that the reverse proxy can easily distribute requests towards multiple back-ends, thus acting as a load balancer.

Timer Interval 1000 != 1 second?

Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

How to count items in JSON data

import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.

How do I create an .exe for a Java program?

Most of the programs that convert java applications to .exe files are just wrappers around the program, and the end user will still need the JRE installed to run it. As far as I know there aren't any converters that will make it a native executable from bytecode (There have been attempts, but if any turned out successful you would hear of them by now).

As for wrappers, the best ones i've used (as previously suggested) are:

JSmooth

and

Launch4j

best of luck!

Eclipse CDT: Symbol 'cout' could not be resolved

I had a similar problem with *std::shared_ptr* with Eclipse using MinGW and gcc 4.8.1. No matter what, Eclipse would not resolve *shared_ptr*. To fix this, I manually added the __cplusplus macro to the C++ symbols and - viola! - Eclipse can find it. Since I specified -std=c++11 as a compile option, I (ahem) assumed that the Eclipse code analyzer would use that option as well. So, to fix this:

  1. Project Context -> C/C++ General -> Paths and Symbols -> Symbols Tab
  2. Select C++ in the Languages panel.
  3. Add symbol __cplusplus with a value of 201103.

The only problem with this is that gcc will complain that the symbol is already defined(!) but the compile will complete as before.

How to throw a C++ exception

Though this question is rather old and has already been answered, I just want to add a note on how to do proper exception handling in C++11:

Use std::nested_exception and std::throw_with_nested

It is described on StackOverflow here and here, how you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions.

Since you can do this with any derived exception class, you can add a lot of information to such a backtrace! You may also take a look at my MWE on GitHub, where a backtrace would look something like this:

Library API: Exception caught in function 'api_function'
Backtrace:
~/Git/mwe-cpp-exception/src/detail/Library.cpp:17 : library_function failed
~/Git/mwe-cpp-exception/src/detail/Library.cpp:13 : could not open file "nonexistent.txt"

Validate that a string is a positive integer

This is almost a duplicate question fo this one:

Validate decimal numbers in JavaScript - IsNumeric()

It's answer is:

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

so, a positive integer would be:

function isPositiveInteger(n) {
  var floatN = parseFloat(n);
  return !isNaN(floatN) && isFinite(n) && floatN > 0
      && floatN % 1 == 0;
}

How to construct a std::string from a std::vector<char>?

With C++11, you can do std::string(v.data()) or, if your vector does not contain a '\0' at the end, std::string(v.data(), v.size()).

How can I completely remove TFS Bindings

In visual studio 2015,

  1. Unbind the solution and project by File->Source Control->Advanced->Change Source Control
  2. Remove the cache in C:\Users\<user>\AppData\Local\Microsoft\Team Foundation\6.0

Interface type check with Typescript

TypeGuards

interface MyInterfaced {
    x: number
}

function isMyInterfaced(arg: any): arg is MyInterfaced {
    return arg.x !== undefined;
}

if (isMyInterfaced(obj)) {
    (obj as MyInterfaced ).x;
}

Error LNK2019: Unresolved External Symbol in Visual Studio

I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

I tried all existing fixes and not working for me

I re-install python 2.7 (will also install pip) by downloading .pkg at https://www.python.org/downloads/mac-osx/

works for me after installation downloaded pkg

Javascript AES encryption

Here's a demonstration page that uses slowAES.

slowAES was easy to use. Logically designed. Reasonable OO packaging. Supports knobs and levers like IV and Encryption mode. Good compatibility with .NET/C#. The name is tongue-in-cheek; it's called "slow AES" because it's not implemented in C++. But in my tests it was not impractically slow.

It lacks an ECB mode. Also lacks a CTR mode, although you could build one pretty easily given an ECB mode, I guess.

It is solely focused on encryption. A nice complementary class that does RFC2898-compliant password-based key derivation, in Javascript, is available from Anandam. This pair of libraries works well with the analogous .NET classes. Good interop. Though, in contrast to SlowAES, the Javascript PBKDF2 is noticeably slower than the Rfc2898DeriveBytes class when generating keys.

It's not surprising that technically there is good interop, but the key point for me was the model adopted by SlowAES is familiar and easy to use. I found some of the other Javascript libraries for AES to be hard to understand and use. For example, in some of them I couldn't find the place to set the IV, or the mode (CBC, ECB, etc). Things were not where I expected them to be. SlowAES was not like that. The properties were right where I expected them to be. It was easy for me to pick up, having been familiar with the Java and .NET crypto programming models.

Anandam's PBKDF2 was not quite on that level. It supported only a single call to DeriveBytes function, so if you need to derive both a key and an IV from a password, this library won't work, unchanged. Some slight modification, and it is working just fine for that purpose.

EDIT: I put together an example of packaging SlowAES and a modified version of Anandam's PBKDF2 into Windows Script Components. Using this AES with a password-derived key shows good interop with the .NET RijndaelManaged class.

EDIT2: the demo page shows how to use this AES encryption from a web page. Using the same inputs (iv, key, mode, etc) supported in .NET gives you good interop with the .NET Rijndael class. You can do a "view source" to get the javascript for that page.

EDIT3
a late addition: Javascript Cryptography considered harmful. Worth the read.

Gradle version 2.2 is required. Current version is 2.10

Based on https://developer.android.com/studio/releases/gradle-plugin.html ...

The following table lists which version of Gradle is required for each version of the Android plugin for Gradle. For the best performance, you should use the latest possible version of both Gradle and the Android plugin.

So, the Plugin version with Required Gradle version should be match.

enter image description here

How do I turn a C# object into a JSON string in .NET?

You can achieve this by using Newtonsoft.json. Install Newtonsoft.json from NuGet. And then:

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);

AngularJS : Difference between the $observe and $watch methods

$observe() is a method on the Attributes object, and as such, it can only be used to observe/watch the value change of a DOM attribute. It is only used/called inside directives. Use $observe when you need to observe/watch a DOM attribute that contains interpolation (i.e., {{}}'s).
E.g., attr1="Name: {{name}}", then in a directive: attrs.$observe('attr1', ...).
(If you try scope.$watch(attrs.attr1, ...) it won't work because of the {{}}s -- you'll get undefined.) Use $watch for everything else.

$watch() is more complicated. It can observe/watch an "expression", where the expression can be either a function or a string. If the expression is a string, it is $parse'd (i.e., evaluated as an Angular expression) into a function. (It is this function that is called every digest cycle.) The string expression can not contain {{}}'s. $watch is a method on the Scope object, so it can be used/called wherever you have access to a scope object, hence in

  • a controller -- any controller -- one created via ng-view, ng-controller, or a directive controller
  • a linking function in a directive, since this has access to a scope as well

Because strings are evaluated as Angular expressions, $watch is often used when you want to observe/watch a model/scope property. E.g., attr1="myModel.some_prop", then in a controller or link function: scope.$watch('myModel.some_prop', ...) or scope.$watch(attrs.attr1, ...) (or scope.$watch(attrs['attr1'], ...)).
(If you try attrs.$observe('attr1') you'll get the string myModel.some_prop, which is probably not what you want.)

As discussed in comments on @PrimosK's answer, all $observes and $watches are checked every digest cycle.

Directives with isolate scopes are more complicated. If the '@' syntax is used, you can $observe or $watch a DOM attribute that contains interpolation (i.e., {{}}'s). (The reason it works with $watch is because the '@' syntax does the interpolation for us, hence $watch sees a string without {{}}'s.) To make it easier to remember which to use when, I suggest using $observe for this case also.

To help test all of this, I wrote a Plunker that defines two directives. One (d1) does not create a new scope, the other (d2) creates an isolate scope. Each directive has the same six attributes. Each attribute is both $observe'd and $watch'ed.

<div d1 attr1="{{prop1}}-test" attr2="prop2" attr3="33" attr4="'a_string'"
        attr5="a_string" attr6="{{1+aNumber}}"></div>

Look at the console log to see the differences between $observe and $watch in the linking function. Then click the link and see which $observes and $watches are triggered by the property changes made by the click handler.

Notice that when the link function runs, any attributes that contain {{}}'s are not evaluated yet (so if you try to examine the attributes, you'll get undefined). The only way to see the interpolated values is to use $observe (or $watch if using an isolate scope with '@'). Therefore, getting the values of these attributes is an asynchronous operation. (And this is why we need the $observe and $watch functions.)

Sometimes you don't need $observe or $watch. E.g., if your attribute contains a number or a boolean (not a string), just evaluate it once: attr1="22", then in, say, your linking function: var count = scope.$eval(attrs.attr1). If it is just a constant string – attr1="my string" – then just use attrs.attr1 in your directive (no need for $eval()).

See also Vojta's google group post about $watch expressions.

XPath to get all child nodes (elements, comments, and text) without parent

From the documentation of XPath ( http://www.w3.org/TR/xpath/#location-paths ):

child::* selects all element children of the context node

child::text() selects all text node children of the context node

child::node() selects all the children of the context node, whatever their node type

So I guess your answer is:

$doc/PRESENTEDIN/X/child::node()

And if you want a flatten array of all nested nodes:

$doc/PRESENTEDIN/X/descendant::node()

Setting dropdownlist selecteditem programmatically

ddlData.SelectedIndex will contain the int value To select the specific value into DropDown :

ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));

return type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value")); is int.

C++11 rvalues and move semantics confusion (return statement)

None of those will do any extra copying. Even if RVO isn't used, the new standard says that move construction is preferred to copy when doing returns I believe.

I do believe that your second example causes undefined behavior though because you're returning a reference to a local variable.

jQuery Ajax requests are getting cancelled without being sent

I had a similar problem. In my case, I'm trying to use a web service on a apache server + django (the service was written by myself). I was having the same output as you: Chrome says it was cancelled while FF does it okay. If I tried to access the service directly on the the browser instead of ajax, it would work as well. Googling around, I found out that some newer versions of apache weren't setting the length of the response correctly in the response headers, so I did this manually. With django, all I had to do was:

response['Content-Length'] = len(content)

If you have control over the service you are trying to access, find out how to modify the response header in the platform you are using, otherwise you'd have to contact the service provider to fix this issue. Apparently, FF and many others browsers are able to handle this situation correctly, but Chrome designers decided to do it as specified.

Swift: print() vs println() vs NSLog()

Moreover, Swift 2 has debugPrint() (and CustomDebugStringConvertible protocol)!

Don't forget about debugPrint() which works like print() but most suitable for debugging.

Examples:

  • Strings
    • print("Hello World!") becomes Hello World
    • debugPrint("Hello World!") becomes "Hello World" (Quotes!)
  • Ranges
    • print(1..<6) becomes 1..<6
    • debugPrint(1..<6) becomes Range(1..<6)

Any class can customize their debug string representation via CustomDebugStringConvertible protocol.

Android- create JSON Array and JSON Object

JSONObject jsonResult = new JSONObject();
try {
  jsonResult.put("clave", "valor");
  jsonResult.put("username", "iesous");
  jsonResult.put("password", "1234");

} catch (JSONException e) {
  // TODO Auto-generated catch block
 e.printStackTrace();
}

Log.d("DEV","jsonResult->"+jsonResult);

What's your most controversial programming opinion?

You need to watch out for Object-Obsessed Programmers.

e.g. if you write a class that models built-in types such as ints or floats, you may be an object-obsessed programmer.

Giving my function access to outside variable

By default, when you are inside a function, you do not have access to the outer variables.


If you want your function to have access to an outer variable, you have to declare it as global, inside the function :

function someFuntion(){
    global $myArr;
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;
}

For more informations, see Variable scope.

But note that using global variables is not a good practice : with this, your function is not independant anymore.


A better idea would be to make your function return the result :

function someFuntion(){
    $myArr = array();       // At first, you have an empty array
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
    return $myArr;
}

And call the function like this :

$result = someFunction();


Your function could also take parameters, and even work on a parameter passed by reference :

function someFuntion(array & $myArr){
    $myVal = //some processing here to determine value of $myVal
    $myArr[] = $myVal;      // Put that $myVal into the array
}

Then, call the function like this :

$myArr = array( ... );
someFunction($myArr);  // The function will receive $myArr, and modify it

With this :

  • Your function received the external array as a parameter
  • And can modify it, as it's passed by reference.
  • And it's better practice than using a global variable : your function is a unit, independant of any external code.


For more informations about that, you should read the Functions section of the PHP manual, and,, especially, the following sub-sections :

Can't Autowire @Repository annotated interface in Spring Boot

@SpringBootApplication(scanBasePackages=,<youur package name>)
@EnableJpaRepositories(<you jpa repo package>)
@EntityScan(<your entity package>)

Entity class like below 
@Entity
@Table(name="USER")
public class User {

    @Id
    @GeneratedValue

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

How to get a microtime in Node.js?

The BigInt data type is supported since Node.js 10.7.0. (see also the blog post announcement). For these supported versions of Node.js, the process.hrtime([time]) method is now regarded as 'legacy', replaced by the process.hrtime.bigint() method.

The bigint version of the process.hrtime() method returning the current high-resolution real time in a bigint.

const start = process.hrtime.bigint();
// 191051479007711n

setTimeout(() => {
  const end = process.hrtime.bigint();
  // 191052633396993n

  console.log(`Benchmark took ${end - start} nanoseconds`);
  // Benchmark took 1154389282 nanoseconds
}, 1000);

tl;dr

  • Node.js 10.7.0+ - Use process.hrtime.bigint()
  • Otherwise - Use process.hrtime()

Windows batch: echo without new line

The simple SET /P method has limitations that vary slightly between Windows versions.

  • Leading quotes may be stripped

  • Leading white space may be stripped

  • Leading = causes a syntax error.

See http://www.dostips.com/forum/viewtopic.php?f=3&t=4209 for more information.

jeb posted a clever solution that solves most of the problems at Output text without linefeed, even with leading space or = I've refined the method so that it can safely print absolutely any valid batch string without the new line, on any version of Windows from XP onward. Note that the :writeInitialize method contains a string literal that may not post well to the site. A remark is included that describes what the character sequence should be.

The :write and :writeVar methods are optimized such that only strings containing troublesome leading characters are written using my modified version of jeb's COPY method. Non-troublesome strings are written using the simpler and faster SET /P method.

@echo off
setlocal disableDelayedExpansion
call :writeInitialize
call :write "=hello"
call :write " world!%$write.sub%OK!"
echo(
setlocal enableDelayedExpansion
set lf=^


set "str= hello!lf!world^!!!$write.sub!hello!lf!world"
echo(
echo str=!str!
echo(
call :write "str="
call :writeVar str
echo(
exit /b

:write  Str
::
:: Write the literal string Str to stdout without a terminating
:: carriage return or line feed. Enclosing quotes are stripped.
::
:: This routine works by calling :writeVar
::
setlocal disableDelayedExpansion
set "str=%~1"
call :writeVar str
exit /b


:writeVar  StrVar
::
:: Writes the value of variable StrVar to stdout without a terminating
:: carriage return or line feed.
::
:: The routine relies on variables defined by :writeInitialize. If the
:: variables are not yet defined, then it calls :writeInitialize to
:: temporarily define them. Performance can be improved by explicitly
:: calling :writeInitialize once before the first call to :writeVar
::
if not defined %~1 exit /b
setlocal enableDelayedExpansion
if not defined $write.sub call :writeInitialize
set $write.special=1
if "!%~1:~0,1!" equ "^!" set "$write.special="
for /f delims^=^ eol^= %%A in ("!%~1:~0,1!") do (
  if "%%A" neq "=" if "!$write.problemChars:%%A=!" equ "!$write.problemChars!" set "$write.special="
)
if not defined $write.special (
  <nul set /p "=!%~1!"
  exit /b
)
>"%$write.temp%_1.txt" (echo !str!!$write.sub!)
copy "%$write.temp%_1.txt" /a "%$write.temp%_2.txt" /b >nul
type "%$write.temp%_2.txt"
del "%$write.temp%_1.txt" "%$write.temp%_2.txt"
set "str2=!str:*%$write.sub%=%$write.sub%!"
if "!str2!" neq "!str!" <nul set /p "=!str2!"
exit /b


:writeInitialize
::
:: Defines 3 variables needed by the :write and :writeVar routines
::
::   $write.temp - specifies a base path for temporary files
::
::   $write.sub  - contains the SUB character, also known as <CTRL-Z> or 0x1A
::
::   $write.problemChars - list of characters that cause problems for SET /P
::      <carriageReturn> <formFeed> <space> <tab> <0xFF> <equal> <quote>
::      Note that <lineFeed> and <equal> also causes problems, but are handled elsewhere
::
set "$write.temp=%temp%\writeTemp%random%"
copy nul "%$write.temp%.txt" /a >nul
for /f "usebackq" %%A in ("%$write.temp%.txt") do set "$write.sub=%%A"
del "%$write.temp%.txt"
for /f %%A in ('copy /z "%~f0" nul') do for /f %%B in ('cls') do (
  set "$write.problemChars=%%A%%B    ""
  REM the characters after %%B above should be <space> <tab> <0xFF>
)
exit /b

How to convert a String to long in javascript?

JavaScript has a Number type which is a 64 bit floating point number*.

If you're looking to convert a string to a number, use

  1. either parseInt or parseFloat. If using parseInt, I'd recommend always passing the radix too.
  2. use the Unary + operator e.g. +"123456"
  3. use the Number constructor e.g. var n = Number("12343")

*there are situations where the number will internally be held as an integer.

What is class="mb-0" in Bootstrap 4?

Bootstrap has predefined classes that we use for styling. If you are familiar with CSS, you'd know what padding, margin and spacing etc. are.

mb-0 = margin-bottom:0;

OK now moving a little further in knowledge, bootstrap has more classes for margin including:

mt- = margin-top
mb- = margin-bottom
ml- = margin-left
mr- = margin-right
my- = it sets margin-left and margin-right at the same time on y axes
mX- = it sets margin-bottom and margin-top at the same time on X axes

This and much more is explained here https://getbootstrap.com/docs/5.0/utilities/spacing/ The best way to learn is through https://getbootstrap.com site itself. It explains a lot obout its built in classes.

SQL Server using wildcard within IN

In Access SQL, I would use this. I'd imagine that SQLserver has the same syntax.

select * from jobdetails where job_no like "0711*" or job_no like "0712*"

Regular expression for first and last name

This is what I use.

This regex accepts only names with minimum characters, from A-Z a-z ,space and -.

Names example:

Ionut Ionete, Ionut-Ionete Cantemir, Ionete Ionut-Cantemirm Ionut-Cantemir Ionete-Second

The limit of name's character is 3. If you want to change this, modify {3,} to {6,}

([a-zA-Z\-]+){3,}\s+([a-zA-Z\-]+){3,}

How do I do redo (i.e. "undo undo") in Vim?

Vim documentation

<Undo>      or                  *undo* *<Undo>* *u*
u           Undo [count] changes.  {Vi: only one level}

                            *:u* *:un* *:undo*
:u[ndo]         Undo one change.  {Vi: only one level}

                            *CTRL-R*
CTRL-R          Redo [count] changes which were undone.  {Vi: redraw screen}

                            *:red* *:redo* *redo*
:red[o]         Redo one change which was undone.  {Vi: no redo}

                            *U*
U           Undo all latest changes on one line.  {Vi: while not
            moved off of it}

Html Agility Pack get all elements by class

You can solve your issue by using the 'contains' function within your Xpath query, as below:

var allElementsWithClassFloat = 
   _doc.DocumentNode.SelectNodes("//*[contains(@class,'float')]")

To reuse this in a function do something similar to the following:

string classToFind = "float";    
var allElementsWithClassFloat = 
   _doc.DocumentNode.SelectNodes(string.Format("//*[contains(@class,'{0}')]", classToFind));

How do I format a String in an email so Outlook will print the line breaks?

Sometimes you have to enter \r\n twice to force outlook to do the break.

This will add one empty line but all the lines will have break.

How do I remove all .pyc files from a project?

Django Extension

Note: This answer is very specific to Django project that have already been using Django Extension.

python manage.py clean_pyc

The implementation can be viewed in its source code.

net::ERR_INSECURE_RESPONSE in Chrome

Maybe you have run into this problem: net::ERR_INSECURE_RESPONSE

You need to check the encryption algorithms supported by your server. For example for apache you can configure the cipher suite this way: cipher suite.

Which version of chrome are you running and what is the server serving your APIs?

Git add all subdirectories

Do,

git add .

while in the root of the repository. It will add everything. If you do git add *, it will only add the files * points to. The single dot refers to the directory.

If your directory or file wasn't added to git index/repo after the above command, remember to check if it's marked as ignored by git in .gitignore file.

Nginx not picking up site in sites-enabled?

I had the same problem. It was because I had accidentally used a relative path with the symbolic link.

Are you sure you used full paths, e.g.:

ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/example.com.conf

How to unzip a file in Powershell?

Use Expand-Archive cmdlet with one of parameter set:

Expand-Archive -LiteralPath C:\source\file.Zip -DestinationPath C:\destination
Expand-Archive -Path file.Zip -DestinationPath C:\destination

Dependent DLL is not getting copied to the build output folder in Visual Studio

VS2019 V16.6.3

For me the problem was somehow the main .proj file ended up with an entry like this for the project whose DLL wasn't getting copied to the parent project bin folder:

<ProjectReference Include="Project B.csproj">
  <Project>{blah blah}</Project>
  <Name>Project B</Name>
  <Private>True</Private>
</ProjectReference>

I manually deleted the line <Private>True</Private> and the DLL was then copied to the main project bin folder on every build of the main project.

If you go to the reference of the problem project in the references folder of the main project, click it and view properties there is a "Copy Local" setting. The private tag equates to this setting, but for me for some reason changing copy local had no effect on the private tag in the .proj file.

Annoyingly I didn't change the copy local value for the reference, no idea how it got set that way and another day wasted tracking down a stupid problem with VS.

Thanks to all the other answers that helped zone me in on the cause.

HTH

Can I limit the length of an array in JavaScript?

The fastest and simplest way is by setting the .length property to the desired length:

arr.length = 4;

This is also the desired way to reset/empty arrays:

arr.length = 0;

Caveat: setting this property can also make the array longer than it is: If its length is 2, running arr.length = 4 will add two undefined items to it. Perhaps add a condition:

if (arr.length > 4) arr.length = 4;

Alternatively:

arr.length = Math.min(arr.length, 4);

Angular2 - Radio Button Binding

Simplest solution and workaround:

<input name="toRent" type="radio" (click)="setToRentControl(false)">
<input name="toRent" type="radio" (click)="setToRentControl(true)">

setToRentControl(value){
    this.vm.toRent.updateValue(value);
    alert(value); //true/false
}

Python read in string from file and split it into values

I would do something like:

filename = "mynumbers.txt"
mynumbers = []
with open(filename) as f:
    for line in f:
        mynumbers.append([int(n) for n in line.strip().split(',')])
for pair in mynumbers:
    try:
        x,y = pair[0],pair[1]
        # Do Something with x and y
    except IndexError:
        print "A line in the file doesn't have enough entries."

The with open is recommended in http://docs.python.org/tutorial/inputoutput.html since it makes sure files are closed correctly even if an exception is raised during the processing.

Single statement across multiple lines in VB.NET without the underscore character

No, you have to use the underscore, but I believe that VB.NET 10 will allow multiple lines w/o the underscore, only requiring if it can't figure out where the end should be.

Angular 4.3 - HttpClient set params

Couple of Easy Alternatives

Without using HttpParams Objects

let body = {
   params : {
    'email' : emailId,
    'password' : password
   }
}

this.http.post(url, body);

Using HttpParams Objects

let body = new HttpParams({
  fromObject : {
    'email' : emailId,
    'password' : password
  }
})

this.http.post(url, body);

Angular.js: set element height on page load

It seems you require the following plugin: https://github.com/yearofmoo/AngularJS-Scope.onReady

It basically gives you the functionality to run your directive code after the your scope or data is loaded i.e. $scope.$whenReady

What is the easiest way to get the current day of the week in Android?

If you want to define the date string in strings.xml. You can do like below.
Calendar.DAY_OF_WEEK return value from 1 -> 7 <=> Calendar.SUNDAY -> Calendar.SATURDAY

strings.xml

<string-array name="title_day_of_week">
    <item>?</item> <!-- sunday -->
    <item>?</item> <!-- monday -->
    <item>?</item>
    <item>?</item>
    <item>?</item>
    <item>?</item>
    <item>?</item> <!-- saturday -->
</string-array>

DateExtension.kt

fun String.getDayOfWeek(context: Context, format: String): String {
    val date = SimpleDateFormat(format, Locale.getDefault()).parse(this)
    return date?.getDayOfWeek(context) ?: "unknown"
}

fun Date.getDayOfWeek(context: Context): String {
    val c = Calendar.getInstance().apply { time = this@getDayOfWeek }
    return context.resources.getStringArray(R.array.title_day_of_week)[c[Calendar.DAY_OF_WEEK] - 1]
}

Using

// get current day
val currentDay = Date().getDayOfWeek(context)

// get specific day
val dayString = "2021-1-4"
val day = dayString.getDayOfWeek(context, "yyyy-MM-dd")

How to check cordova android version of a cordova/phonegap project?

The file platforms/platforms.json lists all of the platform versions.

Input from the keyboard in command line application

Lots of outdated answers to this question. As of Swift 2+ the Swift Standard Library contains the readline() function. It will return an Optional but it will only be nil if EOF has been reached, which will not happen when getting input from the keyboard so it can safely be unwrapped by force in those scenarios. If the user does not enter anything its (unwrapped) value will be an empty string. Here's a small utility function that uses recursion to prompt the user until at least one character has been entered:

func prompt(message: String) -> String {
    print(message)
    let input: String = readLine()!
    if input == "" {
        return prompt(message: message)
    } else {
        return input
    }
}

let input = prompt(message: "Enter something!")
print("You entered \(input)")

Note that using optional binding (if let input = readLine()) to check if something was entered as proposed in other answers will not have the desired effect, as it will never be nil and at least "" when accepting keyboard input.

This will not work in a Playground or any other environment where you does not have access to the command prompt. It seems to have issues in the command-line REPL as well.

Find and replace entire mysql database

I had the same issue on MySQL. I took the procedure from symcbean and adapted her to my needs.

Mine is only replacing textual values (or any type you put in the SELECT FROM information_schema) so if you have date fields, you will not have an error in execution.

Mind the collate in SET @stmt, it must match you database collation.

I used a template request in a variable with multiple replaces but if you have motivation, you could have done it with one CONCAT().

Anyway, if you have serialized data in your database, don't use this. It will not work unless you replace your string with a string with the same lenght.

Hope it helps someone.

DELIMITER $$

DROP PROCEDURE IF EXISTS replace_all_occurences_in_database$$
CREATE PROCEDURE replace_all_occurences_in_database (find_string varchar(255), replace_string varchar(255))
BEGIN
  DECLARE loop_done integer DEFAULT 0;
  DECLARE current_table varchar(255);
  DECLARE current_column varchar(255);
  DECLARE all_columns CURSOR FOR
  SELECT
    t.table_name,
    c.column_name
  FROM information_schema.tables t,
       information_schema.columns c
  WHERE t.table_schema = DATABASE()
  AND c.table_schema = DATABASE()
  AND t.table_name = c.table_name
  AND c.DATA_TYPE IN('varchar', 'text', 'longtext');

  DECLARE CONTINUE HANDLER FOR NOT FOUND
  SET loop_done = 1;

  OPEN all_columns;

table_loop:
LOOP
  FETCH all_columns INTO current_table, current_column;
  IF (loop_done > 0) THEN
    LEAVE table_loop;
  END IF;
  SET @stmt = 'UPDATE `|table|` SET `|column|` = REPLACE(`|column|`, "|find|", "|replace|") WHERE `|column|` LIKE "%|find|%"' COLLATE `utf8mb4_unicode_ci`;
  SET @stmt = REPLACE(@stmt, '|table|', current_table);
  SET @stmt = REPLACE(@stmt, '|column|', current_column);
  SET @stmt = REPLACE(@stmt, '|find|', find_string);
  SET @stmt = REPLACE(@stmt, '|replace|', replace_string);
  PREPARE s1 FROM @stmt;
  EXECUTE s1;
  DEALLOCATE PREPARE s1;
END LOOP;
END
$$

DELIMITER ;

How to sort an STL vector?

this is my approach to solve this generally. It extends the answer from Steve Jessop by removing the requirement to set template arguments explicitly and adding the option to also use functoins and pointers to methods (getters)

#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>

using namespace std;

template <typename T, typename U>
struct CompareByGetter {
    U (T::*getter)() const;
    CompareByGetter(U (T::*getter)() const) : getter(getter) {};
    bool operator()(const T &lhs, const T &rhs) {
        (lhs.*getter)() < (rhs.*getter)();
    }
};

template <typename T, typename U>
CompareByGetter<T,U> by(U (T::*getter)() const) {
    return CompareByGetter<T,U>(getter);
}

//// sort_by
template <typename T, typename U>
struct CompareByMember {
    U T::*field;
    CompareByMember(U T::*f) : field(f) {}
    bool operator()(const T &lhs, const T &rhs) {
        return lhs.*field < rhs.*field;
    }
};

template <typename T, typename U>
CompareByMember<T,U> by(U T::*f) {
    return CompareByMember<T,U>(f);
}

template <typename T, typename U>
struct CompareByFunction {
    function<U(T)> f;
    CompareByFunction(function<U(T)> f) : f(f) {}
    bool operator()(const T& a, const T& b) const {
        return f(a) < f(b);
    }
};

template <typename T, typename U>
CompareByFunction<T,U> by(function<U(T)> f) {
    CompareByFunction<T,U> cmp{f};
    return cmp;
}

struct mystruct {
    double x,y,z;
    string name;
    double length() const {
        return sqrt( x*x + y*y + z*z );
    }
};

ostream& operator<< (ostream& os, const mystruct& ms) {
    return os << "{ " << ms.x << ", " << ms.y << ", " << ms.z << ", " << ms.name << " len: " << ms.length() << "}";
}

template <class T>
ostream& operator<< (ostream& os, std::vector<T> v) {
    os << "[";
    for (auto it = begin(v); it != end(v); ++it) {
        if ( it != begin(v) ) {
            os << " ";
        }
        os << *it;
    }
    os << "]";
    return os;
}

void sorting() {
    vector<mystruct> vec1 = { {1,1,0,"a"}, {0,1,2,"b"}, {-1,-5,0,"c"}, {0,0,0,"d"} };

    function<string(const mystruct&)> f = [](const mystruct& v){return v.name;};

    cout << "unsorted  " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(&mystruct::x) );
    cout << "sort_by x " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(&mystruct::length));
    cout << "sort_by len " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(f) );
    cout << "sort_by name " << vec1 << endl;
}

passing form data to another HTML page

If your situation is as described; You have to send action to a different servelet from a single form and you have two submit buttons and you want to send each submit button to different pages,then your easiest answer is here.

For sending data to two servelets make one button as a submit and the other as button.On first button send action in your form tag as normal, but on the other button call a JavaScript function here you have to submit a form with same field but to different servelets then write another form tag after first close.declare same textboxes there but with hidden attribute.now when you insert data in first form then insert it in another hidden form with some javascript code.Write one function for the second button which submits the second form. Then when you click submit button it will perform the action in first form, if you click on button it will call function to submit second form with its action. Now your second form will be called to second servlet.

Here you can call two serveltes from the same html or jsp page with some mixed code of javascript

An EXAMPLE of second hidden form

_x000D_
_x000D_
<form class="form-horizontal" method="post" action="IPDBILLING" id="MyForm" role="form">_x000D_
    <input type="hidden" class="form-control" name="admno" id="ipdId" value="">_x000D_
</form>_x000D_
<script type="text/javascript">_x000D_
    function Print() {_x000D_
        document.getElementById("MyForm").submit();_x000D_
    }_x000D_
</script>  
_x000D_
_x000D_
_x000D_

Failed to run sdkmanager --list with Java 9

Define home directories of different JDK versions in your .bashrc or .zshrc:

export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_14_HOME=$(/usr/libexec/java_home -v14)

First of all use JDK version 8. Put this line the top of sdkmanager file:

export JAVA_HOME=$JAVA_8_HOME

Switch back to JDK version 14. Put this line the bottom of sdkmanager file:

export JAVA_HOME=$JAVA_14_HOME

Why do I have ORA-00904 even when the column is present?

Check the username credential used to login to the database. (persistence.xml ??). The problem mostly is, the username\password used to login to the database, does not have visiblity to the object (table_name in this case). ( try logging in to sql developer, using the same username\password available in your data source)

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

multipart/form-data

Note. Please consult RFC2388 for additional information about file uploads, including backwards compatibility issues, the relationship between "multipart/form-data" and other content types, performance issues, etc.

Please consult the appendix for information about security issues for forms.

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

The content type "multipart/form-data" follows the rules of all multipart MIME data streams as outlined in RFC2045. The definition of "multipart/form-data" is available at the [IANA] registry.

A "multipart/form-data" message contains a series of parts, each representing a successful control. The parts are sent to the processing agent in the same order the corresponding controls appear in the document stream. Part boundaries should not occur in any of the data; how this is done lies outside the scope of this specification.

As with all multipart MIME types, each part has an optional "Content-Type" header that defaults to "text/plain". User agents should supply the "Content-Type" header, accompanied by a "charset" parameter.

application/x-www-form-urlencoded

This is the default content type. Forms submitted with this content type must be encoded as follows:

Control names and values are escaped. Space characters are replaced by +', and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by%HH', a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A'). The control names/values are listed in the order they appear in the document. The name is separated from the value by=' and name/value pairs are separated from each other by `&'.

application/x-www-form-urlencoded the body of the HTTP message sent to the server is essentially one giant query string -- name/value pairs are separated by the ampersand (&), and names are separated from values by the equals symbol (=). An example of this would be:

MyVariableOne=ValueOne&MyVariableTwo=ValueTwo

The content type "application/x-www-form-urlencoded" is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

Making a request to a RESTful API using python

Using requests:

import requests
url = 'http://ES_search_demo.com/document/record/_search?pretty=true'
data = '''{
  "query": {
    "bool": {
      "must": [
        {
          "text": {
            "record.document": "SOME_JOURNAL"
          }
        },
        {
          "text": {
            "record.articleTitle": "farmers"
          }
        }
      ],
      "must_not": [],
      "should": []
    }
  },
  "from": 0,
  "size": 50,
  "sort": [],
  "facets": {}
}'''
response = requests.post(url, data=data)

Depending on what kind of response your API returns, you will then probably want to look at response.text or response.json() (or possibly inspect response.status_code first). See the quickstart docs here, especially this section.

How to put individual tags for a scatter plot

Perhaps use plt.annotate:

import numpy as np
import matplotlib.pyplot as plt

N = 10
data = np.random.random((N, 4))
labels = ['point{0}'.format(i) for i in range(N)]

plt.subplots_adjust(bottom = 0.1)
plt.scatter(
    data[:, 0], data[:, 1], marker='o', c=data[:, 2], s=data[:, 3] * 1500,
    cmap=plt.get_cmap('Spectral'))

for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label,
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))

plt.show()

enter image description here

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

The SETX command does not modify the current environment.

If you run the following batch file:

setx AAA aaa
echo AAA=%AAA%

It will print

AAA=

So your batch file is wrong. You have to use set:

set AAA=aaa

See What is the difference between SETX and SET in environment variables in Windows.

Adding to the classpath on OSX

To specify a classpath for a single Java process, you can add a classpath option when you run the Java command.

In you command line. Use java -cp "path/to/your/jar:." main rather than just java main

The option tells Java where to search for libraries.

C++ array initialization

Yes, this form of initialization is supported by all C++ compilers. It is a part of C++ language. In fact, it is an idiom that came to C++ from C language. In C language = { 0 } is an idiomatic universal zero-initializer. This is also almost the case in C++.

Since this initalizer is universal, for bool array you don't really need a different "syntax". 0 works as an initializer for bool type as well, so

bool myBoolArray[ARRAY_SIZE] = { 0 };

is guaranteed to initialize the entire array with false. As well as

char* myPtrArray[ARRAY_SIZE] = { 0 };

in guaranteed to initialize the whole array with null-pointers of type char *.

If you believe it improves readability, you can certainly use

bool myBoolArray[ARRAY_SIZE] = { false };
char* myPtrArray[ARRAY_SIZE] = { nullptr };

but the point is that = { 0 } variant gives you exactly the same result.

However, in C++ = { 0 } might not work for all types, like enum types, for example, which cannot be initialized with integral 0. But C++ supports the shorter form

T myArray[ARRAY_SIZE] = {};

i.e. just an empty pair of {}. This will default-initialize an array of any type (assuming the elements allow default initialization), which means that for basic (scalar) types the entire array will be properly zero-initialized.

How do I strip all spaces out of a string in PHP?

If you want to remove all whitespace:

$str = preg_replace('/\s+/', '', $str);

See the 5th example on the preg_replace documentation. (Note I originally copied that here.)

Edit: commenters pointed out, and are correct, that str_replace is better than preg_replace if you really just want to remove the space character. The reason to use preg_replace would be to remove all whitespace (including tabs, etc.).

Accessing items in an collections.OrderedDict by index

Do you have to use an OrderedDict or do you specifically want a map-like type that's ordered in some way with fast positional indexing? If the latter, then consider one of Python's many sorted dict types (which orders key-value pairs based on key sort order). Some implementations also support fast indexing. For example, the sortedcontainers project has a SortedDict type for just this purpose.

>>> from sortedcontainers import SortedDict
>>> sd = SortedDict()
>>> sd['foo'] = 'python'
>>> sd['bar'] = 'spam'
>>> print sd.iloc[0] # Note that 'bar' comes before 'foo' in sort order.
'bar'
>>> # If you want the value, then simple do a key lookup:
>>> print sd[sd.iloc[1]]
'python'

split python source code into multiple files?

Python has importing and namespacing, which are good. In Python you can import into the current namespace, like:

>>> from test import disp
>>> disp('World!')

Or with a namespace:

>>> import test
>>> test.disp('World!')

How to create dynamic href in react render function?

In addition to Felix's answer,

href={`/posts/${posts.id}`}

would work well too. This is nice because it's all in one string.

How to use the ConfigurationManager.AppSettings

\if what you have posted is exactly what you are using then your problem is a bit obvious. Now assuming in your web.config you have you connection string defined like this

 <add name="SiteSqlServer" connectionString="Data Source=(local);Initial Catalog=some_db;User ID=sa;Password=uvx8Pytec" providerName="System.Data.SqlClient" />

In your code you should use the value in the name attribute to refer to the connection string you want (you could actually define several connection strings to different databases), so you would have

 con.ConnectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;

Get image data url in JavaScript?

Note: This only works if the image is from the same domain as the page, or has the crossOrigin="anonymous" attribute and the server supports CORS. It's also not going to give you the original file, but a re-encoded version. If you need the result to be identical to the original, see Kaiido's answer.


You will need to create a canvas element with the correct dimensions and copy the image data with the drawImage function. Then you can use the toDataURL function to get a data: url that has the base-64 encoded image. Note that the image must be fully loaded, or you'll just get back an empty (black, transparent) image.

It would be something like this. I've never written a Greasemonkey script, so you might need to adjust the code to run in that environment.

function getBase64Image(img) {
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);

    // Get the data-URL formatted image
    // Firefox supports PNG and JPEG. You could check img.src to
    // guess the original format, but be aware the using "image/jpg"
    // will re-encode the image.
    var dataURL = canvas.toDataURL("image/png");

    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Getting a JPEG-formatted image doesn't work on older versions (around 3.5) of Firefox, so if you want to support that, you'll need to check the compatibility. If the encoding is not supported, it will default to "image/png".

How to search in an array with preg_match?

$items = array();
foreach ($haystacks as $haystack) {
    if (preg_match($pattern, $haystack, $matches)
        $items[] = $matches[1];
}

ORACLE: Updating multiple columns at once

It's perfectly possible to update multiple columns in the same statement, and in fact your code is doing it. So why does it seem that "INV_TOTAL is not updating, only the inv_discount"?

Because you're updating INV_TOTAL with INV_DISCOUNT, and the database is going to use the existing value of INV_DISCOUNT and not the one you change it to. So I'm afraid what you need to do is this:

UPDATE INVOICE
   SET INV_DISCOUNT = DISC1 * INV_SUBTOTAL
     , INV_TOTAL    = INV_SUBTOTAL - (DISC1 * INV_SUBTOTAL)     
WHERE INV_ID = I_INV_ID;

        

Perhaps that seems a bit clunky to you. It is, but the problem lies in your data model. Storing derivable values in the table, rather than deriving when needed, rarely leads to elegant SQL.

Clear text in EditText when entered

We can clear EditText data in two ways

First One setting EditText is empty like below line

editext.setText("");

Second one clearing EditText data like this

editText.getText().clear();

I suggest second way

How to send a pdf file directly to the printer using JavaScript?

There are two steps you need to take.

First, you need to put the PDF in an iframe.

  <iframe id="pdf" name="pdf" src="document.pdf"></iframe>

To print the iframe you can look at the answers here:

Javascript Print iframe contents only

If you want to print the iframe automatically after the PDF has loaded, you can add an onload handler to the <iframe>:

  <iframe onload="isLoaded()" id="pdf" name="pdf" src="document.pdf"></iframe>

the loader can look like this:

function isLoaded()
{
  var pdfFrame = window.frames["pdf"];
  pdfFrame.focus();
  pdfFrame.print();
}

This will display the browser's print dialog, and then print just the PDF document itself. (I personally use the onload handler to enable a "print" button so the user can decide to print the document, or not).

I'm using this code pretty much verbatim in Safari and Chrome, but am yet to try it on IE or Firefox.

onKeyPress Vs. onKeyUp and onKeyDown

Most of the answers here are focused more on theory than practical matters and there's some big differences between keyup and keypress as it pertains to input field values, at least in Firefox (tested in 43).

If the user types 1 into an empty input element:

  1. The value of the input element will be an empty string (old value) inside the keypress handler

  2. The value of the input element will be 1 (new value) inside the keyup handler.

This is of critical importance if you are doing something that relies on knowing the new value after the input rather than the current value such as inline validation or auto tabbing.

Scenario:

  1. The user types 12345 into an input element.
  2. The user selects the text 12345.
  3. The user types the letter A.

When the keypress event fires after entering the letter A, the text box now contains only the letter A.

But:

  1. Field.val() is 12345.
  2. $Field.val().length is 5
  3. The user selection is an empty string (preventing you from determining what was deleted by overwriting the selection).

So it seems that the browser (Firefox 43) erases the user's selection, then fires the keypress event, then updates the fields contents, then fires keyup.

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

On CentOS Linux, Python3.6, I edited this file (make a backup copy first)

/usr/lib/python3.6/site-packages/certifi/cacert.pem

to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.

disable past dates on datepicker

This will work:

 var dateToday = new Date();    
 $(function () {
     $("#date").datepicker({ 
         minDate: dateToday 
     });
 });

How to add column if not exists on PostgreSQL?

Following select query will return true/false, using EXISTS() function.

EXISTS():
The argument of EXISTS is an arbitrary SELECT statement, or subquery. The subquery is evaluated to determine whether it returns any rows. If it returns at least one row, the result of EXISTS is "true"; if the subquery returns no rows, the result of EXISTS is "false"

SELECT EXISTS(SELECT  column_name 
                FROM  information_schema.columns 
               WHERE  table_schema = 'public' 
                 AND  table_name = 'x' 
                 AND  column_name = 'y'); 

and use the following dynamic SQL statement to alter your table

DO
$$
BEGIN
IF NOT EXISTS (SELECT column_name 
                 FROM  information_schema.columns 
                WHERE  table_schema = 'public' 
                  AND  table_name = 'x' 
                  AND  column_name = 'y') THEN
ALTER TABLE x ADD COLUMN y int DEFAULT NULL;
ELSE
RAISE NOTICE 'Already exists';
END IF;
END
$$

Datepicker: How to popup datepicker when click on edittext

Date Picker Dialog

                Calendar c=Calendar.getInstance();
                Integer month=c.get(Calendar.MONTH);
                Integer day=c.get(Calendar.DAY_OF_MONTH);
                Integer year=c.get(Calendar.YEAR);

                DatePickerDialog datePickerDialog =new DatePickerDialog(Expenture_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        et_from.setText(dayOfMonth+"/"+month+"/"+year);
                    }
                },year,month,day);
                datePickerDialog.show();

How can I take a screenshot/image of a website using Python?

11 years later...
Taking a website screenshot using Python3.6 and Google PageSpeedApi Insights v5:

import base64
import requests
import traceback
import urllib.parse as ul

# It's possible to make requests without the api key, but the number of requests is very limited  

url = "https://duckgo.com"
urle = ul.quote_plus(url)
image_path = "duckgo.jpg"

key = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
strategy = "desktop" # "mobile"
u = f"https://www.googleapis.com/pagespeedonline/v5/runPagespeed?key={key}&strategy={strategy}&url={urle}"

try:
    j = requests.get(u).json()
    ss_encoded = j['lighthouseResult']['audits']['final-screenshot']['details']['data'].replace("data:image/jpeg;base64,", "")
    ss_decoded = base64.b64decode(ss_encoded)
    with open(image_path, 'wb+') as f:
        f.write(ss_decoded) 
except :
    print(traceback.format_exc())
    exit(1)

Notes:

  • Live Demo
  • Pros: Free
  • Conns: Low Resolution
  • Get API Key
  • Docs
  • Limits:
    • Queries per day = 25,000
    • Queries per 100 seconds = 400

What is the format for the PostgreSQL connection string / URL?

server.address=10.20.20.10
server.port=8080
database.user=username
database.password=password
spring.datasource.url=jdbc:postgresql://${server.address}/${server.port}?user=${database.user}&password=${database.password}

How to exit git log or git diff

You can press q to exit.

git hist is using a pager tool so you can scroll up and down the results before returning to the console.

Adding a directory to PATH in Ubuntu

The file .bashrc is read when you start an interactive shell. This is the file that you should update. E.g:

export PATH=$PATH:/opt/ActiveTcl-8.5/bin

Restart the shell for the changes to take effect or source it, i.e.:

source .bashrc

ToList().ForEach in Linq

You shouldn't use ForEach in that way. Read Lippert's “foreach” vs “ForEach”

If you want to be cruel with yourself (and the world), at least don't create useless List

employees.All(p => {
    collection.AddRange(p.Departments);
    p.Departments.All(u => { u.SomeProperty = null; return true; } );
    return true;
});

Note that the result of the All expression is a bool value that we are discarding (we are using it only because it "cycles" all the elements)

I'll repeat. You shouldn't use ForEach to change objects. LINQ should be used in a "functional" way (you can create new objects but you can't change old objects nor you can create side-effects). And what you are writing is creating so many useless List only to gain two lines of code...

How to add an extra language input to Android?

Don't agree with post above. I have a Hero with only English available and I want Spanish.

I installed MoreLocale 2, and it has lots of different languages (Dutch among them). I choose Spanish, Sense UI restarted and EVERYTHING in my phone changed to Spanish: menus, settings, etc. The keyboard predictive text defaulted to Spanish and started suggesting words in Spanish. This means, somewhere within the OS there is a Spanish dictionary hidden and MoreLocale made it available.

The problem is that English is still the only option available in keyboard input language so I can switch to English but can't switch back to Spanish unless I restart Sense UI, which takes a couple of minutes so not a very practical solution.

Still looking for an easier way to do it so please help.

.NET unique object identifier

.NET 4 and later only

Good news, everyone!

The perfect tool for this job is built in .NET 4 and it's called ConditionalWeakTable<TKey, TValue>. This class:

  • can be used to associate arbitrary data with managed object instances much like a dictionary (although it is not a dictionary)
  • does not depend on memory addresses, so is immune to the GC compacting the heap
  • does not keep objects alive just because they have been entered as keys into the table, so it can be used without making every object in your process live forever
  • uses reference equality to determine object identity; moveover, class authors cannot modify this behavior so it can be used consistently on objects of any type
  • can be populated on the fly, so does not require that you inject code inside object constructors

How to set the maxAllowedContentLength to 500MB while running on IIS7?

The limit of requests in .Net can be configured from two properties together:

First

  • Web.Config/system.web/httpRuntime/maxRequestLength
  • Unit of measurement: kilobytes
  • Default value 4096 KB (4 MB)
  • Max. value 2147483647 KB (2 TB)

Second

  • Web.Config/system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength (in bytes)
  • Unit of measurement: bytes
  • Default value 30000000 bytes (28.6 MB)
  • Max. value 4294967295 bytes (4 GB)

References:

Example:

<location path="upl">
   <system.web>
     <!--The default size is 4096 kilobytes (4 MB). MaxValue is 2147483647 KB (2 TB)-->
     <!-- 100 MB in kilobytes -->
     <httpRuntime maxRequestLength="102400" />
   </system.web>
   <system.webServer>
     <security>
       <requestFiltering>          
         <!--The default size is 30000000 bytes (28.6 MB). MaxValue is 4294967295 bytes (4 GB)-->
         <!-- 100 MB in bytes -->
         <requestLimits maxAllowedContentLength="104857600" />
       </requestFiltering>
     </security>
   </system.webServer>
 </location>

jQuery UI Accordion Expand/Collapse All

In the end I found this to be the best solution considering the requirements:

// Expand/Collapse all
$('.accordion-expand-collapse a').click(function() {
    $('.accordion .ui-accordion-header:not(.ui-state-active)').next().slideToggle();
    $(this).text($(this).text() == 'Expand all' ? 'Collapse all' : 'Expand all');
    $(this).toggleClass('collapse');
    return false;
});

Updated JSFiddle Link: http://jsfiddle.net/ccollins1544/r8j105de/4/

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

How to insert data into elasticsearch

To test and try curl requests from Windows, you can make use of Postman client Chrome extension. It is very simple to use and quite powerful.

Or as suggested you can install the cURL util.

A sample curl request is as follows.

curl -X POST -H "Content-Type: application/json" -H "Cache-Control: no-cache" -d '{
"user" : "Arun Thundyill Saseendran",
"post_date" : "2009-03-23T12:30:00",
"message" : "trying out Elasticsearch"
}' "http://10.103.102.56:9200/sampleindex/sampletype/"

I am also getting started with and exploring ES in vast. So please let me know if you have any other doubts.

EDIT: Updated the index name and type name to be fully lowercase to avoid errors and follow convention.

What's the difference between <mvc:annotation-driven /> and <context:annotation-config /> in servlet?

<context:annotation-config> declares support for general annotations such as @Required, @Autowired, @PostConstruct, and so on.

<mvc:annotation-driven /> declares explicit support for annotation-driven MVC controllers (i.e. @RequestMapping, @Controller, although support for those is the default behaviour), as well as adding support for declarative validation via @Valid and message body marshalling with @RequestBody/ResponseBody.

How to change the session timeout in PHP?

If you use PHP's default session handling, the only way to reliably change the session duration in all platforms is to change php.ini. That's because in some platforms, garbage collection is implemented through a script that runs every certain time (a cron script) that reads directly from php.ini, and therefore any attempts at changing it at run time, e.g. via ini_set(), are unreliable and most likely won't work.

For example, in Debian Linux systems, PHP's internal garbage collection is disabled by setting session.gc_probability=0 by default in the configuration, and is instead done via /etc/cron.d/php, which runs at XX:09 and XX:39 (that is, every half hour). This cron job looks for sessions older than the session.gc_maxlifetime specified in the configuration, and if any are found, they are deleted. As a consequence, in these systems ini_set('session.gc_maxlifetime', ...) is ignored. That also explains why in this question: PHP sessions timing out too quickly, the OP had problems in one host but the problems ceased when switching to a different host.

So, given that you don't have access to php.ini, if you want to do it portably, using the default session handling is not an option. Apparently, extending the cookie lifetime was enough for your host, but if you want a solution that works reliably even if you switch hosts, you have to use a different alternative.

Available alternative methods include:

  1. Set a different session (save) handler in PHP to save your sessions in a different directory or in a database, as specified in PHP: Custom Session Handlers (PHP manual), so that the cron job doesn't reach it, and only PHP's internal garbage collection takes place. This option probably can make use of ini_set() to set session.gc_maxlifetime but I prefer to just ignore the maxlifetime parameter in my gc() callback and determine maximum lifetime on my own.

  2. Completely forget about PHP internal session handling and implement your own session management. This method has two main disadvantages: you will need your own global session variables, so you lose the advantage of the $_SESSION superglobal, and it needs more code thus there are more opportunities for bugs and security flaws. Most importantly, the session identifier should be generated out of cryptographically secure random or pseudorandom numbers to avoid session ID predictability (leading to possible session hijacking), and that is not so easy to do with PHP portably. The main advantage is that it will work consistently in all platforms and you have full control over the code. That's the approach taken e.g. by the phpBB forum software (at least version 1; I'm not sure about more recent versions).

There is an example of (1) in the documentation for session_set_save_handler(). The example is long but I'll reproduce it here, with the relevant modifications necessary to extend the session duration. Note the inclusion of session_set_cookie_params() to increase the cookie lifetime as well.

<?php
class FileSessionHandler
{

    private $savePath;
    private $lifetime;

    function open($savePath, $sessionName)
    {
        $this->savePath = 'my_savepath'; // Ignore savepath and use our own to keep it safe from automatic GC
        $this->lifetime = 3600; // 1 hour minimum session duration
        if (!is_dir($this->savePath)) {
            mkdir($this->savePath, 0777);
        }

        return true;
    }

    function close()
    {
        return true;
    }

    function read($id)
    {
        return (string)@file_get_contents("$this->savePath/sess_$id");
    }

    function write($id, $data)
    {
        return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;
    }

    function destroy($id)
    {
        $file = "$this->savePath/sess_$id";
        if (file_exists($file)) {
            unlink($file);
        }

        return true;
    }

    function gc($maxlifetime)
    {
        foreach (glob("$this->savePath/sess_*") as $file) {
            if (filemtime($file) + $this->lifetime < time() && file_exists($file)) { // Use our own lifetime
                unlink($file);
            }
        }

        return true;
    }
}

$handler = new FileSessionHandler();
session_set_save_handler(
    array($handler, 'open'),
    array($handler, 'close'),
    array($handler, 'read'),
    array($handler, 'write'),
    array($handler, 'destroy'),
    array($handler, 'gc')
    );

// the following prevents unexpected effects when using objects as save handlers
register_shutdown_function('session_write_close');

session_set_cookie_params(3600); // Set session cookie duration to 1 hour
session_start();
// proceed to set and retrieve values by key from $_SESSION

Approach (2) is more complicated; basically, you have to re-implement all session functions on your own. I won't go into details here.

surface plots in matplotlib

For surfaces it's a bit different than a list of 3-tuples, you should pass in a grid for the domain in 2d arrays.

If all you have is a list of 3d points, rather than some function f(x, y) -> z, then you will have a problem because there are multiple ways to triangulate that 3d point cloud into a surface.

Here's a smooth surface example:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D  
# Axes3D import has side effects, it enables using projection='3d' in add_subplot
import matplotlib.pyplot as plt
import random

def fun(x, y):
    return x**2 + y

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-3.0, 3.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array(fun(np.ravel(X), np.ravel(Y)))
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

plt.show()

3d

Remove element by id

You could make a remove function so that you wouldn't have to think about it every time:

function removeElement(id) {
    var elem = document.getElementById(id);
    return elem.parentNode.removeChild(elem);
}

How to break/exit from a each() function in JQuery?

Return false from the anonymous function:

$(xml).find("strengths").each(function() {
  // Code
  // To escape from this block based on a condition:
  if (something) return false;
});

From the documentation of the each method:

Returning 'false' from within the each function completely stops the loop through all of the elements (this is like using a 'break' with a normal loop). Returning 'true' from within the loop skips to the next iteration (this is like using a 'continue' with a normal loop).

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

How to use ternary operator in razor (specifically on HTML attributes)?

You should be able to use the @() expression syntax:

<a class="@(User.Identity.IsAuthenticated ? "auth" : "anon")">My link here</a>

Table column sizing

Another option is to apply flex styling at the table row, and add the col-classes to the table header / table data elements:

<table>
  <thead>
    <tr class="d-flex">
      <th class="col-3">3 columns wide header</th>
      <th class="col-sm-5">5 columns wide header</th>
      <th class="col-sm-4">4 columns wide header</th>
    </tr>
  </thead>
  <tbody>
    <tr class="d-flex">
      <td class="col-3">3 columns wide content</th>
      <td class="col-sm-5">5 columns wide content</th>
      <td class="col-sm-4">4 columns wide content</th>
    </tr>
  </tbody>
</table>

Get name of object or class

Try this:

var classname = ("" + obj.constructor).split("function ")[1].split("(")[0];

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.

How to rename a directory/folder on GitHub website?

You could use a workflow for this.

# ./.github/workflows/rename.yaml
name: Rename Directory

on:
  push:

jobs:
  rename:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - run: git mv old_name new_name
      - uses: EndBug/[email protected]

Then just delete the workflow file, which you can do in the UI