Programs & Examples On #Sqlprofileprovider

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

Most of the answers provided here address the number of incoming requests to your backend webservice, not the number of outgoing requests you can make from your ASP.net application to your backend service.

It's not your backend webservice that is throttling your request rate here, it is the number of open connections your calling application is willing to establish to the same endpoint (same URL).

You can remove this limitation by adding the following configuration section to your machine.config file:

<configuration>
  <system.net>
    <connectionManagement>
      <add address="*" maxconnection="65535"/>
    </connectionManagement>
  </system.net>
</configuration>

You could of course pick a more reasonable number if you'd like such as 50 or 100 concurrent connections. But the above will open it right up to max. You can also specify a specific address for the open limit rule above rather than the '*' which indicates all addresses.

MSDN Documentation for System.Net.connectionManagement

Another Great Resource for understanding ConnectManagement in .NET

Hope this solves your problem!

EDIT: Oops, I do see you have the connection management mentioned in your code above. I will leave my above info as it is relevant for future enquirers with the same problem. However, please note there are currently 4 different machine.config files on most up to date servers!

There is .NET Framework v2 running under both 32-bit and 64-bit as well as .NET Framework v4 also running under both 32-bit and 64-bit. Depending on your chosen settings for your application pool you could be using any one of these 4 different machine.config files! Please check all 4 machine.config files typically located here:

  • C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG
  • C:\Windows\Microsoft.NET\Framework64\v2.0.50727\CONFIG
  • C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config
  • C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Config

The 'packages' element is not declared

You can also find a copy of the nuspec.xsd here as it seems to no longer be available:

https://gist.github.com/sharwell/6131243

Web.Config Debug/Release

If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

<connectionStrings xdt:Transform="Replace">
    <!-- production environment config --->
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>
....

Information for this answer are brought from this answer and this blog post.

notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).

Calculate business days

The add_business_days has a small bug. Try the following with the existing function and the output will be a Saturday.

Startdate = Friday Business days to add = 1 Holidays array = Add date for the following Monday.

I have fixed that in my function below.

function add_business_days($startdate, $buisnessdays, $holidays = array(), $dateformat = 'Y-m-d'){
$i= 1;
$dayx= strtotime($startdate);
$buisnessdays= ceil($buisnessdays);

while($i < $buisnessdays)
{
    $day= date('N',$dayx);

    $date= date('Y-m-d',$dayx);
    if($day < 6 && !in_array($date,$holidays))
        $i++;

    $dayx= strtotime($date.' +1 day');
}

## If the calculated day falls on a weekend or is a holiday, then add days to the next business day
$day= date('N',$dayx);
$date= date('Y-m-d',$dayx);

while($day >= 6 || in_array($date,$holidays))
{
    $dayx= strtotime($date.' +1 day');
    $day= date('N',$dayx);
    $date= date('Y-m-d',$dayx);
}

return date($dateformat, $dayx);}

Get and Set Screen Resolution

This code will work perfectly in WPF. You can use it in either page load or in button click.

      string screenWidth =System.Windows.SystemParameters.PrimaryScreenWidth.ToString();

      string screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight.ToString();

      txtResolution.Text ="Resolution : "+screenWidth + " X " + screenHeight;

Marker content (infoWindow) Google Maps

Although this question has already been answered, I think this approach is better : http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:

Each marker gets an "infowindow" entry :

function createMarker(lat, lon, html) {
    var newmarker = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lon),
        map: map,
        title: html
    });

    newmarker['infowindow'] = new google.maps.InfoWindow({
            content: html
        });

    google.maps.event.addListener(newmarker, 'mouseover', function() {
        this['infowindow'].open(map, this);
    });
}

XAMPP Apache Webserver localhost not working on MAC OS

I had success with easy killing all active httpd processes in Monitor Activity tool:

1) close XAMPP control

2) open Monitor Activity

3) select filter for All processes (default is My processes)

4) in fulltext search type: httpd

5) kill all showen items

6) relaunch XAMPP control and launch apache again

System.IO.IOException: file used by another process

Are you running a real-time antivirus scanner by any chance ? If so, you could try (temporarily) disabling it to see if that is what is accessing the file you are trying to delete. (Chris' suggestion to use Sysinternals process explorer is a good one).

Under what conditions is a JSESSIONID created?

CORRECTION: Please vote for Peter Štibraný's answer - it is more correct and complete!

A "JSESSIONID" is the unique id of the http session - see the javadoc here. There, you'll find the following sentence

Session information is scoped only to the current web application (ServletContext), so information stored in one context will not be directly visible in another.

So when you first hit a site, a new session is created and bound to the SevletContext. If you deploy multiple applications, the session is not shared.

You can also invalidate the current session and therefore create a new one. e.g. when switching from http to https (after login), it is a very good idea, to create a new session.

Hope, this answers your question.

Nested or Inner Class in PHP

As per Xenon's comment to Anil Özselgin's answer, anonymous classes have been implemented in PHP 7.0, which is as close to nested classes as you'll get right now. Here are the relevant RFCs:

Nested Classes (status: withdrawn)

Anonymous Classes (status: implemented in PHP 7.0)

An example to the original post, this is what your code would look like:

<?php
    public class User {
        public $userid;
        public $username;
        private $password;

        public $profile;
        public $history;

        public function __construct() {
            $this->profile = new class {
                // Some code here for user profile
            }

            $this->history = new class {
                // Some code here for user history
            }
        }
    }
?>

This, though, comes with a very nasty caveat. If you use an IDE such as PHPStorm or NetBeans, and then add a method like this to the User class:

public function foo() {
  $this->profile->...
}

...bye bye auto-completion. This is the case even if you code to interfaces (the I in SOLID), using a pattern like this:

<?php
    public class User {
        public $profile;

        public function __construct() {
            $this->profile = new class implements UserProfileInterface {
                // Some code here for user profile
            }
        }
    }
?>

Unless your only calls to $this->profile are from the __construct() method (or whatever method $this->profile is defined in) then you won't get any sort of type hinting. Your property is essentially "hidden" to your IDE, making life very hard if you rely on your IDE for auto-completion, code smell sniffing, and refactoring.

How do I find out which computer is the domain controller in Windows programmatically?

In C#/.NET 3.5 you could write a little program to do:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    string controller = context.ConnectedServer;
    Console.WriteLine( "Domain Controller:" + controller );
} 

This will list all the users in the current domain:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    using (UserPrincipal searchPrincipal = new UserPrincipal(context))
    {
       using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
       {
           foreach (UserPrincipal principal in searcher.FindAll())
           {
               Console.WriteLine( principal.SamAccountName);
           }
       }
    }
}

How to find NSDocumentDirectory in Swift?

Usually i prefer like below in swift 3, because i can add file name and create a file easily

let fileManager = FileManager.default
if let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first {
    let databasePath = documentsURL.appendingPathComponent("db.sqlite3").path
    print("directory path:", documentsURL.path)
    print("database path:", databasePath)
    if !fileManager.fileExists(atPath: databasePath) {
        fileManager.createFile(atPath: databasePath, contents: nil, attributes: nil)
    }
}

SQL grouping by all the columns

If you are using SqlServer the distinct keyword should work for you. (Not sure about other databases)

declare @t table (a int , b int)

insert into @t (a,b) select 1, 1
insert into @t (a,b) select 1, 2
insert into @t (a,b) select 1, 1

select distinct * from @t

results in

a b
1 1
1 2

Django request.GET

since your form has a field called 'q', leaving it blank still sends an empty string.

try

if 'q' in request.GET and request.GET['q'] != "" :
     message
else
     error message

How to check for a valid URL in Java?

The most "foolproof" way is to check for the availability of URL:

public boolean isURL(String url) {
  try {
     (new java.net.URL(url)).openStream().close();
     return true;
  } catch (Exception ex) { }
  return false;
}

tsc is not recognized as internal or external command

The problem is that tsc is not in your PATH if installed locally.

You should modify your .vscode/tasks.json to include full path to tsc.

The line to change is probably equal to "command": "tsc".

You should change it to "command": "node" and add the following to your args: "args": ["${workspaceRoot}\\node_modules\\typescript\\bin\\tsc"] (on Windows).

This will instruct VSCode to:

  1. Run NodeJS (it should be installed globally).
  2. Pass your local Typescript installation as the script to run.

(that's pretty much what tsc executable does)

Are you sure you don't want to install Typescript globally? It should make things easier, especially if you're just starting to use it.

asp.net: Invalid postback or callback argument

My problem was that i had nested form tags. After removing the inner one, worked out for me.

TypeError: 'list' object is not callable in python

to solve the error like this one: "list object is not callable in python" even you are changing the variable name then please restart the kernel in Python Jutyter Notebook if you are using it or simply restart the IDE.

I hope this will work. Thank you!!!

Filezilla FTP Server Fails to Retrieve Directory Listing

I had Filezilla 3.6, and had the same issue as OP. I have upgraded to 3.10.3 thinking it would fix it. Nope, still the same.

Then I did a bit digging around the options, and what worked for me is:

Edit -> Settings -> FTP -> Passive Mode and switched from "Fall back to active mode" to "Use the server's external IP address instead"

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

I had the same problem. I enabled vtx in bios and it didn't worked. After a doublecheck in the bios I recogniced that the bios said that you have to poweroff (and realy power off) the computer. After that it worked. Heavy Pitfall :)

How to find the width of a div using vanilla JavaScript?

The correct way of getting computed style is waiting till page is rendered. It can be done in the following manner. Pay attention to timeout on getting auto values.

function getStyleInfo() {
    setTimeout(function() {
        const style = window.getComputedStyle(document.getElementById('__root__'));
        if (style.height == 'auto') {
            getStyleInfo();
        }
        // IF we got here we can do actual business logic staff
        console.log(style.height, style.width);
    }, 100);
};

window.onload=function() { getStyleInfo(); };

If you use just

window.onload=function() {
    var computedStyle = window.getComputedStyle(document.getElementById('__root__'));
}

you can get auto values for width and height because browsers does not render till full load is performed.

How large should my recv buffer be when calling recv in the socket library

16kb is about right; if you're using gigabit ethernet, each packet could be 9kb in size.

Render Content Dynamically from an array map function in React Native

Don't forget to return the mapped array , like:

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })

}

Reference for the map() method: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Can I edit an iPad's host file?

I needed the same functionality, and doing jailbreak is no-no. One solution is to host yourself DNS server (MaraDNS), go to your wifi settings in ipad/phone, and add your custom DNS server there.

The whole process took me only 10 minutes, and it works!

1) Download MaraDNS

2) Run mkSecretTxt.exe as administrator

3) Modify mararc file, mine is:

ipv4_bind_addresses = "put your public IP Here"
timestamp_type = 2
random_seed_file = "secret.txt"

csv2 = {}
csv2["Simple.Example.com."] = "example.configuration"

Add file called "example.configuration" into the same folder where run_maradns.bat is.

4) Edit your example.configuration file:

Simple.Example.com. 10.10.13.13 ~

5) Disable all Firewalls (convenience)

6) Run file "run_maradns.bat"

7) There should be no errors.

8) Add your DNS server to list, as shown here: http://www.iphonehacks.com/2014/08/change-dns-iphone-ipad.html

9) Works!

Number of visitors on a specific page

As Blexy already answered, go to "Behavior > Site Content > All Pages".

Just pay attention that "Behavior" appears two times in the left sidebar and we need to click on the second option:

                                                     sidebar

Jquery button click() function is not working

After making the id unique across the document ,You have to use event delegation

$("#container").on("click", "buttonid", function () {
  alert("Hi");
});

How to use the PI constant in C++

Rather than writing

#define _USE_MATH_DEFINES

I would recommend using -D_USE_MATH_DEFINES or /D_USE_MATH_DEFINES depending on your compiler.

This way you are assured that even in the event of someone including the header before you do (and without the #define) you will still have the constants instead of an obscure compiler error that you will take ages to track down.

How to take keyboard input in JavaScript?

If you are doing this in a browser, you can capture keyboard events.

  • keydown
  • keypress
  • keyup

Can all be listened to on HTML nodes in most browsers.

Webkit also supports...

  • textInput

See for more details .. http://unixpapa.com/js/key.html

Key existence check in HashMap

Better way is to use containsKey method of HashMap. Tomorrow somebody will add null to the Map. You should differentiate between key presence and key has null value.

python filter list of dictionaries based on key value

You can try a list comp

>>> exampleSet = [{'type':'type1'},{'type':'type2'},{'type':'type2'}, {'type':'type3'}]
>>> keyValList = ['type2','type3']
>>> expectedResult = [d for d in exampleSet if d['type'] in keyValList]
>>> expectedResult
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Another way is by using filter

>>> list(filter(lambda d: d['type'] in keyValList, exampleSet))
[{'type': 'type2'}, {'type': 'type2'}, {'type': 'type3'}]

Convert String to Date in MS Access Query

Basically, this will not work out

Format("20130423014854","yyyy-MM-dd hh:mm:ss")

the format function will only work if your string has correct format

Format (#17/04/2004#, "yyyy/mm/dd")

And you need to specify, what datatype of field [Date] is, because I can't put this value 2013-04-23 13:48:54.0 under a General Date field (I use MS access2007). You might want to view this topic: select date in between

socket.shutdown vs socket.close

Here's one explanation:

Once a socket is no longer required, the calling program can discard the socket by applying a close subroutine to the socket descriptor. If a reliable delivery socket has data associated with it when a close takes place, the system continues to attempt data transfer. However, if the data is still undelivered, the system discards the data. Should the application program have no use for any pending data, it can use the shutdown subroutine on the socket prior to closing it.

Cause of a process being a deadlock victim

Q1:Could the time it takes for a transaction to execute make the associated process more likely to be flagged as a deadlock victim.

No. The SELECT is the victim because it had only read data, therefore the transaction has a lower cost associated with it so is chosen as the victim:

By default, the Database Engine chooses as the deadlock victim the session running the transaction that is least expensive to roll back. Alternatively, a user can specify the priority of sessions in a deadlock situation using the SET DEADLOCK_PRIORITY statement. DEADLOCK_PRIORITY can be set to LOW, NORMAL, or HIGH, or alternatively can be set to any integer value in the range (-10 to 10).

Q2. If I execute the select with a NOLOCK hint, will this remove the problem?

No. For several reasons:

Q3. I suspect that a datetime field that is checked as part of the WHERE clause in the select statement is causing the slow lookup time. Can I create an index based on this field? Is it advisable?

Probably. The cause of the deadlock is almost very likely to be a poorly indexed database.10 minutes queries are acceptable in such narrow conditions, that I'm 100% certain in your case is not acceptable.

With 99% confidence I declare that your deadlock is cased by a large table scan conflicting with updates. Start by capturing the deadlock graph to analyze the cause. You will very likely have to optimize the schema of your database. Before you do any modification, read this topic Designing Indexes and the sub-articles.

Regex: Check if string contains at least one digit

you could use look-ahead assertion for this:

^(?=.*\d).+$

how to enable sqlite3 for php?

try this:

sudo apt-get --purge remove php5*
sudo apt-get install php5 php5-sqlite php5-mysql
sudo apt-get install php-pear php-apc php5-curl
sudo apt-get autoremove
sudo apt-get install php5-sqlite
sudo apt-get install libapache2-mod-fastcgi php5-fpm php5

How to secure database passwords in PHP?

An additional trick is to use a PHP separate configuration file that looks like that :

<?php exit() ?>

[...]

Plain text data including password

This does not prevent you from setting access rules properly. But in the case your web site is hacked, a "require" or an "include" will just exit the script at the first line so it's even harder to get the data.

Nevertheless, do not ever let configuration files in a directory that can be accessed through the web. You should have a "Web" folder containing your controler code, css, pictures and js. That's all. Anything else goes in offline folders.

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

In your giant elif chain, you skipped 13. You might want to throw an error if you hit the end of the chain without returning anything, to catch numbers you missed and incorrect calls of the function:

...
elif x == 90:
    return 6
else:
    raise ValueError(x)

Git: How to pull a single file from a server repository in Git?

https://raw.githubusercontent.com/[USER-NAME]/[REPOSITORY-NAME]/[BRANCH-NAME]/[FILE-PATH]

Ex. https://raw.githubusercontent.com/vipinbihari/apana-result/master/index.php

Through this you would get the contents of an individual file as a row text. You can download that text with wget.

Ex. https://raw.githubusercontent.com/vipinbihari/apana-result/master/index.php

BeautifulSoup: extract text from anchor tag

This will help:

from bs4 import BeautifulSoup

data = '''<div class="image">
        <a href="http://www.example.com/eg1">Content1<img  
        src="http://image.example.com/img1.jpg" /></a>
        </div>
        <div class="image">
        <a href="http://www.example.com/eg2">Content2<img  
        src="http://image.example.com/img2.jpg" /> </a>
        </div>'''

soup = BeautifulSoup(data)

for div in soup.findAll('div', attrs={'class':'image'}):
    print(div.find('a')['href'])
    print(div.find('a').contents[0])
    print(div.find('img')['src'])

If you are looking into Amazon products then you should be using the official API. There is at least one Python package that will ease your scraping issues and keep your activity within the terms of use.

Tokenizing strings in C

When reading the strtok documentation, I see you need to pass in a NULL pointer after the first "initializing" call. Maybe you didn't do that. Just a guess of course.

How to set the thumbnail image on HTML5 video?

Add poster="placeholder.png" to the video tag.

<video width="470" height="255" poster="placeholder.png" controls>
    <source src="video.mp4" type="video/mp4">
    <source src="video.ogg" type="video/ogg">
    <source src="video.webm" type="video/webm">
    <object data="video.mp4" width="470" height="255">
    <embed src="video.swf" width="470" height="255">
    </object>
</video>

Does that work?

Correct way to use StringBuilder in SQL

When you already have all the "pieces" you wish to append, there is no point in using StringBuilder at all. Using StringBuilder and string concatenation in the same call as per your sample code is even worse.

This would be better:

return "select id1, " + " id2 " + " from " + " table";

In this case, the string concatenation is actually happening at compile-time anyway, so it's equivalent to the even-simpler:

return "select id1, id2 from table";

Using new StringBuilder().append("select id1, ").append(" id2 ")....toString() will actually hinder performance in this case, because it forces the concatenation to be performed at execution time, instead of at compile time. Oops.

If the real code is building a SQL query by including values in the query, then that's another separate issue, which is that you should be using parameterized queries, specifying the values in the parameters rather than in the SQL.

I have an article on String / StringBuffer which I wrote a while ago - before StringBuilder came along. The principles apply to StringBuilder in the same way though.

How can I get a precise time, for example in milliseconds in Objective-C?

NSDate and the timeIntervalSince* methods will return a NSTimeInterval which is a double with sub-millisecond accuracy. NSTimeInterval is in seconds, but it uses the double to give you greater precision.

In order to calculate millisecond time accuracy, you can do:

// Get a current time for where you want to start measuring from
NSDate *date = [NSDate date];

// do work...

// Find elapsed time and convert to milliseconds
// Use (-) modifier to conversion since receiver is earlier than now
double timePassed_ms = [date timeIntervalSinceNow] * -1000.0;

Documentation on timeIntervalSinceNow.

There are many other ways to calculate this interval using NSDate, and I would recommend looking at the class documentation for NSDate which is found in NSDate Class Reference.

Java and SSL - java.security.NoSuchAlgorithmException

Try javax.net.ssl.keyStorePassword instead of javax.net.ssl.keyPassword: the latter isn't mentioned in the JSSE ref guide.

The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmExceptions are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.

You could also use -Djavax.net.debug=ssl, or at least -Djavax.net.debug=ssl,keymanager, to get more debugging information, if the information in the stack trace isn't sufficient.

Syntax error near unexpected token 'fi'

Use Notepad ++ and use the option to Convert the file to UNIX format. That should solve this problem.

IIS7 Settings File Locations

It sounds like you're looking for applicationHost.config, which is located in C:\Windows\System32\inetsrv\config.

Yes, it's an XML file, and yes, editing the file by hand will affect the IIS config after a restart. You can think of IIS Manager as a GUI front-end for editing applicationHost.config and web.config.

ImportError: No module named PyQt4

I solved the same problem for my own program by installing python3-pyqt4.

I'm not using Python 3 but it still helped.

jquery count li elements inside ul -> length?

If you have a dom object of the ul, use the following.

$('#my_ul').children().length;

A simple example

_x000D_
_x000D_
window.setInterval(function() {_x000D_
  let ul = $('#ul');                 // Get the ul_x000D_
  let length = ul.children().length; // Count of the child nodes._x000D_
_x000D_
  // The show!_x000D_
  ul.append('<li>Item ' + (length + 1) + '</li>');_x000D_
  if (5 <= length) {_x000D_
    ul.empty();_x000D_
    length = -1;_x000D_
  }_x000D_
  $('#ul_length').text(length + 1);_x000D_
}, 1000);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<h4>Count of the child nodes: <span id='ul_length'>0</span></h4>_x000D_
<ul id="ul"></ul>
_x000D_
_x000D_
_x000D_

Django: OperationalError No Such Table

If anyone finds that any of the suggested:

python manage.py makemigrations

python manage.py migrate

python manage.py migrate --run-syncdb

fail, you may need to add a folder named "migrations" inside the app directory, and create an empty __init__.py file.

Automating the InvokeRequired code pattern

I Kind of like to do it a bit different, i like to call "myself" if needed with an Action,

    private void AddRowToListView(ScannerRow row, bool suspend)
    {
        if (IsFormClosing)
            return;

        if (this.InvokeRequired)
        {
            var A = new Action(() => AddRowToListView(row, suspend));
            this.Invoke(A);
            return;
        }
         //as of here the Code is thread-safe

this is a handy pattern, the IsFormClosing is a field that i set to True when I am closing my form as there might be some background threads that are still running...

Maven: How to run a .java file from command line passing arguments

Adding a shell script e.g. run.sh makes it much more easier:

#!/usr/bin/env bash
export JAVA_PROGRAM_ARGS=`echo "$@"`
mvn exec:java -Dexec.mainClass="test.Main" -Dexec.args="$JAVA_PROGRAM_ARGS"

Then you are able to execute:

./run.sh arg1 arg2 arg3

How do I test a website using XAMPP?

The webpages on an online server reside in a location which looks somewhat like this: http://www.somerandomsite.com/index.php

Since xampp is Offline, it sets up a local server whose address is like this http://localhost/

Basically, xampp sets up a server (apache and others) in your system. And all the files such as index.php, somethingelse.php, etc., reside in the xampp\htdocs\ folder.

The browser locates the server in localhost and will search through the above folder for any resources available in there.

So create any number of folders inside the "xampp\htdocs\" each folder thus forming a website (as you build it).

Sometimes apache won't even start. This is due to the clashing of ports with some applications. Some of them I commonly encounter is Skype. See to that it is killed completely and restart apache

Determine if 2 lists have the same elements, regardless of order?

Determine if 2 lists have the same elements, regardless of order?

Inferring from your example:

x = ['a', 'b']
y = ['b', 'a']

that the elements of the lists won't be repeated (they are unique) as well as hashable (which strings and other certain immutable python objects are), the most direct and computationally efficient answer uses Python's builtin sets, (which are semantically like mathematical sets you may have learned about in school).

set(x) == set(y) # prefer this if elements are hashable

In the case that the elements are hashable, but non-unique, the collections.Counter also works semantically as a multiset, but it is far slower:

from collections import Counter
Counter(x) == Counter(y)

Prefer to use sorted:

sorted(x) == sorted(y) 

if the elements are orderable. This would account for non-unique or non-hashable circumstances, but this could be much slower than using sets.

Empirical Experiment

An empirical experiment concludes that one should prefer set, then sorted. Only opt for Counter if you need other things like counts or further usage as a multiset.

First setup:

import timeit
import random
from collections import Counter

data = [str(random.randint(0, 100000)) for i in xrange(100)]
data2 = data[:]     # copy the list into a new one

def sets_equal(): 
    return set(data) == set(data2)

def counters_equal(): 
    return Counter(data) == Counter(data2)

def sorted_lists_equal(): 
    return sorted(data) == sorted(data2)

And testing:

>>> min(timeit.repeat(sets_equal))
13.976069927215576
>>> min(timeit.repeat(counters_equal))
73.17287588119507
>>> min(timeit.repeat(sorted_lists_equal))
36.177085876464844

So we see that comparing sets is the fastest solution, and comparing sorted lists is second fastest.

stdcall and cdecl

I want to improve on @adf88's answer. I feel that pseudocode for the STDCALL does not reflect the way of how it happens in reality. 'a', 'b', and 'c' aren't popped from the stack in the function body. Instead they are popped by the ret instruction (ret 12 would be used in this case) that in one swoop jumps back to the caller and at the same time pops 'a', 'b', and 'c' from the stack.

Here is my version corrected according to my understanding:

STDCALL:

/* 1. calling STDCALL in pseudo-assembler (similar to what the compiler outputs) */
push on the stack a copy of 'z', then copy of 'y', then copy of 'x'
call
move contents of register A to 'i' variable

/* 2. STDCALL 'Function' body in pseaudo-assembler */ copy 'a' (from stack) to register A copy 'b' (from stack) to register B add A and B, store result in A copy 'c' (from stack) to register B add A and B, store result in A jump back to caller code and at the same time pop 'a', 'b' and 'c' off the stack (a, b and c are removed from the stack in this step, result in register A)

How do you check if a JavaScript Object is a DOM Object?

I think that what you have to do is make a thorough check of some properties that will always be in a dom element, but their combination won't most likely be in another object, like so:

var isDom = function (inp) {
    return inp && inp.tagName && inp.nodeName && inp.ownerDocument && inp.removeAttribute;
};

iOS 7 UIBarButton back button arrow color

You have to set the tintColor of the entire app.

self.window.tintColor = [UIColor redColor];

Or in Swift 3:

self.window?.tintColor = UIColor.blue

Source: iOS 7 UI Transition Guide

Bootstrap Accordion button toggle "data-parent" not working

As Blazemonger said, #parent, .panel and .collapse have to be direct descendants. However, if You can't change Your html, You can do workaround using bootstrap events and methods with the following code:

$('#your-parent .collapse').on('show.bs.collapse', function (e) {
    var actives = $('#your-parent').find('.in, .collapsing');
    actives.each( function (index, element) {
        $(element).collapse('hide');
    })
})

VBA Excel 2-Dimensional Arrays

You need ReDim:

m = 5
n = 8
Dim my_array()
ReDim my_array(1 To m, 1 To n)
For i = 1 To m
  For j = 1 To n
    my_array(i, j) = i * j
  Next
Next

For i = 1 To m
  For j = 1 To n
    Cells(i, j) = my_array(i, j)
  Next
Next

As others have pointed out, your actual problem would be better solved with ranges. You could try something like this:

Dim r1 As Range
Dim r2 As Range
Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
totalRow = ws1.Range("A1").End(xlDown).Row
totalCol = ws1.Range("A1").End(xlToRight).Column

Set r1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(totalRow, totalCol))
Set r2 = ws2.Range(ws2.Cells(1, 1), ws2.Cells(totalRow, totalCol))
r2.Value = r1.Value

Spring get current ApplicationContext

Even after adding @Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:

@Component
public class SpringContext implements ApplicationContextAware{

   private static ApplicationContext applicationContext;

   @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws 
     BeansException {
    this.applicationContext=applicationContext;
   }
 }

you can then implement a getter method in the same class as per your need like getting the Implemented class reference by:

    applicationContext.getBean(String serviceName,Interface.Class)

Escaping special characters in Java Regular Expressions

Agree with Gray, as you may need your pattern to have both litrals (\[, \]) and meta-characters ([, ]). so with some utility you should be able to escape all character first and then you can add meta-characters you want to add on same pattern.

Switch statement for greater-than/less-than

This is another option:

     switch (true) {
         case (value > 100):
             //do stuff
             break;
         case (value <= 100)&&(value > 75):
             //do stuff
             break;
         case (value < 50):
            //do stuff
             break;
     }

How to compare LocalDate instances Java 8

I believe this snippet will also be helpful in a situation where the dates comparison spans more than two entries.

static final int COMPARE_EARLIEST = 0;

static final int COMPARE_MOST_RECENT = 1;


public LocalDate getTargetDate(List<LocalDate> datesList, int comparatorType) { 
   LocalDate refDate = null;
   switch(comparatorType)
   {
       case COMPARE_EARLIEST:         
       //returns the most earliest of the date entries
          refDate = (LocalDate) datesList.stream().min(Comparator.comparing(item -> 
                      item.toDateTimeAtCurrentTime())).get();
          break;

       case COMPARE_MOST_RECENT:
          //returns the most recent of the date entries 
          refDate = (LocalDate) datesList.stream().max(Comparator.comparing(item -> 
                    item.toDateTimeAtCurrentTime())).get();
          break;
   }

   return refDate;
}

Detecting the onload event of a window opened with window.open

The core problem seems to be you are opening a window to show a page whose content is already cached in the browser. Therefore no loading happens and therefore no load-event happens.

One possibility could be to use the 'pageshow' -event instead, as described in:

https://support.microsoft.com/en-us/help/3011939/onload-event-does-not-occur-when-clicking-the-back-button-to-a-previou

ES6 modules implementation, how to load a json file

This just works on React & React Native

const data = require('./data/photos.json');

console.log('[-- typeof data --]', typeof data); // object


const fotos = data.xs.map(item => {
    return { uri: item };
});

How to revert the last migration?

The answer by Alasdair covers the basics

  • Identify the migrations you want by ./manage.py showmigrations
  • migrate using the app name and the migration name

But it should be pointed out that not all migrations can be reversed. This happens if Django doesn't have a rule to do the reversal. For most changes that you automatically made migrations by ./manage.py makemigrations, the reversal will be possible. However, custom scripts will need to have both a forward and reverse written, as described in the example here:

https://docs.djangoproject.com/en/1.9/ref/migration-operations/

How to do a no-op reversal

If you had a RunPython operation, then maybe you just want to back out the migration without writing a logically rigorous reversal script. The following quick hack to the example from the docs (above link) allows this, leaving the database in the same state that it was after the migration was applied, even after reversing it.

# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import migrations, models

def forwards_func(apps, schema_editor):
    # We get the model from the versioned app registry;
    # if we directly import it, it'll be the wrong version
    Country = apps.get_model("myapp", "Country")
    db_alias = schema_editor.connection.alias
    Country.objects.using(db_alias).bulk_create([
        Country(name="USA", code="us"),
        Country(name="France", code="fr"),
    ])

class Migration(migrations.Migration):

    dependencies = []

    operations = [
        migrations.RunPython(forwards_func, lambda apps, schema_editor: None),
    ]

This works for Django 1.8, 1.9


Update: A better way of writing this would be to replace lambda apps, schema_editor: None with migrations.RunPython.noop in the snippet above. These are both functionally the same thing. (credit to the comments)

How to convert map to url query string?

This is the solution I implemented, using Java 8 and org.apache.http.client.URLEncodedUtils. It maps the entries of the map into a list of BasicNameValuePair and then uses Apache's URLEncodedUtils to turn that into a query string.

List<BasicNameValuePair> nameValuePairs = params.entrySet().stream()
   .map(entry -> new BasicNameValuePair(entry.getKey(), entry.getValue()))
   .collect(Collectors.toList());

URLEncodedUtils.format(nameValuePairs, Charset.forName("UTF-8"));

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

How to open adb and use it to send commands

The adb tool can be found in sdk/platform-tools/

If you don't see this directory in your SDK, launch the SDK Manager and install "Android SDK Platform-tools"

Also update your PATH environment variable to include the platform-tools/ directory, so you can execute adb from any location.

Disable hover effects on mobile browsers

In my project we solved this issue using https://www.npmjs.com/package/postcss-hover-prefix and https://modernizr.com/ First we post-process output css files with postcss-hover-prefix. It adds .no-touch for all css hover rules.

const fs = require("fs");
const postcss = require("postcss");
const hoverPrfx = require("postcss-hover-prefix");

var css = fs.readFileSync(cssFileName, "utf8").toString();
postcss()
   .use(hoverPrfx("no-touch"))
   .process(css)
   .then((result) => {
      fs.writeFileSync(cssFileName, result);
   });

css

a.text-primary:hover {
  color: #62686d;
}

becomes

.no-touch a.text-primary:hover {
  color: #62686d;
}

At runtime Modernizr automatically adds css classes to html tag like this

<html class="wpfe-full-height js flexbox flexboxlegacy canvas canvastext webgl 
  no-touch 
  geolocation postmessage websqldatabase indexeddb hashchange
  history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage
  borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients
  cssreflections csstransforms csstransforms3d csstransitions fontface
  generatedcontent video audio localstorage sessionstorage webworkers
  applicationcache svg inlinesvg smil svgclippaths websocketsbinary">

Such post-processing of css plus Modernizr disables hover for touch devices and enables for others. In fact this approach was inspired by Bootstrap 4, how they solve the same issue: https://v4-alpha.getbootstrap.com/getting-started/browsers-devices/#sticky-hoverfocus-on-mobile

TypeScript add Object to array with push

If your example represents your real code, the problem is not in the push, it's that your constructor doesn't do anything.

You need to declare and initialize the x and y members.

Explicitly:

export class Pixel {
    public x: number;
    public y: number;   
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}

Or implicitly:

export class Pixel {
    constructor(public x: number, public y: number) {}
}

How to get summary statistics by group

I'll put in my two cents for tapply().

tapply(df$dt, df$group, summary)

You could write a custom function with the specific statistics you want to replace summary.

Server.MapPath - Physical path given, virtual path expected

var files = Directory.GetFiles(@"E:\ftproot\sales");

How to get the next auto-increment id in mysql

Use LAST_INSERT_ID() from your SQL query.

Or

You can also use mysql_insert_id() to get it using PHP.

Execute an action when an item on the combobox is selected

The simple solution would be to use a ItemListener. When the state changes, you would simply check the currently selected item and set the text accordingly

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox06 {

    public static void main(String[] args) {
        new TestComboBox06();
    }

    public TestComboBox06() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JComboBox cb;
        private JTextField field;

        public TestPane() {
            cb = new JComboBox(new String[]{"Item 1", "Item 2"});
            field = new JTextField(12);

            add(cb);
            add(field);

            cb.setSelectedItem(null);

            cb.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    Object item = cb.getSelectedItem();
                    if ("Item 1".equals(item)) {
                        field.setText("20");
                    } else if ("Item 2".equals(item)) {
                        field.setText("30");
                    }
                }
            });
        }

    }

}

A better solution would be to create a custom object that represents the value to be displayed and the value associated with it...

Updated

Now I no longer have a 10 month chewing on my ankles, I updated the example to use a ListCellRenderer which is a more correct approach then been lazy and overriding toString

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class TestComboBox06 {

    public static void main(String[] args) {
        new TestComboBox06();
    }

    public TestComboBox06() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }

        });
    }

    public class TestPane extends JPanel {

        private JComboBox cb;
        private JTextField field;

        public TestPane() {
            cb = new JComboBox(new Item[]{
                new Item("Item 1", "20"), 
                new Item("Item 2", "30")});
            cb.setRenderer(new ItemCelLRenderer());
            field = new JTextField(12);

            add(cb);
            add(field);

            cb.setSelectedItem(null);

            cb.addItemListener(new ItemListener() {
                @Override
                public void itemStateChanged(ItemEvent e) {
                    Item item = (Item)cb.getSelectedItem();
                    field.setText(item.getValue());
                }
            });
        }

    }

    public class Item {
        private String value;
        private String text;

        public Item(String text, String value) {
            this.text = text;
            this.value = value;
        }

        public String getText() {
            return text;
        }

        public String getValue() {
            return value;
        }

    }

    public class ItemCelLRenderer extends DefaultListCellRenderer {

        @Override
        public Component getListCellRendererComponent(JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
            super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); //To change body of generated methods, choose Tools | Templates.
            if (value instanceof Item) {
                setText(((Item)value).getText());
            }
            return this;
        }

    }

}

File URL "Not allowed to load local resource" in the Internet Browser

I didn't realise from your original question that you were opening a file on the local machine, I thought you were sending a file from the web server to the client.

Based on your screenshot, try formatting your link like so:

<a href="file:///C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">Klik hier</a>

(without knowing the contents of each of your recordset variables I can't give you the exact ASP code)

How to check for null in Twig?

I don't think you can. This is because if a variable is undefined (not set) in the twig template, it looks like NULL or none (in twig terms). I'm pretty sure this is to suppress bad access errors from occurring in the template.

Due to the lack of a "identity" in Twig (===) this is the best you can do

{% if var == null %}
    stuff in here
{% endif %}

Which translates to:

if ((isset($context['somethingnull']) ? $context['somethingnull'] : null) == null)
{
  echo "stuff in here";
}

Which if your good at your type juggling, means that things such as 0, '', FALSE, NULL, and an undefined var will also make that statement true.

My suggest is to ask for the identity to be implemented into Twig.

Multiple commands in an alias for bash

So use a semi-colon:

alias lock='gnome-screensaver; gnome-screen-saver-command --lock'

This doesn't work well if you want to supply arguments to the first command. Alternatively, create a trivial script in your $HOME/bin directory.

How to draw border around a UILabel?

Swift version:

myLabel.layer.borderWidth = 0.5
myLabel.layer.borderColor = UIColor.greenColor().CGColor

For Swift 3:

myLabel.layer.borderWidth = 0.5
myLabel.layer.borderColor = UIColor.green.cgColor

How do I pass multiple parameters into a function in PowerShell?

Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma separated. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if Set-StrictMode -Version 2 or higher is active. Parenthesised arguments are used in .NET methods only.

function foo($a, $b, $c) {
   "a: $a; b: $b; c: $c"
}

ps> foo 1 2 3
a: 1; b: 2; c: 3

how to setup ssh keys for jenkins to publish via ssh

You will need to create a public/private key as the Jenkins user on your Jenkins server, then copy the public key to the user you want to do the deployment with on your target server.

Step 1, generate public and private key on build server as user jenkins

build1:~ jenkins$ whoami
jenkins
build1:~ jenkins$ ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/var/lib/jenkins/.ssh/id_rsa): 
Created directory '/var/lib/jenkins/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /var/lib/jenkins/.ssh/id_rsa.
Your public key has been saved in /var/lib/jenkins/.ssh/id_rsa.pub.
The key fingerprint is:
[...] 
The key's randomart image is:
[...]
build1:~ jenkins$ ls -l .ssh
total 2
-rw-------  1 jenkins  jenkins  1679 Feb 28 11:55 id_rsa
-rw-r--r--  1 jenkins  jenkins   411 Feb 28 11:55 id_rsa.pub 
build1:~ jenkins$ cat .ssh/id_rsa.pub
ssh-rsa AAAlskdjfalskdfjaslkdjf... [email protected]

Step 2, paste the pub file contents onto the target server.

target:~ bob$ cd .ssh
target:~ bob$ vi authorized_keys (paste in the stuff which was output above.)

Make sure your .ssh dir has permissoins 700 and your authorized_keys file has permissions 644

Step 3, configure Jenkins

  1. In the jenkins web control panel, nagivate to "Manage Jenkins" -> "Configure System" -> "Publish over SSH"
  2. Either enter the path of the file e.g. "var/lib/jenkins/.ssh/id_rsa", or paste in the same content as on the target server.
  3. Enter your passphrase, server and user details, and you are good to go!

Microsoft Visual C++ 14.0 is required (Unable to find vcvarsall.bat)

None of the solutions here and elsewhere worked for me. Turns out an incompatible 32bit version of mysqlclient is being installed on my 64bit Windows 10 OS because I'm using a 32bit version of Python

I had to uninstall my current Python 3.7 32bit, and reinstalled Python 3.7 64bit and everything is working fine now

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

In the first example, you are reassigning the variable a, while in the second one you are modifying the data in-place, using the += operator.

See the section about 7.2.1. Augmented assignment statements :

An augmented assignment expression like x += 1 can be rewritten as x = x + 1 to achieve a similar, but not exactly equal effect. In the augmented version, x is only evaluated once. Also, when possible, the actual operation is performed in-place, meaning that rather than creating a new object and assigning that to the target, the old object is modified instead.

+= operator calls __iadd__. This function makes the change in-place, and only after its execution, the result is set back to the object you are "applying" the += on.

__add__ on the other hand takes the parameters and returns their sum (without modifying them).

org.hibernate.exception.SQLGrammarException: could not insert [com.sample.Person]

I sovled this errors by modifying the Database charset.Old Database charset is cp1252 and i conver to utf-8

Where to put the gradle.properties file

Gradle looks for gradle.properties files in these places:

  • in project build dir (that is where your build script is)
  • in sub-project dir
  • in gradle user home (defined by the GRADLE_USER_HOME environment variable, which if not set defaults to USER_HOME/.gradle)

Properties from one file will override the properties from the previous ones (so file in gradle user home has precedence over the others, and file in sub-project has precedence over the one in project root).

Reference: https://gradle.org/docs/current/userguide/build_environment.html

converting Java bitmap to byte array

In order to avoid OutOfMemory error for bigger files, I would solve the task by splitting a bitmap into several parts and merging their parts' bytes.

private byte[] getBitmapBytes(Bitmap bitmap)
{
    int chunkNumbers = 10;
    int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
    byte[] imageBytes = new byte[bitmapSize];
    int rows, cols;
    int chunkHeight, chunkWidth;
    rows = cols = (int) Math.sqrt(chunkNumbers);
    chunkHeight = bitmap.getHeight() / rows;
    chunkWidth = bitmap.getWidth() / cols;

    int yCoord = 0;
    int bitmapsSizes = 0;

    for (int x = 0; x < rows; x++)
    {
        int xCoord = 0;
        for (int y = 0; y < cols; y++)
        {
            Bitmap bitmapChunk = Bitmap.createBitmap(bitmap, xCoord, yCoord, chunkWidth, chunkHeight);
            byte[] bitmapArray = getBytesFromBitmapChunk(bitmapChunk);
            System.arraycopy(bitmapArray, 0, imageBytes, bitmapsSizes, bitmapArray.length);
            bitmapsSizes = bitmapsSizes + bitmapArray.length;
            xCoord += chunkWidth;

            bitmapChunk.recycle();
            bitmapChunk = null;
        }
        yCoord += chunkHeight;
    }

    return imageBytes;
}


private byte[] getBytesFromBitmapChunk(Bitmap bitmap)
{
    int bitmapSize = bitmap.getRowBytes() * bitmap.getHeight();
    ByteBuffer byteBuffer = ByteBuffer.allocate(bitmapSize);
    bitmap.copyPixelsToBuffer(byteBuffer);
    byteBuffer.rewind();
    return byteBuffer.array();
}

Remove decimal values using SQL query

As I understand your question, You have one table with column as datatype decimal(18,9). And the column contains the data as follows:-

12.00
15.00
18.00
20.00

Now if you want to show record on UI without decimal value means like (12,15,18,20) then there are two options:-

  1. Either cast this column as int in Select Clause
  2. or may be you want to update this column value like (12,15,18,20).

To apply, First very simple just use the cast in select clause

select CAST(count AS INT) from tablename;

But if you want to update your column data with int value then you have to update you column datatype

and to do that

ALTER TABLE tablename ALTER COLUMN columnname decimal(9,0)

Then execute this

UPDATE tablename
   SET count = CAST(columnname AS INT)

Merge (with squash) all changes from another branch as a single commit

Try git rebase -i master on your feature branch. You can then change all but one 'pick' to 'squash' to combine the commits. See squashing commits with rebase

Finally, you can then do the merge from master branch.

Clearing _POST array fully

The solutions so far don't work because the POST data is stored in the headers. A redirect solves this issue according this this post.

How to delete $_POST variable upon pressing 'Refresh' button on browser with PHP?

How can we dynamically allocate and grow an array

You have to manually create a new bigger array and copy over the items.

this may help

How to set scope property with ng-init?

I had some trouble with $scope.$watch but after a lot of testing I found out that my data-ng-model="User.UserName" was badly named and after I changed it to data-ng-model="UserName" everything worked fine. I expect it to be the . in the name causing the issue.

Using number_format method in Laravel

If you are using Eloquent the best solution is:

public function getFormattedPriceAttribute()
{
    return number_format($this->attributes['price'], 2);
}

So now you must append formattedPrice in your model and you can use both, price (at its original state) and formattedPrice.

Attach Authorization header for all axios requests

If you want to call other api routes in the future and keep your token in the store then try using redux middleware.

The middleware could listen for the an api action and dispatch api requests through axios accordingly.

Here is a very basic example:

actions/api.js

export const CALL_API = 'CALL_API';

function onSuccess(payload) {
  return {
    type: 'SUCCESS',
    payload
  };
}

function onError(payload) {
  return {
    type: 'ERROR',
    payload,
    error: true
  };
}

export function apiLogin(credentials) {
  return {
    onSuccess,
    onError,
    type: CALL_API,
    params: { ...credentials },
    method: 'post',
    url: 'login'
  };
}

middleware/api.js

import axios from 'axios';
import { CALL_API } from '../actions/api';

export default ({ getState, dispatch }) => next => async action => {
  // Ignore anything that's not calling the api
  if (action.type !== CALL_API) {
    return next(action);
  }

  // Grab the token from state
  const { token } = getState().session;

  // Format the request and attach the token.
  const { method, onSuccess, onError, params, url } = action;

  const defaultOptions = {
    headers: {
      Authorization: token ? `Token ${token}` : '',
    }
  };

  const options = {
    ...defaultOptions,
    ...params
  };

  try {
    const response = await axios[method](url, options);
    dispatch(onSuccess(response.data));
  } catch (error) {
    dispatch(onError(error.data));
  }

  return next(action);
};

How to move an element down a litte bit in html

You can use the top margin-top and adjust the text or you could also use padding-top both would have similar visual effect in your case but actually both behave a bit differently.

Construct pandas DataFrame from items in nested dictionary

So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d

import pandas as pd
d
{'RAY Index': {datetime.date(2014, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},
datetime.date(2014, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},
datetime.date(2014, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},
datetime.date(2014, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {datetime.date(2014, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},
datetime.date(2014, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},
datetime.date(2014, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},
datetime.date(2014, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}

The command

pd.Panel(d)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06

where pd.Panel(d)[item] yields a dataframe

pd.Panel(d)['SPX Index']
2014-11-03  2014-11-04  2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33

You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.

pd.Panel(d).to_frame().reset_index()
major   minor      RAY Index    SPX Index
PX_LAST 2014-11-03  1199.460    2017.81
PX_LAST 2014-11-04  1195.323    2012.10
PX_LAST 2014-11-05  1200.936    2023.57
PX_LAST 2014-11-06  1206.061    2031.21
PX_OPEN 2014-11-03  1200.140    2018.21
PX_OPEN 2014-11-04  1197.690    2015.81
PX_OPEN 2014-11-05  1195.320    2015.29
PX_OPEN 2014-11-06  1200.620    2023.33

Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Panel.transpose.html

Just as an example

pd.Panel(d).transpose(2,0,1).to_frame().reset_index()
major        minor  2014-11-03  2014-11-04  2014-11-05  2014-11-06
RAY Index   PX_LAST 1199.46    1195.323     1200.936    1206.061
RAY Index   PX_OPEN 1200.14    1197.690     1195.320    1200.620
SPX Index   PX_LAST 2017.81    2012.100     2023.570    2031.210
SPX Index   PX_OPEN 2018.21    2015.810     2015.290    2023.330

Hope this helps.

Flexbox Not Centering Vertically in IE

Try wrapping whatever div you have flexboxed with flex-direction: column in a container that is also flexboxed.

I just tested this in IE11 and it works. An odd fix, but until Microsoft makes their internal bug fix external...it'll have to do!

HTML:

<div class="FlexContainerWrapper">
    <div class="FlexContainer">
        <div class="FlexItem">
            <p>I should be centered.</p>
        </div>
    </div>
</div>

CSS:

html, body {
  height: 100%;
}

.FlexContainerWrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.FlexContainer {
  align-items: center;
  background: hsla(0,0%,0%,.1);
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-height: 100%;
  width: 600px;
}

.FlexItem {
  background: hsla(0,0%,0%,.1);
  box-sizing: border-box;
  max-width: 100%;
}

2 examples for you to test in IE11: http://codepen.io/philipwalton/pen/JdvdJE http://codepen.io/chriswrightdesign/pen/emQNGZ/

How to install Boost on Ubuntu

Actually you don't need "install" or "compile" anything before using Boost in your project. You can just download and extract the Boost library to any location on your machine, which is usually like /usr/local/.

When you compile your code, you can just indicate the compiler where to find the libraries by -I. For example, g++ -I /usr/local/boost_1_59_0 xxx.hpp.

Error : java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V

I encountered the same error when added http-builder to dependencies.
In my case, I could solve by simply excluding asm like this:

compile('org.codehaus.groovy.modules.http-builder:http-builder:0.7'){
    excludes 'xml-apis'
    exclude(group:'xerces', module: 'xercesImpl')
    excludes 'asm'
}

What is a good practice to check if an environmental variable exists or not?

Use the first; it directly tries to check if something is defined in environ. Though the second form works equally well, it's lacking semantically since you get a value back if it exists and only use it for a comparison.

You're trying to see if something is present in environ, why would you get just to compare it and then toss it away?

That's exactly what getenv does:

Get an environment variable, return None if it doesn't exist. The optional second argument can specify an alternate default.

(this also means your check could just be if getenv("FOO"))

you don't want to get it, you want to check for it's existence.

Either way, getenv is just a wrapper around environ.get but you don't see people checking for membership in mappings with:

from os import environ
if environ.get('Foo') is not None:

To summarize, use:

if "FOO" in os.environ:
    pass

if you just want to check for existence, while, use getenv("FOO") if you actually want to do something with the value you might get.

Convert timestamp long to normal date format

java.time

    ZoneId usersTimeZone = ZoneId.of("Asia/Tashkent");
    Locale usersLocale = Locale.forLanguageTag("ga-IE");
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(usersLocale);

    long microsSince1970 = 1_512_345_678_901_234L;
    long secondsSince1970 = TimeUnit.MICROSECONDS.toSeconds(microsSince1970);
    long remainingMicros = microsSince1970 - TimeUnit.SECONDS.toMicros(secondsSince1970);
    ZonedDateTime dateTime = Instant.ofEpochSecond(secondsSince1970, 
                    TimeUnit.MICROSECONDS.toNanos(remainingMicros))
            .atZone(usersTimeZone);
    String dateTimeInUsersFormat = dateTime.format(formatter);
    System.out.println(dateTimeInUsersFormat);

The above snippet prints:

4 Noll 2017 05:01:18

“Noll” is Gaelic for December, so this should make your user happy. Except there may be very few Gaelic speaking people living in Tashkent, so please specify the user’s correct time zone and locale yourself.

I am taking seriously that you got microseconds from your database. If second precision is fine, you can do without remainingMicros and just use the one-arg Instant.ofEpochSecond(), which will make the code a couple of lines shorter. Since Instant and ZonedDateTime do support nanosecond precision, I found it most correct to keep the full precision of your timestamp. If your timestamp was in milliseconds rather than microseconds (which they often are), you may just use Instant.ofEpochMilli().

The answers using Date, Calendar and/or SimpleDateFormat were fine when this question was asked 7 years ago. Today those classes are all long outdated, and we have so much better in java.time, the modern Java date and time API.

For most uses I recommend you use the built-in localized formats as I do in the code. You may experiment with passing SHORT, LONG or FULL for format style. Yo may even specify format style for the date and for the time of day separately using an overloaded ofLocalizedDateTime method. If a specific format is required (this was asked in a duplicate question), you can have that:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss, dd/MM/uuuu");

Using this formatter instead we get

05:01:18, 04/12/2017

Link: Oracle tutorial: Date Time explaining how to use java.time.

Open files always in a new tab

enabling using GUI

go to Code -> Preferences -> Settings -> User -> Window -> New Window

here Open Files In New Window under drop down list select "on" that's it.

my VS Code version 1.38.1

How to specify credentials when connecting to boto3 S3?

There are numerous ways to store credentials while still using boto3.resource(). I'm using the AWS CLI method myself. It works perfectly.

https://boto3.amazonaws.com/v1/documentation/api/latest/guide/configuration.html?fbclid=IwAR2LlrS4O2gYH6xAF4QDVIH2Q2tzfF_VZ6loM3XfXsPAOR4qA-pX_qAILys

jQuery convert line breaks to br (nl2br equivalent)

I wrote a little jQuery extension for this:

$.fn.nl2brText = function (sText) {
    var bReturnValue = 'undefined' == typeof sText;
    if(bReturnValue) {
        sText = $('<pre>').html(this.html().replace(/<br[^>]*>/i, '\n')).text();
    }
    var aElms = [];
    sText.split(/\r\n|\r|\n/).forEach(function(sSubstring) {
        if(aElms.length) {
            aElms.push(document.createElement('br'));
        }
        aElms.push(document.createTextNode(sSubstring));
    });
    var $aElms = $(aElms);
    if(bReturnValue) {
        return $aElms;
    }
    return this.empty().append($aElms);
};

Redirect From Action Filter Attribute

I am using MVC4, I used following approach to redirect a custom html screen upon authorization breach.

Extend AuthorizeAttribute say CutomAuthorizer override the OnAuthorization and HandleUnauthorizedRequest

Register the CustomAuthorizer in the RegisterGlobalFilters.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{

    filters.Add(new CustomAuthorizer());
}

upon identifying the unAuthorized access call HandleUnauthorizedRequestand redirect to the concerned controller action as shown below.


public class CustomAuthorizer : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        bool isAuthorized = IsAuthorized(filterContext); // check authorization
        base.OnAuthorization(filterContext);
        if (!isAuthorized && !filterContext.ActionDescriptor.ActionName.Equals("Unauthorized", StringComparison.InvariantCultureIgnoreCase)
            && !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals("LogOn", StringComparison.InvariantCultureIgnoreCase))
        {

            HandleUnauthorizedRequest(filterContext);

        }
    }

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {
        filterContext.Result =
       new RedirectToRouteResult(
           new RouteValueDictionary{{ "controller", "LogOn" },
                                          { "action", "Unauthorized" }

                                         });

    }
}

How to replace NaN value with zero in a huge data frame?

The following should do what you want:

x <- data.frame(X1=sample(c(1:3,NaN), 200, replace=TRUE), X2=sample(c(4:6,NaN), 200, replace=TRUE))
head(x)
x <- replace(x, is.na(x), 0)
head(x)

Authenticate with GitHub using a token

By having struggling so many hours on applying GitHub token finally it works as below:

$ cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o yaml | yq -y .spec.data.auth.password)

  • code follows Codefresh guidance on cloning a repo using token (freestyle}
  • test carried: sed %d%H%M on match word '-123456-whatever'
  • push back to the repo (which is private repo)
  • triggered by DockerHub webhooks

Following is the complete code:

version: '1.0'
steps:
  get_git_token:
    title: Reading Github token
    image: codefresh/cli
    commands:
      - cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o yaml | yq -y .spec.data.auth.password)
  main_clone:
    title: Updating the repo
    image: alpine/git:latest
    commands:
      - git clone https://chetabahana:[email protected]/chetabahana/compose.git
      - cd compose && git remote rm origin
      - git config --global user.name "chetabahana"
      - git config --global user.email "[email protected]"
      - git remote add origin https://chetabahana:[email protected]/chetabahana/compose.git
      - sed -i "s/-[0-9]\{1,\}-\([a-zA-Z0-9_]*\)'/-`date +%d%H%M`-whatever'/g" cloudbuild.yaml
      - git status && git add . && git commit -m "fresh commit" && git push -u origin master

Output...

On branch master 
Changes not staged for commit: 
  (use "git add ..." to update what will be committed) 
  (use "git checkout -- ..." to discard changes in working directory) 

modified:   cloudbuild.yaml 

no changes added to commit (use "git add" and/or "git commit -a") 
[master dbab20f] fresh commit 
 1 file changed, 1 insertion(+), 1 deletion(-) 
Enumerating objects: 5, done. 
Counting objects:  20% (1/5) ...  Counting objects: 100% (5/5), done. 
Delta compression using up to 4 threads 
Compressing objects:  33% (1/3) ... Writing objects: 100% (3/3), 283 bytes | 283.00 KiB/s, done. 
Total 3 (delta 2), reused 0 (delta 0) 
remote: Resolving deltas:   0% (0/2)  ...   (2/2), completed with 2 local objects. 
To https://github.com/chetabahana/compose.git 
   bbb6d2f..dbab20f  master -> master 
Branch 'master' set up to track remote branch 'master' from 'origin'. 
Reading environment variable exporting file contents. 
Successfully ran freestyle step: Cloning the repo 

Detect click event inside iframe

Just posting in case it helps someone. For me, the following code worked perfect:

$(document).ready(function(){
     $("#payment_status_div").hide();
     var iframe = $('#FileFrame').contents();
     iframe.find("#take_payment").click(function(){
         $("#payment_status_div").show("slow");
     });
});

Where 'FileFrame' is the iframe id and 'take_payment' is the button inside iframe. Since my form inside the iframe is posted to a different domain, when used load, I got an error message saying:

Blocked a frame with origin "https://www.example.com" from accessing a frame with origin "https://secure-test.worldpay.com". Protocols, domains, and ports must match.

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You can just use the Select() extension method:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());

Or in LINQ syntax:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };

var strings = from i in integers
              select i.ToString();

Variable that has the path to the current ansible-playbook that is executing?

I was using a playbook like this to test my roles locally:

---
- hosts: localhost
  roles:
     - role: .

but this stopped working with Ansible v2.2.

I debugged the aforementioned solution of

---
- hosts: all
  tasks:
    - name: Find out playbooks path
      shell: pwd
      register: playbook_path_output
    - debug: var=playbook_path_output.stdout

and it produced my home directory and not the "current working directory"

I settled with

---
- hosts: all
  roles:
    - role: '{{playbook_dir}}'

per the solution above.

json and empty array

null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.

Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.

How do I format a number to a dollar amount in PHP

i tried money_format() but it didn't work for me at all. then i tried the following one. it worked perfect for me. hopefully it will work in right way for you too.. :)

you should use this one

number_format($money, 2,'.', ',')

it will show money number in terms of money format up to 2 decimal.

Right way to convert data.frame to a numeric matrix, when df also contains strings?

I had the same problem and I solved it like this, by taking the original data frame without row names and adding them later

SFIo <- as.matrix(apply(SFI[,-1],2,as.numeric))
row.names(SFIo) <- SFI[,1]

How to get the file extension in PHP?

This will work as well:

$array = explode('.', $_FILES['image']['name']);
$extension = end($array);

Django. Override save for model

Some thoughts:

class Model(model.Model):
    _image=models.ImageField(upload_to='folder')
    thumb=models.ImageField(upload_to='folder')
    description=models.CharField()

    def set_image(self, val):
        self._image = val
        self._image_changed = True

        # Or put whole logic in here
        small = rescale_image(self.image,width=100,height=100)
        self.image_small=SimpleUploadedFile(name,small_pic)

    def get_image(self):
        return self._image

    image = property(get_image, set_image)

    # this is not needed if small_image is created at set_image
    def save(self, *args, **kwargs):
        if getattr(self, '_image_changed', True):
            small=rescale_image(self.image,width=100,height=100)
            self.image_small=SimpleUploadedFile(name,small_pic)
        super(Model, self).save(*args, **kwargs)

Not sure if it would play nice with all pseudo-auto django tools (Example: ModelForm, contrib.admin etc).

Add 10 seconds to a Date

Just for the performance maniacs among us.

getTime

var d = new Date('2014-01-01 10:11:55');
d = new Date(d.getTime() + 10000);

5,196,949 Ops/sec, fastest


setSeconds

var d = new Date('2014-01-01 10:11:55');
d.setSeconds(d.getSeconds() + 10);

2,936,604 Ops/sec, 43% slower


moment.js

var d = new moment('2014-01-01 10:11:55');
d = d.add(10, 'seconds');

22,549 Ops/sec, 100% slower


So maybe its the least human readable (not that bad) but the fastest way of going :)

jspref online tests

Angular 4 - get input value

In HTML add

<input (keyup)="onKey($event)">

And in component Add

onKey(event) {const inputValue = event.target.value;}

Running a cron job on Linux every six hours

You should include a path to your command, since cron runs with an extensively cut-down environment. You won't have all the environment variables you have in your interactive shell session.

It's a good idea to specify an absolute path to your script/binary, or define PATH in the crontab itself. To help debug any issues I would also redirect stdout/err to a log file.

How do I do word Stemming or Lemmatization?

If you know Python, The Natural Language Toolkit (NLTK) has a very powerful lemmatizer that makes use of WordNet.

Note that if you are using this lemmatizer for the first time, you must download the corpus prior to using it. This can be done by:

>>> import nltk
>>> nltk.download('wordnet')

You only have to do this once. Assuming that you have now downloaded the corpus, it works like this:

>>> from nltk.stem.wordnet import WordNetLemmatizer
>>> lmtzr = WordNetLemmatizer()
>>> lmtzr.lemmatize('cars')
'car'
>>> lmtzr.lemmatize('feet')
'foot'
>>> lmtzr.lemmatize('people')
'people'
>>> lmtzr.lemmatize('fantasized','v')
'fantasize'

There are other lemmatizers in the nltk.stem module, but I haven't tried them myself.

Accessing last x characters of a string in Bash

Last three characters of string:

${string: -3}

or

${string:(-3)}

(mind the space between : and -3 in the first form).

Please refer to the Shell Parameter Expansion in the reference manual:

${parameter:offset}
${parameter:offset:length}

Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.

If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.

Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.

Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3} expands to the empty string. If, in this case, you want the expansion of string, you may use:

${string:${#string}<3?0:-3}

This uses the ?: ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.


Update for a POSIX-compliant solution

The previous part gives the best option when using Bash. If you want to target POSIX shells, here's an option (that doesn't use pipes or external tools like cut):

# New variable with 3 last characters removed
prefix=${string%???}
# The new string is obtained by removing the prefix a from string
newstring=${string#"$prefix"}

One of the main things to observe here is the use of quoting for prefix inside the parameter expansion. This is mentioned in the POSIX ref (at the end of the section):

The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Pattern Matching Notation), rather than regular expression notation, shall be used to evaluate the patterns. If parameter is '#', '*', or '@', the result of the expansion is unspecified. If parameter is unset and set -u is in effect, the expansion shall fail. Enclosing the full parameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces shall have this effect. In each variety, if word is omitted, the empty pattern shall be used.

This is important if your string contains special characters. E.g. (in dash),

$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
*ext
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"
ext

Of course, this is usable only when then number of characters is known in advance, as you have to hardcode the number of ? in the parameter expansion; but when it's the case, it's a good portable solution.

getting " (1) no such column: _id10 " error

I think you missed a equal sign at:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + "" + l, null, null, null, null);  

Change to:

Cursor c = ourDatabase.query(DATABASE_TABLE, column, KEY_ROWID + " = " + l, null, null, null, null); 

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

When I drag files in, the "Add to targets" box seems to be un-ticked by default. If I leave it un-ticked then I have the problem described. Fix it by deleting the files then dragging them back in but making sure to tick "Add to targets". enter image description here

mat-form-field must contain a MatFormFieldControl

You might have missed to import MatInputModule

How to import/include a CSS file using PHP code and not HTML code?

you can use:

<?php
$css = file_get_contents('CSS/main.css');
echo $css;
?>

and assuming that css file doesn't have it already, wrap the above in:

<style type="text/css">
...
</style>

Trigger insert old values- values that was updated

ALTER trigger ETU on Employee FOR UPDATE AS insert into Log (EmployeeId, LogDate, OldName) select EmployeeId, getdate(), name from deleted go

jQuery AJAX Character Encoding

I DONT AGREE everything must be UTF-8, you can make it work perfectly with ISO 8859, I did, please read my response here.

my response in stackoverflow

Assign a class name to <img> tag instead of write it in css file?

The short answer is adding a class directly to the element you want to style is indeed the most efficient way to target and style that Element. BUT, in real world scenarios it is so negligible that it is not an issue at all to worry about.

To quote Steve Ouders (CSS optimization expert) http://www.stevesouders.com/blog/2009/03/10/performance-impact-of-css-selectors/:

Based on tests I have the following hypothesis: For most web sites, the possible performance gains from optimizing CSS selectors will be small, and are not worth the costs.

Maintainability of code is much more important in real world scenarios. Since the underlying topic here is front-end performance; the real performance boosters for speedy page rendering are found in:

  • Make fewer HTTP requests
  • Use a CDN
  • Add an Expires header
  • Gzip components
  • Put stylesheets at the top
  • Put scripts at the bottom
  • Avoid CSS expressions
  • Make JS and CSS external
  • Reduce DNS lookups
  • Minify JS
  • Avoid redirects
  • Remove duplicate scripts
  • Configure ETags
  • Make AJAX cacheable

Source: http://stevesouders.com/docs/web20expo-20090402.ppt

So just to confirm, the answer is yes, example below is indeed faster but be aware of the bigger picture:

<div class="column">
   <img class="custom-style" alt="appropriate alt text" />
</div>

How do you change Background for a Button MouseOver in WPF?

To remove the default MouseOver behaviour on the Button you will need to modify the ControlTemplate. Changing your Style definition to the following should do the trick:

<Style TargetType="{x:Type Button}">
    <Setter Property="Background" Value="Green"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{TemplateBinding Background}" BorderBrush="Black" BorderThickness="1">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="Red"/>
        </Trigger>
    </Style.Triggers>
</Style>

EDIT: It's a few years late, but you are actually able to set the border brush inside of the border that is in there. Idk if that was pointed out but it doesn't seem like it was...

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

You can't remove, nor can you add to a fixed-size-list of Arrays.

But you can create your sublist from that list.

list = list.subList(0, list.size() - (list.size() - count));

public static String SelectRandomFromTemplate(String template, int count) {
   String[] split = template.split("\\|");
   List<String> list = Arrays.asList(split);
   Random r = new Random();
   while( list.size() > count ) {
      list = list.subList(0, list.size() - (list.size() - count));
   }
   return StringUtils.join(list, ", ");
}

*Other way is

ArrayList<String> al = new ArrayList<String>(Arrays.asList(template));

this will create ArrayList which is not fixed size like Arrays.asList

How do you get the selected value of a Spinner?

mySpinner.getItemAtPosition(mySpinner.getSelectedItemPosition()) works based on Rich's description.

How to assign an action for UIImageView object in Swift

You can add a UITapGestureRecognizer to the imageView, just drag one into your Storyboard/xib, Ctrl-drag from the imageView to the gestureRecognizer, and Ctrl-drag from the gestureRecognizer to the Swift-file to make an IBAction.

You'll also need to enable user interactions on the UIImageView, as shown in this image: enter image description here

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

Just for documentation purpose, to someone that comes on the future, this thing can be solved as simple as this, and with this method, you could do a method that disabled one time, and you could access your method normally

Add this method to the context database class:

protected override void OnModelCreating(DbModelBuilder modelBuilder) {
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}

Use YAML with variables

if your requirement is like parsing an replacing multiple variable and then use it as a hash/or anything then you can do something like this

require 'yaml'
require 'json'
yaml = YAML.load_file("xxxx.yaml")
blueprint = yaml.to_json % { var_a: "xxxx", var_b: "xxxx"}
hash = JSON.parse(blueprint)

inside the yaml just put variables like this

"%{var_a}"

Automatically add all files in a folder to a target using CMake?

The answer by Kleist certainly works, but there is an important caveat:

When you write a Makefile manually, you might generate a SRCS variable using a function to select all .cpp and .h files. If a source file is later added, re-running make will include it.

However, CMake (with a command like file(GLOB ...)) will explicitly generate a file list and place it in the auto-generated Makefile. If you have a new source file, you will need to re-generate the Makefile by re-running cmake.

edit: No need to remove the Makefile.

html 5 audio tag width

Set it the same way you'd set the width of any other HTML element, with CSS:

audio { width: 200px; }

Note that audio is an inline element by default in Firefox, so you might also want to set it to display: block. Here's an example.

Spring MVC 4: "application/json" Content Type is not being set correctly

Use jackson library and @ResponseBody annotation on return type for the Controller.

This works if you wish to return POJOs represented as JSon. If you woud like to return String and not POJOs as JSon please refer to Sotirious answer.

Failed to instantiate module error in Angular js

Or the minified version of the file...

<script src="angular-route.min.js"></script>

More information about this here:

"This error occurs when a module fails to load due to some exception. The error message above should provide additional context."

"In AngularJS 1.2.0 and later, ngRoute has been moved to its own module. If you are getting this error after upgrading to 1.2.x, be sure that you've installed ngRoute."

Listed under section Error: $injector:modulerr Module Error in the Angularjs docs.

Java 8 Iterable.forEach() vs foreach loop

The advantage of Java 1.8 forEach method over 1.7 Enhanced for loop is that while writing code you can focus on business logic only.

forEach method takes java.util.function.Consumer object as an argument, so It helps in having our business logic at a separate location that you can reuse it anytime.

Have look at below snippet,

  • Here I have created new Class that will override accept class method from Consumer Class, where you can add additional functionility, More than Iteration..!!!!!!

    class MyConsumer implements Consumer<Integer>{
    
        @Override
        public void accept(Integer o) {
            System.out.println("Here you can also add your business logic that will work with Iteration and you can reuse it."+o);
        }
    }
    
    public class ForEachConsumer {
    
        public static void main(String[] args) {
    
            // Creating simple ArrayList.
            ArrayList<Integer> aList = new ArrayList<>();
            for(int i=1;i<=10;i++) aList.add(i);
    
            //Calling forEach with customized Iterator.
            MyConsumer consumer = new MyConsumer();
            aList.forEach(consumer);
    
    
            // Using Lambda Expression for Consumer. (Functional Interface) 
            Consumer<Integer> lambda = (Integer o) ->{
                System.out.println("Using Lambda Expression to iterate and do something else(BI).. "+o);
            };
            aList.forEach(lambda);
    
            // Using Anonymous Inner Class.
            aList.forEach(new Consumer<Integer>(){
                @Override
                public void accept(Integer o) {
                    System.out.println("Calling with Anonymous Inner Class "+o);
                }
            });
        }
    }
    

MSVCP140.dll missing

That usually means that your friend does not have the Microsoft redistributable for Visual C++. I am of course assuming you are using VC++ and not MingW or another compiler. Since your friend does not have VS installed as well there is no guarantee he has the redist installed.

VC++ Distro

Insertion sort vs Bubble Sort Algorithms

Bubble sort is almost useless under all circumstances. In use cases when insertion sort may have too many swaps, selection sort can be used because it guarantees less than N times of swap. Because selection sort is better than bubble sort, bubble sort has no use cases.

How do I remove the horizontal scrollbar in a div?

Don't forget to write overflow-x: hidden;

The code should be:

overflow-y: scroll;
overflow-x: hidden;

How to convert an NSString into an NSNumber

Objective-C

(Note: this method doesn't play nice with difference locales, but is slightly faster than a NSNumberFormatter)

NSNumber *num1 = @([@"42" intValue]);
NSNumber *num2 = @([@"42.42" floatValue]);

Swift

Simple but dirty way

// Swift 1.2
if let intValue = "42".toInt() {
    let number1 = NSNumber(integer:intValue)
}

// Swift 2.0
let number2 = Int("42')

// Swift 3.0
NSDecimalNumber(string: "42.42") 

// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)

The extension-way This is better, really, because it'll play nicely with locales and decimals.

extension String {

    var numberValue:NSNumber? {
        let formatter = NSNumberFormatter()
        formatter.numberStyle = .DecimalStyle
        return formatter.number(from: self)
    }
}

Now you can simply do:

let someFloat = "42.42".numberValue
let someInt = "42".numberValue

Styling JQuery UI Autocomplete

You can overwrite the classes in your own css using !important, e.g. if you want to get rid of the rounded corners.

.ui-corner-all
{
border-radius: 0px !important;
}

Use a normal link to submit a form

You can't really do this without some form of scripting to the best of my knowledge.

<form id="my_form">
<!-- Your Form -->    
<a href="javascript:{}" onclick="document.getElementById('my_form').submit(); return false;">submit</a>
</form>

Example from Here.

When should I use a table variable vs temporary table in sql server?

Use a table variable if for a very small quantity of data (thousands of bytes)

Use a temporary table for a lot of data

Another way to think about it: if you think you might benefit from an index, automated statistics, or any SQL optimizer goodness, then your data set is probably too large for a table variable.

In my example, I just wanted to put about 20 rows into a format and modify them as a group, before using them to UPDATE / INSERT a permanent table. So a table variable is perfect.

But I am also running SQL to back-fill thousands of rows at a time, and I can definitely say that the temporary tables perform much better than table variables.

This is not unlike how CTE's are a concern for a similar size reason - if the data in the CTE is very small, I find a CTE performs as good as or better than what the optimizer comes up with, but if it is quite large then it hurts you bad.

My understanding is mostly based on http://www.developerfusion.com/article/84397/table-variables-v-temporary-tables-in-sql-server/, which has a lot more detail.

Name node is in safe mode. Not able to leave

In order to forcefully let the namenode leave safemode, following command should be executed:

 bin/hadoop dfsadmin -safemode leave

You are getting Unknown command error for your command as -safemode isn't a sub-command for hadoop fs, but it is of hadoop dfsadmin.

Also after the above command, I would suggest you to once run hadoop fsck so that any inconsistencies crept in the hdfs might be sorted out.

Update:

Use hdfs command instead of hadoop command for newer distributions. The hadoop command is being deprecated:

hdfs dfsadmin -safemode leave

hadoop dfsadmin has been deprecated and so is hadoop fs command, all hdfs related tasks are being moved to a separate command hdfs.

Differentiate between function overloading and function overriding

Overloading means having methods with same name but different signature Overriding means rewriting the virtual method of the base class.............

Downloading folders from aws s3, cp or sync?

Just used version 2 of the AWS CLI. For the s3 option, there is also a --dryrun option now to show you what will happen:

aws s3 --dryrun cp s3://bucket/filename /path/to/dest/folder --recursive

How to update a plot in matplotlib?

You can also do like the following: This will draw a 10x1 random matrix data on the plot for 50 cycles of the for loop.

import matplotlib.pyplot as plt
import numpy as np

plt.ion()
for i in range(50):
    y = np.random.random([10,1])
    plt.plot(y)
    plt.draw()
    plt.pause(0.0001)
    plt.clf()

Upload Image using POST form data in Python-requests

Use this snippet

import os
import requests
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
  name_img= os.path.basename(path_img)
  files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
  with requests.Session() as s:
    r = s.post(url,files=files)
    print(r.status_code)

How do I translate an ISO 8601 datetime string into a Python datetime object?

Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]. If you want to use strptime, you need to strip out those variations first.

The goal is to generate a UTC datetime object.


If you just want a basic case that work for UTC with the Z suffix like 2016-06-29T19:36:29.3453Z:

datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")

If you want to handle timezone offsets like 2016-06-29T19:36:29.3453-0400 or 2008-09-03T20:56:35.450686+05:00 use the following. These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500 making it more consistent/easier to parse.

import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )

If your system does not support the %z strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z') then you need to manually offset the time from Z (UTC). Note %z may not work on your system in Python versions < 3 as it depended on the C library support which varies across system/Python build type (i.e., Jython, Cython, etc.).

import re
import datetime

# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)

# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split(r"([+|-])",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
    sign = split_timestamp[1]
    offset = split_timestamp[2]
else:
    sign = None
    offset = None

# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
    # Create timedelta based on offset
    offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))

    # Offset datetime with timedelta
    output_datetime = output_datetime + offset_delta

How to listen for changes to a MongoDB collection?

There is an awesome set of services available called MongoDB Stitch. Look into stitch functions/triggers. Note this is a cloud-based paid service (AWS). In your case, on an insert, you could call a custom function written in javascript.

enter image description here

How do I align a number like this in C?

[I realize this question is a million years old, but there is a deeper question (or two) at its heart, about OP, the pedagogy of programming, and about assumption-making.]

A few people, including a mod, have suggested this is impossible. And, in some--including the most obvious--contexts, it is. But it's interesting to see that that wasn't immediately obvious to the OP.

The impossibility assumes that the contex is running an executable compiled from C on a line-oriented text console (e.g., console+sh or X-term+csh or Terminal+bash), which is a very reasonable assumption. But the fact that the "right" answer ("%8d") wasn't good enough for OP while also being non-obvious suggests that there's a pretty big can of worms nearby...

Consider Curses (and its many variants). In it, you can navigate the "screen", and "move" the cursor around, and "repaint" portions (windows) of text-based output. In a Curses context, it absolutely would be possible to do; i.e., dynamically resize a "window" to accommodate a larger number. But even Curses is just a screen "painting" abstraction. No one suggested it, and probably rightfully so, because a Curses implementation in C doesn't mean it's "strictly C". Fine.

But what does this really mean? In order for the response: "it's impossible" to be correct, it would mean that we're saying something about the runtime system. In other words, this isn't theoretical, (as in, "How do I sort a statically-allocated array of ints?"), which can be explained as a "closed system" that totally ignores any aspect of the runtime.

But, in this case, we have I/O: specifically, the implementation of printf(). But that's where there's an opportunity to have said something more interesting in response (even though, admittedly, the asker was probably not digging quite this deep).

Suppose we use a different set of assumptions. Suppose OP is reasonably "clever" and understands that it would not be possible to to edit previous lines on a line-oriented stream (how would you correct the horizontal position of a character output by a line-printer??). Suppose also, that OP isn't just a kid working on a homework assignment and not realizing it was a "trick" question, intended to tease out an exploration of the meaning of "stream abstraction". Further, let's suppose OP was wondering: "Wait...If C's runtime environment supports the idea of STDOUT--and if STDOUT is just an abstraction--why isn't it just as reasonable to have a terminal abstraction that 1) can vertically scroll but 2) supports a positionable cursor? Both are moving text on a screen."

Because if that were the question we're trying to answer, then you'd only have to look as far as:

ANSI Escape Codes

to see that:

Almost all manufacturers of video terminals added vendor-specific escape sequences to perform operations such as placing the cursor at arbitrary positions on the screen. One example is the VT52 terminal, which allowed the cursor to be placed at an x,y location on the screen by sending the ESC character, a Y character, and then two characters representing with numerical values equal to the x,y location plus 32 (thus starting at the ASCII space character and avoiding the control characters). The Hazeltine 1500 had a similar feature, invoked using ~, DC1 and then the X and Y positions separated with a comma. While the two terminals had identical functionality in this regard, different control sequences had to be used to invoke them.

The first popular video terminal to support these sequences was the Digital VT100, introduced in 1978. This model was very successful in the market, which sparked a variety of VT100 clones, among the earliest and most popular of which was the much more affordable Zenith Z-19 in 1979. Others included the Qume QVT-108, Televideo TVI-970, Wyse WY-99GT as well as optional "VT100" or "VT103" or "ANSI" modes with varying degrees of compatibility on many other brands. The popularity of these gradually led to more and more software (especially bulletin board systems and other online services) assuming the escape sequences worked, leading to almost all new terminals and emulator programs supporting them.

It has been possible, as early as 1978. C itself was "born" in 1972, and the K&R version was established in 1978. If "ANSI" escape sequences were around at that time, then there is an answer "in C" if we're willing to also stipulate: "Well, assuming your terminal is VT100-capable." Incidentally, the consoles which don't support ANSI escapes? You guessed it: Windows & DOS consoles. But on almost every other platform (Unices, Vaxen, Mac OS, Linux) you can expect to.

TL;DR - There is no reasonable answer that can be given without stating assumptions about the runtime environment. Since most runtimes (unless you're using desktop-computer-market-share-of-the-80's-and-90's to calculate 'most') would have, (since the time of the VT-52!), then I don't think it's entirely justified to say that it's impossible--just that in order for it to be possible, it's an entire different order of magnitude of work, and not as simple as %8d...which it kinda seemed like the OP knew about.

We just have to clarify the assumptions.

And lest one thinks that I/O is exceptional, i.e., the only time we need to think about the runtime, (or even the hardware), just dig into IEEE 754 Floating Point exception handling. For those interested:

Intel Floating Point Case Study

According to Professor William Kahan, University of California at Berkeley, a classic case occurred in June 1996. A satellite-lifting rocket named Ariane 5 turned cartwheels shortly after launch and scattered itself and a payload worth over half a billion dollars over a marsh in French Guiana. Kahan found the disaster could be blamed upon a programming language that disregarded the default exception-handling specifications in IEEE 754. Upon launch, sensors reported acceleration so strong that it caused a conversion-to-integer overflow in software intended for recalibration of the rocket’s inertial guidance while on the launching pad.

Pandas DataFrame column to list

You can use pandas.Series.tolist

e.g.:

import pandas as pd
df = pd.DataFrame({'a':[1,2,3], 'b':[4,5,6]})

Run:

>>> df['a'].tolist()

You will get

>>> [1, 2, 3]

Can I try/catch a warning?

I would only recommend using @ to suppress warnings when it's a straight forward operation (e.g. $prop = @($high/($width - $depth)); to skip division by zero warnings). However in most cases it's better to handle.

How to find tag with particular text with Beautiful Soup?

result = soup.find('strong', text='text I am looking for').text

Compare two files line by line and generate the difference in another file

diff(1) is not the answer, but comm(1) is.

NAME
       comm - compare two sorted files line by line

SYNOPSIS
       comm [OPTION]... FILE1 FILE2

...

       -1     suppress lines unique to FILE1

       -2     suppress lines unique to FILE2

       -3     suppress lines that appear in both files

So

comm -2 -3 file1 file2 > file3

The input files must be sorted. If they are not, sort them first. This can be done with a temporary file, or...

comm -2 -3 <(sort file1) <(sort file2) > file3

provided that your shell supports process substitution (bash does).

How to debug a GLSL shader?

At the bottom of this answer is an example of GLSL code which allows to output the full float value as color, encoding IEEE 754 binary32. I use it like follows (this snippet gives out yy component of modelview matrix):

vec4 xAsColor=toColor(gl_ModelViewMatrix[1][1]);
if(bool(1)) // put 0 here to get lowest byte instead of three highest
    gl_FrontColor=vec4(xAsColor.rgb,1);
else
    gl_FrontColor=vec4(xAsColor.a,0,0,1);

After you get this on screen, you can just take any color picker, format the color as HTML (appending 00 to the rgb value if you don't need higher precision, and doing a second pass to get the lower byte if you do), and you get the hexadecimal representation of the float as IEEE 754 binary32.

Here's the actual implementation of toColor():

const int emax=127;
// Input: x>=0
// Output: base 2 exponent of x if (x!=0 && !isnan(x) && !isinf(x))
//         -emax if x==0
//         emax+1 otherwise
int floorLog2(float x)
{
    if(x==0.) return -emax;
    // NOTE: there exist values of x, for which floor(log2(x)) will give wrong
    // (off by one) result as compared to the one calculated with infinite precision.
    // Thus we do it in a brute-force way.
    for(int e=emax;e>=1-emax;--e)
        if(x>=exp2(float(e))) return e;
    // If we are here, x must be infinity or NaN
    return emax+1;
}

// Input: any x
// Output: IEEE 754 biased exponent with bias=emax
int biasedExp(float x) { return emax+floorLog2(abs(x)); }

// Input: any x such that (!isnan(x) && !isinf(x))
// Output: significand AKA mantissa of x if !isnan(x) && !isinf(x)
//         undefined otherwise
float significand(float x)
{
    // converting int to float so that exp2(genType) gets correctly-typed value
    float expo=float(floorLog2(abs(x)));
    return abs(x)/exp2(expo);
}

// Input: x\in[0,1)
//        N>=0
// Output: Nth byte as counted from the highest byte in the fraction
int part(float x,int N)
{
    // All comments about exactness here assume that underflow and overflow don't occur
    const float byteShift=256.;
    // Multiplication is exact since it's just an increase of exponent by 8
    for(int n=0;n<N;++n)
        x*=byteShift;

    // Cut higher bits away.
    // $q \in [0,1) \cap \mathbb Q'.$
    float q=fract(x);

    // Shift and cut lower bits away. Cutting lower bits prevents potentially unexpected
    // results of rounding by the GPU later in the pipeline when transforming to TrueColor
    // the resulting subpixel value.
    // $c \in [0,255] \cap \mathbb Z.$
    // Multiplication is exact since it's just and increase of exponent by 8
    float c=floor(byteShift*q);
    return int(c);
}

// Input: any x acceptable to significand()
// Output: significand of x split to (8,8,8)-bit data vector
ivec3 significandAsIVec3(float x)
{
    ivec3 result;
    float sig=significand(x)/2.; // shift all bits to fractional part
    result.x=part(sig,0);
    result.y=part(sig,1);
    result.z=part(sig,2);
    return result;
}

// Input: any x such that !isnan(x)
// Output: IEEE 754 defined binary32 number, packed as ivec4(byte3,byte2,byte1,byte0)
ivec4 packIEEE754binary32(float x)
{
    int e = biasedExp(x);
    // sign to bit 7
    int s = x<0. ? 128 : 0;

    ivec4 binary32;
    binary32.yzw=significandAsIVec3(x);
    // clear the implicit integer bit of significand
    if(binary32.y>=128) binary32.y-=128;
    // put lowest bit of exponent into its position, replacing just cleared integer bit
    binary32.y+=128*int(mod(float(e),2.));
    // prepare high bits of exponent for fitting into their positions
    e/=2;
    // pack highest byte
    binary32.x=e+s;

    return binary32;
}

vec4 toColor(float x)
{
    ivec4 binary32=packIEEE754binary32(x);
    // Transform color components to [0,1] range.
    // Division is inexact, but works reliably for all integers from 0 to 255 if
    // the transformation to TrueColor by GPU uses rounding to nearest or upwards.
    // The result will be multiplied by 255 back when transformed
    // to TrueColor subpixel value by OpenGL.
    return vec4(binary32)/255.;
}

Replace spaces with dashes and make all letters lower-case

Just use the String replace and toLowerCase methods, for example:

var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"

Notice the g flag on the RegExp, it will make the replacement globally within the string, if it's not used, only the first occurrence will be replaced, and also, that RegExp will match one or more white-space characters.

Preview an image before it is uploaded

THIS IS THE SIMPLEST METHOD


To PREVIEW the image before uploading it to the SERVER from the Browser without using Ajax or any complicated functions.


It needs an "onChange" event to load the image.

_x000D_
_x000D_
function preview() {
    frame.src=URL.createObjectURL(event.target.files[0]);
}
_x000D_
<form>
  <input type="file" onchange="preview()">
  <img id="frame" src="" width="100px" height="100px"/>
</form>
_x000D_
_x000D_
_x000D_

To preview multiple image click here

How do I run a batch file from my Java Application?

To run batch files using java if that's you're talking about...

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);`

This should do it.

How can I copy the content of a branch to a new local branch?

git checkout old_branch
git branch new_branch

This will give you a new branch "new_branch" with the same state as "old_branch".

This command can be combined to the following:

git checkout -b new_branch old_branch

Parse an HTML string with JS

with this simple code you can do that:

let el = $('<div></div>');
$(document.body).append(el);
el.html(`<html><head><title>titleTest</title></head><body><a href='test0'>test01</a><a href='test1'>test02</a><a href='test2'>test03</a></body></html>`);
console.log(el.find('a[href="test0"]'));

What does 'stale file handle' in Linux mean?

When the directory is deleted, the inode for that directory (and the inodes for its contents) are recycled. The pointer your shell has to that directory's inode (and its contents's inodes) are now no longer valid. When the directory is restored from backup, the old inodes are not (necessarily) reused; the directory and its contents are stored on random inodes. The only thing that stays the same is that the parent directory reuses the same name for the restored directory (because you told it to).

Now if you attempt to access the contents of the directory that your original shell is still pointing to, it communicates that request to the file system as a request for the original inode, which has since been recycled (and may even be in use for something entirely different now). So you get a stale file handle message because you asked for some nonexistent data.

When you perform a cd operation, the shell reevaluates the inode location of whatever destination you give it. Now that your shell knows the new inode for the directory (and the new inodes for its contents), future requests for its contents will be valid.

SQL Server CTE and recursion example

I haven't tested your code, just tried to help you understand how it operates in comment;

WITH
  cteReports (EmpID, FirstName, LastName, MgrID, EmpLevel)
  AS
  (
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
-- In a rCTE, this block is called an [Anchor]
-- The query finds all root nodes as described by WHERE ManagerID IS NULL
    SELECT EmployeeID, FirstName, LastName, ManagerID, 1
    FROM Employees
    WHERE ManagerID IS NULL
-->>>>>>>>>>Block 1>>>>>>>>>>>>>>>>>
    UNION ALL
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>    
-- This is the recursive expression of the rCTE
-- On the first "execution" it will query data in [Employees],
-- relative to the [Anchor] above.
-- This will produce a resultset, we will call it R{1} and it is JOINed to [Employees]
-- as defined by the hierarchy
-- Subsequent "executions" of this block will reference R{n-1}
    SELECT e.EmployeeID, e.FirstName, e.LastName, e.ManagerID,
      r.EmpLevel + 1
    FROM Employees e
      INNER JOIN cteReports r
        ON e.ManagerID = r.EmpID
-->>>>>>>>>>Block 2>>>>>>>>>>>>>>>>>
  )
SELECT
  FirstName + ' ' + LastName AS FullName,
  EmpLevel,
  (SELECT FirstName + ' ' + LastName FROM Employees
    WHERE EmployeeID = cteReports.MgrID) AS Manager
FROM cteReports
ORDER BY EmpLevel, MgrID

The simplest example of a recursive CTE I can think of to illustrate its operation is;

;WITH Numbers AS
(
    SELECT n = 1
    UNION ALL
    SELECT n + 1
    FROM Numbers
    WHERE n+1 <= 10
)
SELECT n
FROM Numbers

Q 1) how value of N is getting incremented. if value is assign to N every time then N value can be incremented but only first time N value was initialize.

A1: In this case, N is not a variable. N is an alias. It is the equivalent of SELECT 1 AS N. It is a syntax of personal preference. There are 2 main methods of aliasing columns in a CTE in T-SQL. I've included the analog of a simple CTE in Excel to try and illustrate in a more familiar way what is happening.

--  Outside
;WITH CTE (MyColName) AS
(
    SELECT 1
)
-- Inside
;WITH CTE AS
(
    SELECT 1 AS MyColName
    -- Or
    SELECT MyColName = 1  
    -- Etc...
)

Excel_CTE

Q 2) now here about CTE and recursion of employee relation the moment i add two manager and add few more employee under second manager then problem start. i want to display first manager detail and in the next rows only those employee details will come those who are subordinate of that manager

A2:

Does this code answer your question?

--------------------------------------------
-- Synthesise table with non-recursive CTE
--------------------------------------------
;WITH Employee (ID, Name, MgrID) AS 
(
    SELECT 1,      'Keith',      NULL   UNION ALL
    SELECT 2,      'Josh',       1      UNION ALL
    SELECT 3,      'Robin',      1      UNION ALL
    SELECT 4,      'Raja',       2      UNION ALL
    SELECT 5,      'Tridip',     NULL   UNION ALL
    SELECT 6,      'Arijit',     5      UNION ALL
    SELECT 7,      'Amit',       5      UNION ALL
    SELECT 8,      'Dev',        6   
)
--------------------------------------------
-- Recursive CTE - Chained to the above CTE
--------------------------------------------
,Hierarchy AS
(
    --  Anchor
    SELECT   ID
            ,Name
            ,MgrID
            ,nLevel = 1
            ,Family = ROW_NUMBER() OVER (ORDER BY Name)
    FROM Employee
    WHERE MgrID IS NULL

    UNION ALL
    --  Recursive query
    SELECT   E.ID
            ,E.Name
            ,E.MgrID
            ,H.nLevel+1
            ,Family
    FROM Employee   E
    JOIN Hierarchy  H ON E.MgrID = H.ID
)
SELECT *
FROM Hierarchy
ORDER BY Family, nLevel

Another one sql with tree structure

SELECT ID,space(nLevel+
                    (CASE WHEN nLevel > 1 THEN nLevel ELSE 0 END)
                )+Name
FROM Hierarchy
ORDER BY Family, nLevel

How to make a div with a circular shape?

HTML div elements, unlike SVG circle primitives, are always rectangular.

You could use round corners (i.e. CSS border-radius) to make it look round. On square elements, a value of 50% naturally forms a circle. Use this, or even a SVG inside your HTML:

_x000D_
_x000D_
document.body.innerHTML+='<i></i>'.repeat(4);
_x000D_
i{border-radius:50%;display:inline-block;background:#F48024;}
svg {fill:#F48024;width:60px;height:60px;}
i:nth-of-type(1n){width:30px;height:30px;}
i:nth-of-type(2n){width:60px;height:60px;}
_x000D_
<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
  <circle cx="60" cy="60" r="60"/>
</svg>
_x000D_
_x000D_
_x000D_

How to implement one-to-one, one-to-many and many-to-many relationships while designing tables?

Here are some real-world examples of the types of relationships:

One-to-one (1:1)

A relationship is one-to-one if and only if one record from table A is related to a maximum of one record in table B.

To establish a one-to-one relationship, the primary key of table B (with no orphan record) must be the secondary key of table A (with orphan records).

For example:

CREATE TABLE Gov(
    GID number(6) PRIMARY KEY, 
    Name varchar2(25), 
    Address varchar2(30), 
    TermBegin date,
    TermEnd date
); 

CREATE TABLE State(
    SID number(3) PRIMARY KEY,
    StateName varchar2(15),
    Population number(10),
    SGID Number(4) REFERENCES Gov(GID), 
    CONSTRAINT GOV_SDID UNIQUE (SGID)
);

INSERT INTO gov(GID, Name, Address, TermBegin) 
values(110, 'Bob', '123 Any St', '1-Jan-2009');

INSERT INTO STATE values(111, 'Virginia', 2000000, 110);

One-to-many (1:M)

A relationship is one-to-many if and only if one record from table A is related to one or more records in table B. However, one record in table B cannot be related to more than one record in table A.

To establish a one-to-many relationship, the primary key of table A (the "one" table) must be the secondary key of table B (the "many" table).

For example:

CREATE TABLE Vendor(
    VendorNumber number(4) PRIMARY KEY,
    Name varchar2(20),
    Address varchar2(20),
    City varchar2(15),
    Street varchar2(2),
    ZipCode varchar2(10),
    Contact varchar2(16),
    PhoneNumber varchar2(12),
    Status varchar2(8),
    StampDate date
);

CREATE TABLE Inventory(
    Item varchar2(6) PRIMARY KEY,
    Description varchar2(30),
    CurrentQuantity number(4) NOT NULL,
    VendorNumber number(2) REFERENCES Vendor(VendorNumber),
    ReorderQuantity number(3) NOT NULL
);

Many-to-many (M:M)

A relationship is many-to-many if and only if one record from table A is related to one or more records in table B and vice-versa.

To establish a many-to-many relationship, create a third table called "ClassStudentRelation" which will have the primary keys of both table A and table B.

CREATE TABLE Class(
    ClassID varchar2(10) PRIMARY KEY, 
    Title varchar2(30),
    Instructor varchar2(30), 
    Day varchar2(15), 
    Time varchar2(10)
);

CREATE TABLE Student(
    StudentID varchar2(15) PRIMARY KEY, 
    Name varchar2(35),
    Major varchar2(35), 
    ClassYear varchar2(10), 
    Status varchar2(10)
);  

CREATE TABLE ClassStudentRelation(
    StudentID varchar2(15) NOT NULL,
    ClassID varchar2(14) NOT NULL,
    FOREIGN KEY (StudentID) REFERENCES Student(StudentID), 
    FOREIGN KEY (ClassID) REFERENCES Class(ClassID),
    UNIQUE (StudentID, ClassID)
);

How to remove a package from Laravel using composer?

Normally composer remove used like this is enough:

$ composer remove vendor/package

but if composer package is removed and config cache is not cleaned you cannot clean it, when you try like so

php artisan config:clear

you can get an error In ProviderRepository.php line 208:

Class 'Laracasts\Flash\FlashServiceProvider' not found

this is a dead end, unless you go deleting files

$rm bootstrap/cache/config.php

And this is Laravel 5.6 I'm talking about, not some kind of very old stuff.

It happens usually on automated deployment, when you copy files of a new release on top of old cache. Even if you cleared cache before copying. You end up with old cache and a new composer.json.

Rounded table corners CSS only

Lesson in Table Borders...

NOTE: The HTML/CSS code below should be viewed in IE only. The code will not be rendered correctly in Chrome!

We need to remember that:

  1. A table has a border: its outer boundary (which can also have a border-radius.)

  2. The cells themselves ALSO have borders (which too, can also have a border-radius.)

  3. The table and cell borders can interfere with each other:

    The cell border can pierce through the table border (ie: table boundary).

    To see this effect, amend the CSS style rules in the code below as follows:
    i. table {border-collapse: separate;}
    ii. Delete the style rules which round the corner cells of the table.
    iii. Then play with border-spacing so you can see the interference.

  4. However, the table border and cell borders can be COLLAPSED (using: border-collapse: collapse;).

  5. When they are collapsed, the cell and table borders interfere in a different way:

    i. If the table border is rounded but cell borders remain square, then the cell's shape takes precedence and the table loses its curved corners.

    ii. Conversely, if the corner cell's are curved but the table boundary is square, then you will see an ugly square corner bordering the curvature of the corner cells.

  6. Given that cell's attribute takes precedence, the way to round the table's four corner's then, is by:

    i. Collapsing borders on the table (using: border-collapse: collapse;).

    ii. Setting your desired curvature on the corner cells of the table.
    iii. It does not matter if the table's corner's are rounded (ie: Its border-radius can be zero).

_x000D_
_x000D_
   .zui-table-rounded {_x000D_
    border: 2px solid blue;_x000D_
    /*border-radius: 20px;*/_x000D_
    _x000D_
    border-collapse: collapse;_x000D_
    border-spacing: 0px;_x000D_
   }_x000D_
      _x000D_
   .zui-table-rounded thead th:first-child {_x000D_
    border-radius: 30px 0 0 0;_x000D_
   }_x000D_
   _x000D_
   .zui-table-rounded thead th:last-child {_x000D_
    border-radius: 0 10px 0 0;_x000D_
   }_x000D_
   _x000D_
   .zui-table-rounded tbody tr:last-child td:first-child {_x000D_
    border-radius: 0 0 0 10px;_x000D_
   }_x000D_
   _x000D_
   .zui-table-rounded tbody tr:last-child td:last-child {_x000D_
    border-radius: 0 0 10px 0;_x000D_
   }_x000D_
   _x000D_
   _x000D_
   .zui-table-rounded thead th {_x000D_
    background-color: #CFAD70;_x000D_
   }_x000D_
   _x000D_
   .zui-table-rounded tbody td {_x000D_
    border-top: solid 1px #957030;_x000D_
    background-color: #EED592;_x000D_
   }
_x000D_
   <table class="zui-table-rounded">_x000D_
   <thead>_x000D_
    <tr>_x000D_
     <th>Name</th>_x000D_
     <th>Position</th>_x000D_
     <th>Height</th>_x000D_
     <th>Born</th>_x000D_
     <th>Salary</th>_x000D_
    </tr>_x000D_
   </thead>_x000D_
   <tbody>_x000D_
    <tr>_x000D_
     <td>DeMarcus Cousins</td>_x000D_
     <td>C</td>_x000D_
     <td>6'11"</td>_x000D_
     <td>08-13-1990</td>_x000D_
     <td>$4,917,000</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
     <td>Isaiah Thomas</td>_x000D_
     <td>PG</td>_x000D_
     <td>5'9"</td>_x000D_
     <td>02-07-1989</td>_x000D_
     <td>$473,604</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
     <td>Ben McLemore</td>_x000D_
     <td>SG</td>_x000D_
     <td>6'5"</td>_x000D_
     <td>02-11-1993</td>_x000D_
     <td>$2,895,960</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
     <td>Marcus Thornton</td>_x000D_
     <td>SG</td>_x000D_
     <td>6'4"</td>_x000D_
     <td>05-05-1987</td>_x000D_
     <td>$7,000,000</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
     <td>Jason Thompson</td>_x000D_
     <td>PF</td>_x000D_
     <td>6'11"</td>_x000D_
     <td>06-21-1986</td>_x000D_
     <td>$3,001,000</td>_x000D_
    </tr>_x000D_
   </tbody>_x000D_
  </table>
_x000D_
_x000D_
_x000D_

Postman - How to see request with headers and body data with variables substituted

If, like me, you are still using the browser version (which will be deprecated soon), have you tried the "Code" button?

enter image description here

This should generate a snippet which contains the entire request Postman is firing. You can even choose the language for the snippet. I find it quite handy when I need to debug stuff.

Hope this helps.

How do I find a list of Homebrew's installable packages?

brew help will show you the list of commands that are available.

brew list will show you the list of installed packages. You can also append formulae, for example brew list postgres will tell you of files installed by postgres (providing it is indeed installed).

brew search <search term> will list the possible packages that you can install. brew search post will return multiple packages that are available to install that have post in their name.

brew info <package name> will display some basic information about the package in question.

You can also search http://searchbrew.com or https://brewformulas.org (both sites do basically the same thing)

Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag

React element has to return only one element. You'll have to wrap both of your tags with another element tag.

I can also see that your render function is not returning anything. This is how your component should look like:

var app = React.createClass({
    render () {
        /*React element can only return one element*/
        return (
             <div></div>
        )
    }
})

Also note that you can't use if statements inside of a returned element:

render: function() {
var text = this.state.submitted ? 'Thank you!  Expect a follow up at '+email+' soon!' : 'Enter your email to request early access:';
var style = this.state.submitted ? {"backgroundColor": "rgba(26, 188, 156, 0.4)"} : {};
    if(this.state.submitted==false) {
        return <YourJSX />
    } else {
        return <YourOtherJSX />
    }
},

How to calculate distance between two locations using their longitude and latitude value

If you have two Location Objects Location loc1 and Location loc2 you do

float distance = loc1.distanceTo(loc2);

If you have longitude and latitude values you use the static distanceBetween() function

    float[] results = new float[1];
    Location.distanceBetween(startLatitude, startLongitude,
    endLatitude, endLongitude, results);
    float distance = results[0];

[Vue warn]: Cannot find element

I think sometimes stupid mistakes can give us this error.

<div id="#main"> <--- id with hashtag
    <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>

To

<div id="main"> <--- id without hashtag
    <div id="mainActivity" v-component="{{currentActivity}}" class="activity"></div>
</div>

How to effectively work with multiple files in Vim

I use buffer commands - :bn (next buffer), :bp (previous buffer) :buffers (list open buffers) :b<n> (open buffer n) :bd (delete buffer). :e <filename> will just open into a new buffer.

How do you implement a good profanity filter?

Regarding your "trick the system" subquestion, you can handle that by normalizing both the "bad word" list and the user-entered text before doing your search. e.g., Use a series of regexes (or tr if PHP has it) to convert [z$5] to "s", [4@] to "a", etc., then compare the normalized "bad word" list against the normalized text. Note that the normalization could potentially lead to additional false positives, although I can't think of any actual cases at the moment.

The larger challenge is to come up with something that will let people quote "The pen is mightier than the sword" while blocking "p e n i s".

How to change dot size in gnuplot

The pointsize command scales the size of points, but does not affect the size of dots.

In other words, plot ... with points ps 2 will generate points of twice the normal size, but for plot ... with dots ps 2 the "ps 2" part is ignored.

You could use circular points (pt 7), which look just like dots.

#1214 - The used table type doesn't support FULLTEXT indexes

Simply do the following:

  1. Open your .sql file with Notepad or Notepad ++

  2. Find InnoDB and Replace all (around 87) with MyISAM

  3. Save and now you can import your database with out error.

What is the $? (dollar question mark) variable in shell scripting?

$? is the exit status of a command, such that you can daisy-chain a series of commands.

Example

command1 && command2 && command3

command2 will run if command1's $? yields a success (0) and command3 will execute if $? of command2 will yield a success

Can't get Python to import from a different folder

I believe you need to create a file called __init__.py in the Models directory so that python treats it as a module.

Then you can do:

from Models.user import User

You can include code in the __init__.py (for instance initialization code that a few different classes need) or leave it blank. But it must be there.

What's the difference between text/xml vs application/xml for webservice response

application/xml is seen by svn as binary type whereas text/xml as text file for which a diff can be displayed.

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

in my case it wasn't checked in xcode After installation process ,

you can do that as following : xcode -> Preferences and tap Locations then select , as the followng image

enter image description here

warning: incompatible implicit declaration of built-in function ‘xyz’

In C, using a previously undeclared function constitutes an implicit declaration of the function. In an implicit declaration, the return type is int if I recall correctly. Now, GCC has built-in definitions for some standard functions. If an implicit declaration does not match the built-in definition, you get this warning.

To fix the problem, you have to declare the functions before using them; normally you do this by including the appropriate header. I recommend not to use the -fno-builtin-* flags if possible.

Instead of stdlib.h, you should try:

#include <string.h>

That's where strcpy and strncpy are defined, at least according to the strcpy(2) man page.

The exit function is defined in stdlib.h, though, so I don't know what's going on there.

Check if instance is of a type

The different answers here have two different meanings.

If you want to check whether an instance is of an exact type then

if (c.GetType() == typeof(TForm))

is the way to go.

If you want to know whether c is an instance of TForm or a subclass then use is/as:

if (c is TForm)

or

TForm form = c as TForm;
if (form != null)

It's worth being clear in your mind about which of these behaviour you actually want.

difference between throw and throw new Exception()

The first preserves the original stacktrace:

try { ... }
catch
{
    // Do something.
    throw;
}

The second allows you to change the type of the exception and/or the message and other data:

try { ... } catch (Exception e)
{
    throw new BarException("Something broke!");
}

There's also a third way where you pass an inner exception:

try { ... }
catch (FooException e) {
    throw new BarException("foo", e);
} 

I'd recommend using:

  • the first if you want to do some cleanup in error situation without destroying information or adding information about the error.
  • the third if you want to add more information about the error.
  • the second if you want to hide information (from untrusted users).

How can I make the browser wait to display the page until it's fully loaded?

Don't use display:none. If you do, you will see images resize/reposition when you do the show(). Use visibility:hidden instead and it will lay everything out correctly, but it just won't be visible until you tell it to.

How to convert file to base64 in JavaScript?

Modern ES6 way (async/await)

const toBase64 = file => new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
});

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   console.log(await toBase64(file));
}

Main();

UPD:

If you want to catch errors

async function Main() {
   const file = document.querySelector('#myfile').files[0];
   const result = await toBase64(file).catch(e => Error(e));
   if(result instanceof Error) {
      console.log('Error: ', result.message);
      return;
   }
   //...
}

IE11 Document mode defaults to IE7. How to reset?

If you are a developer, this is what you need to do:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

How can I handle the warning of file_get_contents() function in PHP?

This will try to get the data, if it does not work, it will catch the error and allow you to do anything you need within the catch.

try {
    $content = file_get_contents($site);
} catch(\Exception $e) {
    return 'The file was not found';
}

Reset push notification settings for app

After hours of searching, and no luck with the suggestions above, this worked like to a charm for 3.x+

override func viewDidLoad() {
        super.viewDidLoad()


            requestAuthorization()

}

func requestAuthorization() {

        if #available(iOS 10.0, *) {

            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
                print("Access granted: \(granted.description)")
            }

        } else {
            // Fallback on earlier versions
        }

    }

Return value in SQL Server stored procedure

I can recommend make pre-init of future index value, this is very usefull in a lot of case like multi work, some export e.t.c.

just create additional User_Seq table: with two fields: id Uniq index and SeqVal nvarchar(1)

and create next SP, and generated ID value from this SP and put to new User row!

CREATE procedure [dbo].[User_NextValue]
as
begin
    set NOCOUNT ON


    declare @existingId int = (select isnull(max(UserId)+1, 0)  from dbo.User)

    insert into User_Seq (SeqVal) values ('a')
    declare @NewSeqValue int = scope_identity()     

    if @existingId > @NewSeqValue 
    begin  

        set identity_insert User_Seq  on
        insert into User_Seq (SeqID) values (@existingId)     
        set @NewSeqValue = scope_identity()     
    end

    delete from User_Seq WITH (READPAST)

return @NewSeqValue

end

How to install Flask on Windows?

Install pip as described here: How do I install pip on Windows?

Then do

pip install flask

That installation tutorial is a bit misleading, it refers to actually running it in a production environment.

TypeError: unhashable type: 'numpy.ndarray'

Your variable energies probably has the wrong shape:

>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

And that's what happens if you read columnar data using your approach:

>>> data
array([[  1.,   2.,   3.],
       [  3.,   4.,   5.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
       [ 3.],
       [ 5.],
       [ 8.]])

Probably you can simply use

>>> data[:,0]
array([ 1.,  3.,  5.,  8.])

instead.

(P.S. Your code looks like it's undecided about whether it's data or elementdata. I've assumed it's simply a typo.)

How do I disable fail_on_empty_beans in Jackson?

In Jersey Rest Services just use the JacksonFeatures annotation ...

@JacksonFeatures(serializationDisable = {SerializationFeature.FAIL_ON_EMPTY_BEANS})
public Response getSomething() {
    Object entity = doSomething();
    return Response.ok(entity).build();
}

Directory index forbidden by Options directive

In my case, it's a typo caused this issue:

<VirtualHost *.8080>

should be

<VirtualHost *:8080>

Event when window.location.href changes

I use this script in my extension "Grab Any Media" and work fine ( like youtube case )

var oldHref = document.location.href;

window.onload = function() {

    var
         bodyList = document.querySelector("body")

        ,observer = new MutationObserver(function(mutations) {

            mutations.forEach(function(mutation) {

                if (oldHref != document.location.href) {

                    oldHref = document.location.href;

                    /* Changed ! your code here */

                }

            });

        });

    var config = {
        childList: true,
        subtree: true
    };

    observer.observe(bodyList, config);

};

Purpose of #!/usr/bin/python3 shebang

Actually the determination of what type of file a file is very complicated, so now the operating system can't just know. It can make lots of guesses based on -

  • extension
  • UTI
  • MIME

But the command line doesn't bother with all that, because it runs on a limited backwards compatible layer, from when that fancy nonsense didn't mean anything. If you double click it sure, a modern OS can figure that out- but if you run it from a terminal then no, because the terminal doesn't care about your fancy OS specific file typing APIs.

Regarding the other points. It's a convenience, it's similarly possible to run

python3 path/to/your/script

If your python isn't in the path specified, then it won't work, but we tend to install things to make stuff like this work, not the other way around. It doesn't actually matter if you're under *nix, it's up to your shell whether to consider this line because it's a shellcode. So for example you can run bash under Windows.

You can actually ommit this line entirely, it just mean the caller will have to specify an interpreter. Also don't put your interpreters in nonstandard locations and then try to call scripts without providing an interpreter.

Java ArrayList clear() function

If you in any doubt, have a look at JDK source code

ArrayList.clear() source code:

public void clear() {
    modCount++;

    // Let gc do its work
    for (int i = 0; i < size; i++)
        elementData[i] = null;

    size = 0;
}

You will see that size is set to 0 so you start from 0 position.

Please note that when adding elements to ArrayList, the backend array is extended (i.e. array data is copied to bigger array if needed) in order to be able to add new items. When performing ArrayList.clear() you only remove references to array elements and sets size to 0, however, capacity stays as it was.

Something better than .NET Reflector?

Some others not mentioned here -

  • Mono Cecil: With Cecil, you can load existing managed assemblies, browse all the contained types, modify them on the fly and save back to the disk the modified assembly.

  • Kaliro: This is a tool for exploring the content of applications built using the Microsoft.Net framework.

  • Dotnet IL Editor (DILE): Dotnet IL Editor (DILE) allows disassembling and debugging .NET 1.0/1.1/2.0/3.0/3.5 applications without source code or .pdb files. It can debug even itself or the assemblies of the .NET Framework on IL level.

  • Common Compiler Infrastructure: Microsoft Research Common Compiler Infrastructure (CCI) is a set of libraries and an application programming interface (API) that supports some of the functionality that is common to compilers and related programming tools. CCI is used primarily by applications that create, modify or analyze .NET portable executable (PE) and debug (PDB) files.

Sorting HashMap by values

package com.naveen.hashmap;

import java.util.*;
import java.util.Map.Entry;

public class SortBasedonValues {

    /**
     * @param args
     */
    public static void main(String[] args) {

        HashMap<String, Integer> hm = new HashMap<String, Integer>();
        hm.put("Naveen", 2);
        hm.put("Santosh", 3);
        hm.put("Ravi", 4);
        hm.put("Pramod", 1);
        Set<Entry<String, Integer>> set = hm.entrySet();
        List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(
                set);
        Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> o1,
                    Map.Entry<String, Integer> o2) {
                return o2.getValue().compareTo(o1.getValue());
            }
        });

        for (Entry<String, Integer> entry : list) {
            System.out.println(entry.getValue());

        }

    }
}

Postgres: clear entire database before re-creating / re-populating from bash script

If you want to clean your database named "example_db":

1) Login to another db(for example 'postgres'):

psql postgres

2) Remove your database:

DROP DATABASE example_db;

3) Recreate your database:

CREATE DATABASE example_db;

How do you run a script on login in *nix?

The script ~/.bash_profile is run on login.

How can I call PHP functions by JavaScript?

Try looking at CASSIS. The idea is to mix PHP with JS so both can work on client and server side.