Programs & Examples On #Page size

Resize svg when window is resized in d3.js

In force layouts simply setting the 'height' and 'width' attributes will not work to re-center/move the plot into the svg container. However, there's a very simple answer that works for Force Layouts found here. In summary:

Use same (any) eventing you like.

window.on('resize', resize);

Then assuming you have svg & force variables:

var svg = /* D3 Code */;
var force = /* D3 Code */;    

function resize(e){
    // get width/height with container selector (body also works)
    // or use other method of calculating desired values
    var width = $('#myselector').width(); 
    var height = $('#myselector').height(); 

    // set attrs and 'resume' force 
    svg.attr('width', width);
    svg.attr('height', height);
    force.size([width, height]).resume();
}

In this way, you don't re-render the graph entirely, we set the attributes and d3 re-calculates things as necessary. This at least works when you use a point of gravity. I'm not sure if that's a prerequisite for this solution. Can anyone confirm or deny ?

Cheers, g

Add querystring parameters to link_to

If you want the quick and dirty way and don't worry about XSS attack, use params.merge to keep previous parameters. e.g.

<%= link_to 'Link', params.merge({:per_page => 20}) %>

see: https://stackoverflow.com/a/4174493/445908

Otherwise , check this answer: params.merge and cross site scripting

How can I scale an entire web page with CSS?

 * {
transform: scale(1.1, 1.1)
}

this will transform every element on the page

Map a network drive to be used by a service

You wan't to either change the user that the Service runs under from "System" or find a sneaky way to run your mapping as System.

The funny thing is that this is possible by using the "at" command, simply schedule your drive mapping one minute into the future and it will be run under the System account making the drive visible to your service.

How to make the checkbox unchecked by default always

This is browser specific behavior and is a way for making filling up forms more convenient to users (like reloading the page when an error has been encountered and not losing what they just typed). So there is no sure way to disable this across browsers short of setting the default values on page load using javascript.

Firefox though seems to disable this feature when you specify the header:

Cache-Control: no-store

See this question.

Get index of array element faster than O(n)

If your array has a natural order use binary search.

Use binary search.

Binary search has O(log n) access time.

Here are the steps on how to use binary search,

  • What is the ordering of you array? For example, is it sorted by name?
  • Use bsearch to find elements or indices

Code example

# assume array is sorted by name!

array.bsearch { |each| "Jamie" <=> each.name } # returns element
(0..array.size).bsearch { |n| "Jamie" <=> array[n].name } # returns index

How can I make my website's background transparent without making the content (images & text) transparent too?

I think what's happening, is that, since the wrapper id is relatively position, it just appears on the same position with the body tag, what you should do, is that you can add a Z-index to the wrapper id.

#wrapper {
margin: auto;
text-align: left;
width: 832px;
position: relative;
padding-top: 27px;
z-index: 99; /* added this line */
 }

This should make layers above the transparent body tag.

How to drop columns by name in a data frame

Here is another solution that may be helpful to others. The code below selects a small number of rows and columns from a large data set. The columns are selected as in one of juba's answers except that I use a paste function to select a set of columns with names that are numbered sequentially:

df = read.table(text = "

state county city  region  mmatrix  X1 X2 X3    A1     A2     A3      B1     B2     B3      C1      C2      C3

  1      1     1      1     111010   1  0  0     2     20    200       4      8     12      NA      NA      NA
  1      2     1      1     111010   1  0  0     4     NA    400       5      9     NA      NA      NA      NA
  1      1     2      1     111010   1  0  0     6     60     NA      NA     10     14      NA      NA      NA
  1      2     2      1     111010   1  0  0    NA     80    800       7     11     15      NA      NA      NA

  1      1     3      2     111010   0  1  0     1      2      1       2      2      2      10      20      30
  1      2     3      2     111010   0  1  0     2     NA      1       2      2     NA      40      50      NA
  1      1     4      2     111010   0  1  0     1      1     NA      NA      2      2      70      80      90
  1      2     4      2     111010   0  1  0    NA      2      1       2      2     10     100     110     120

  1      1     1      3     010010   0  0  1    10     20     10     200    200    200       1       2       3
  1      2     1      3     001000   0  0  1    20     NA     10     200    200    200       4       5       9
  1      1     2      3     101000   0  0  1    10     10     NA     200    200    200       7       8      NA
  1      2     2      3     011010   0  0  1    NA     20     10     200    200    200      10      11      12

", sep = "", header = TRUE, stringsAsFactors = FALSE)
df

df2 <- df[df$region == 2, names(df) %in% c(paste("C", seq_along(1:3), sep=''))]
df2

#    C1  C2  C3
# 5  10  20  30
# 6  40  50  NA
# 7  70  80  90
# 8 100 110 120

add a temporary column with a value

I giving you an example in wich the TABLE registrofaena doesn't have the column called minutos. Minutos is created and it content is a result of divide demora/60, in other words, i created a column to show the values of the delay in minutes.

This is the query:

SELECT idfaena,fechahora,demora, demora/60 as minutos,comentario 
FROM registrofaena  
WHERE fecha>='2018-10-17' AND comentario <> '' 
ORDER BY idfaena ASC;

This is the view:

This is the result

Export/import jobs in Jenkins

This does not work for existing jobs, however there is Jenkins job builder.

This allows one to keep job definitions in yaml files and in a git repo which is very portable.

How do I install the yaml package for Python?

pip install pyyaml

If you don't have pip, run easy_install pip to install pip, which is the go-to package installer - Why use pip over easy_install?. If you prefer to stick with easy_install, then easy_install pyyaml

stdlib and colored output in C

Dealing with colour sequences can get messy and different systems might use different Colour Sequence Indicators.

I would suggest you try using ncurses. Other than colour, ncurses can do many other neat things with console UI.

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

Precision and scale are often misunderstood. In numeric(3,2) you want 3 digits overall, but 2 to the right of the decimal. If you want 15 => 15.00 so the leading 1 causes the overflow (since if you want 2 digits to the right of the decimal, there is only room on the left for one more digit). With 4,2 there is no problem because all 4 digits fit.

Should I put input elements inside a label element?

The primary advantage of placing input inside of label is typing efficiency for humans and byte storage for computers.

@Znarkus said in his comment to the OP,

One of the big pros of putting the <input /> inside the <label>, is that you can omit for and id: <label>My text <input /></label> in your example. So much nicer!

Note: In @Znarknus code, another efficiency was included not explicitly stated in the comment. type="text" can also be omitted and input will render a text box by default.

A side by side comparison of keystrokes and bytes[1].

31 keystrokes, 31 bytes

<label>My Text<input /></label>

58 keystrokes, 58 bytes

<label for="myinput">My Text</label><input id="myinput" />

Otherwise, the snippets are visually equal and they offer the same level of user accessibility. A user can click or tap the label to place the cursor in the text box.

[1] Text files (.txt) created in Notepad on Windows, bytes from Windows File Explorer properties

PHP - Get key name of array value

if you need to return an array elements with same value, use array_keys() function

$array = array('red' => 1, 'blue' => 1, 'green' => 2);
print_r(array_keys($array, 1));

Codeigniter $this->db->get(), how do I return values for a specific row?

Accessing a single row

//Result as an Object
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row();
echo $result->age;

//Result as an Array
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row_array();
echo $result['age'];

Is there a keyboard shortcut (hotkey) to open Terminal in macOS?

iTerm2 - an alternative to Terminal - has an option to use configurable system-wide hotkey to show/hide (initially set to Alt+Space, disabled by default)

T-SQL - function with default parameters

You can call it three ways - with parameters, with DEFAULT and via EXECUTE

SET NOCOUNT ON;

DECLARE
@Table  SYSNAME = 'YourTable',
@Schema SYSNAME = 'dbo',
@Rows   INT;

SELECT dbo.TableRowCount( @Table, @Schema )

SELECT dbo.TableRowCount( @Table, DEFAULT )

EXECUTE @Rows = dbo.TableRowCount @Table

SELECT @Rows

Mocking a class: Mock() or patch()?

I've got a YouTube video on this.

Short answer: Use mock when you're passing in the thing that you want mocked, and patch if you're not. Of the two, mock is strongly preferred because it means you're writing code with proper dependency injection.

Silly example:

# Use a mock to test this.
my_custom_tweeter(twitter_api, sentence):
    sentence.replace('cks','x')   # We're cool and hip.
    twitter_api.send(sentence)

# Use a patch to mock out twitter_api. You have to patch the Twitter() module/class 
# and have it return a mock. Much uglier, but sometimes necessary.
my_badly_written_tweeter(sentence):
    twitter_api = Twitter(user="XXX", password="YYY")
    sentence.replace('cks','x') 
    twitter_api.send(sentence)

How to split a String by space

Use Stringutils.split() to split the string by whites paces. For example StringUtils.split("Hello World") returns "Hello" and "World";

In order to solve the mentioned case we use split method like this

String split[]= StringUtils.split("Hello I'm your String");

when we print the split array the output will be :

Hello

I'm

your

String

For complete example demo check here

Search for "does-not-contain" on a DataFrame in pandas

I was having trouble with the not (~) symbol as well, so here's another way from another StackOverflow thread:

df[df["col"].str.contains('this|that')==False]

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.

If you're experiencing a different behaviour, it's time to change for another DBMS.

Oracle PL/SQL : remove "space characters" from a string

To replace one or more white space characters by a single blank you should use {2,} instead of *, otherwise you would insert a blank between all non-blank characters.

REGEXP_REPLACE( my_value, '[[:space:]]{2,}', ' ' )

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

It's been a while since this was posted but I found a more elegant solution if you are not needing to support old browsers.

You can do a check with

performance.navigation.type

Documentation including browser support is here: https://developer.mozilla.org/en-US/docs/Web/API/Performance/navigation

So to see if the page was loaded from history using back you can do

if(performance.navigation.type == 2){
   location.reload(true);
}

The 2 indicates the page was accessed by navigating into the history. Other possibilities are-

0:The page was accessed by following a link, a bookmark, a form submission, or a script, or by typing the URL in the address bar.

1:The page was accessed by clicking the Reload button or via the Location.reload() method.

255: Any other way

These are detailed here: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigation


Note Performance.navigation.type is now deprecated in favour of PerformanceNavigationTiming.type which returns 'navigate' / 'reload' / 'back_forward' / 'prerender': https://developer.mozilla.org/en-US/docs/Web/API/PerformanceNavigationTiming/type

How can I overwrite file contents with new content in PHP?

MY PREFERRED METHOD is using fopen,fwrite and fclose [it will cost less CPU]

$f=fopen('myfile.txt','w');
fwrite($f,'new content');
fclose($f);

Warning for those using file_put_contents

It'll affect a lot in performance, for example [on the same class/situation] file_get_contents too: if you have a BIG FILE, it'll read the whole content in one shot and that operation could take a long waiting time

Using JavaScript to display a Blob

You can also get BLOB object directly from XMLHttpRequest. Setting responseType to blob makes the trick. Here is my code:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/image.jpg");
xhr.responseType = "blob";
xhr.onload = response;
xhr.send();

And the response function looks like this:

function response(e) {
   var urlCreator = window.URL || window.webkitURL;
   var imageUrl = urlCreator.createObjectURL(this.response);
   document.querySelector("#image").src = imageUrl;
}

We just have to make an empty image element in HTML:

<img id="image"/>

UILabel font size?

This worked for me:

sequencerPlayLabel.font = [UIFont fontWithName:kTypeFont size:kTypeFontSize];

-rich

Sorting a Dictionary in place with respect to keys

You can't sort a Dictionary<TKey, TValue> - it's inherently unordered. (Or rather, the order in which entries are retrieved is implementation-specific. You shouldn't rely on it working the same way between versions, as ordering isn't part of its designed functionality.)

You can use SortedList<TKey, TValue> or SortedDictionary<TKey, TValue>, both of which sort by the key (in a configurable way, if you pass an IEqualityComparer<T> into the constructor) - might those be of use to you?

Pay little attention to the word "list" in the name SortedList - it's still a dictionary in that it maps keys to values. It's implemented using a list internally, effectively - so instead of looking up by hash code, it does a binary search. SortedDictionary is similarly based on binary searches, but via a tree instead of a list.

set the iframe height automatically

If the sites are on separate domains, the calling page can't access the height of the iframe due to cross-browser domain restrictions. If you have access to both sites, you may be able to use the [document domain hack].1 Then anroesti's links should help.

Copy output of a JavaScript variable to the clipboard

At the time of writing, setting display:none on the element didn't work for me. Setting the element's width and height to 0 did not work either. So the element has to be at least 1px in width for this to work.

The following example worked in Chrome and Firefox:

    const str = 'Copy me';
    const el = document.createElement("input");
    // Does not work:
    // dummy.style.display = "none";
    el.style.height = '0px';
    // Does not work:
    // el.style.width = '0px';
    el.style.width = '1px';
    document.body.appendChild(el);
    el.value = str;
    el.select();
    document.execCommand("copy");
    document.body.removeChild(el);

I'd like to add that I can see why the browsers are trying to prevent this hackish approach. It's better to openly show the content you are going copy into the user's browser. But sometimes there are design requirements, we can't change.

Array String Declaration

You can write like below. Check out the syntax guidelines in this thread

AClass[] array;
...
array = new AClass[]{object1, object2};

If you find arrays annoying better use ArrayList.

How can I auto hide alert box after it showing it?

impossible with javascript. Just as another alternative to suggestions from other answers: consider using jGrowl: http://archive.plugins.jquery.com/project/jGrowl

Is it possible to decompile an Android .apk file?

Decompilation of APK file is possible. But it might be difficult to understand the code if it is obfuscated.

ApkTool to view resources inside APK File

  • Extracts AndroidManifest.xml and everything in res folder(layout xml files, images, htmls used on webview etc..)
  • command : apktool.bat d sampleApp.apk
  • NOTE: You can achieve this by using zip utility like 7-zip. But, It also extracts the .smali file of all .class files.

Using dex2jar

  • Generates .jar file from .apk file, we need JD-GUI to view the source code from this .jar.
  • command : dex2jar sampleApp.apk

Decompiling .jar using JD-GUI

  • decompiles the .class files (obfuscated- in a case of the android app, but a readable original code is obtained in a case of other .jar file). i.e., we get .java back from the application.

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Usually the problem is not closing brackets (}) or missing semicolon (;)

What is Join() in jQuery?

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

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

will output:

stackoverflow is cool

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

Have you tried moving the reduction step outside the loop? Right now you have a data dependency that really isn't needed.

Try:

  uint64_t subset_counts[4] = {};
  for( unsigned k = 0; k < 10000; k++){
     // Tight unrolled loop with unsigned
     unsigned i=0;
     while (i < size/8) {
        subset_counts[0] += _mm_popcnt_u64(buffer[i]);
        subset_counts[1] += _mm_popcnt_u64(buffer[i+1]);
        subset_counts[2] += _mm_popcnt_u64(buffer[i+2]);
        subset_counts[3] += _mm_popcnt_u64(buffer[i+3]);
        i += 4;
     }
  }
  count = subset_counts[0] + subset_counts[1] + subset_counts[2] + subset_counts[3];

You also have some weird aliasing going on, that I'm not sure is conformant to the strict aliasing rules.

keytool error Keystore was tampered with, or password was incorrect

In my case I was needed to have root access.

Synchronous XMLHttpRequest warning and <script>

UPDATE: This has been fixed in jQuery 3.x. If you have no possibility to upgrade to any version above 3.0, you could use following snippet BUT be aware that now you will lose sync behaviour of script loading in the targeted content.

You could fix it, setting explicitly async option of xhr request to true:

$.ajaxPrefilter(function( options, original_Options, jqXHR ) {
    options.async = true;
});

Location of GlassFish Server Logs

tail -f /path/to/glassfish/domains/YOURDOMAIN/logs/server.log

You can also upload log from admin console : http://yoururl:4848

enter image description here

Python dict how to create key or append an element to key?

You can use a defaultdict for this.

from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')

This is slightly more efficient than setdefault since you don't end up creating new lists that you don't end up using. Every call to setdefault is going to create a new list, even if the item already exists in the dictionary.

Spring Security redirect to previous page after successful login

Back to previous page after succesfull login, we can use following custom authentication manager as follows:

<!-- enable use-expressions -->
    <http auto-config="true" use-expressions="true">
        <!-- src** matches: src/bar.c src/baz.c src/test/bartest.c-->
        <intercept-url pattern="/problemSolution/home/**" access="hasRole('ROLE_ADMIN')"/>
        <intercept-url pattern="favicon.ico" access="permitAll"/>
        <form-login
                authentication-success-handler-ref="authenticationSuccessHandler"
                always-use-default-target="true"
                login-processing-url="/checkUser"
                login-page="/problemSolution/index"

                default-target-url="/problemSolution/home"
                authentication-failure-url="/problemSolution/index?error"
                username-parameter="username"
                password-parameter="password"/>
        <logout logout-url="/problemSolution/logout"
                logout-success-url="/problemSolution/index?logout"/>
        <!-- enable csrf protection -->
        <csrf/>
    </http>

    <beans:bean id="authenticationSuccessHandler"
            class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
        <beans:property name="defaultTargetUrl" value="/problemSolution/home"/>
    </beans:bean>

    <!-- Select users and user_roles from database -->
    <authentication-manager>
        <authentication-provider user-service-ref="customUserDetailsService">
            <password-encoder hash="plaintext">
            </password-encoder>
        </authentication-provider>
    </authentication-manager>

CustomUserDetailsService class

@Service
public class CustomUserDetailsService implements UserDetailsService {

        @Autowired
        private UserService userService;

        public UserDetails loadUserByUsername(String userName)
                        throws UsernameNotFoundException {
                com.codesenior.telif.local.model.User domainUser = userService.getUser(userName);

                boolean enabled = true;
                boolean accountNonExpired = true;
                boolean credentialsNonExpired = true;
                boolean accountNonLocked = true;

                return new User(
                                domainUser.getUsername(),
                                domainUser.getPassword(),
                                enabled,
                                accountNonExpired,
                                credentialsNonExpired,
                                accountNonLocked,
                                getAuthorities(domainUser.getUserRoleList())
                );
        }

        public Collection<? extends GrantedAuthority> getAuthorities(List<UserRole> userRoleList) {
                return getGrantedAuthorities(getRoles(userRoleList));
        }

        public List<String> getRoles(List<UserRole> userRoleList) {

                List<String> roles = new ArrayList<String>();

                for(UserRole userRole:userRoleList){
                        roles.add(userRole.getRole());
                }
                return roles;
        }

        public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
                List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

                for (String role : roles) {
                        authorities.add(new SimpleGrantedAuthority(role));
                }
                return authorities;
        }

}

User Class

import com.codesenior.telif.local.model.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


@Service
public class CustomUserDetailsService implements UserDetailsService {

        @Autowired
        private UserService userService;

        public UserDetails loadUserByUsername(String userName)
                        throws UsernameNotFoundException {
                com.codesenior.telif.local.model.User domainUser = userService.getUser(userName);

                boolean enabled = true;
                boolean accountNonExpired = true;
                boolean credentialsNonExpired = true;
                boolean accountNonLocked = true;

                return new User(
                                domainUser.getUsername(),
                                domainUser.getPassword(),
                                enabled,
                                accountNonExpired,
                                credentialsNonExpired,
                                accountNonLocked,
                                getAuthorities(domainUser.getUserRoleList())
                );
        }

        public Collection<? extends GrantedAuthority> getAuthorities(List<UserRole> userRoleList) {
                return getGrantedAuthorities(getRoles(userRoleList));
        }

        public List<String> getRoles(List<UserRole> userRoleList) {

                List<String> roles = new ArrayList<String>();

                for(UserRole userRole:userRoleList){
                        roles.add(userRole.getRole());
                }
                return roles;
        }

        public static List<GrantedAuthority> getGrantedAuthorities(List<String> roles) {
                List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

                for (String role : roles) {
                        authorities.add(new SimpleGrantedAuthority(role));
                }
                return authorities;
        }

}

UserRole Class

@Entity
public class UserRole {
        @Id
        @GeneratedValue
        private Integer userRoleId;

        private String role;

        @ManyToMany(fetch = FetchType.LAZY, mappedBy = "userRoleList")
        @JsonIgnore
        private List<User> userList;

        public Integer getUserRoleId() {
                return userRoleId;
        }

        public void setUserRoleId(Integer userRoleId) {
                this.userRoleId= userRoleId;
        }

        public String getRole() {
                return role;
        }

        public void setRole(String role) {
                this.role= role;
        }

        @Override
        public String toString() {
                return String.valueOf(userRoleId);
        }

        public List<User> getUserList() {
                return userList;
        }

        public void setUserList(List<User> userList) {
                this.userList= userList;
        }
}

Spring Boot JPA - configuring auto reconnect

The above suggestions did not work for me. What really worked was the inclusion of the following lines in the application.properties

spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 3600000
spring.datasource.validationQuery = SELECT 1

You can find the explanation out here

What is the role of "Flatten" in Keras?

enter image description here This is how Flatten works converting Matrix to single array.

Descending order by date filter in AngularJs

In my case, the orderBy is determined by a select box. I prefer Ludwig's response because you can set the sort direction in the select options as such:

        $scope.options = [
            { label: 'Title', value: 'title' },
            { label: 'Newest', value: '-publish_date' },
            { label: 'Featured', value: '-featured' }
        ]; 

markup:

<select ng-model="orderProp" ng-options="opt as opt.label for opt in options"></select>
<ul>
    <li ng-repeat="item in items | orderBy:orderProp.value"></li>
</ul>

docker run <IMAGE> <MULTIPLE COMMANDS>

You can also pipe commands inside Docker container, bash -c "<command1> | <command2>" for example:

docker run img /bin/bash -c "ls -1 | wc -l"

But, without invoking the shell in the remote the output will be redirected to the local terminal.

Android Studio SDK location

If your project is open click on Gradle Scripts >local.properties(SDK LOCATION), open it and there is the location of sdk with name

sdk.dir=C\:\\Users\\shiva\\AppData\\Local\\Android\\Sdk

Note don't forget the replace \\ to \ before coping the things(sdk location)

Downloading a large file using curl

Find below code if you want to download the contents of the specified URL also want to saves it to a file.

<?php
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,'http://news.google.com/news?hl=en&topic=t&output=rss');

$fp = fopen('rss.xml', 'w+');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);

curl_exec ($ch);

curl_close ($ch);
fclose($fp);
?>

If you want to downloads file from the FTP server you can use php FTP extension. Please find below code:

<?php
$SERVER_ADDRESS="";
$SERVER_USERNAME="";
$SERVER_PASSWORD="";
$conn_id = ftp_connect($SERVER_ADDRESS);

// login with username and password
$login_result = ftp_login($conn_id, $SERVER_USERNAME, $SERVER_PASSWORD);

$server_file="test.pdf" //FTP server file path 
$local_file = "new.pdf"; //Local server file path 

##----- DOWNLOAD $SERVER_FILE AND SAVE TO $LOCAL_FILE--------##
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

ftp_close($conn_id);
?>

What is unit testing and how do you do it?

What exactly IS unit testing? Is it built into code or run as separate programs? Or something else?

From MSDN: The primary goal of unit testing is to take the smallest piece of testable software in the application, isolate it from the remainder of the code, and determine whether it behaves exactly as you expect.

Essentially, you are writing small bits of code to test the individual bits of your code. In the .net world, you would run these small bits of code using something like NUnit or MBunit or even the built in testing tools in visual studio. In Java you might use JUnit. Essentially the test runners will build your project, load and execute the unit tests and then let you know if they pass or fail.

How do you do it?

Well it's easier said than done to unit test. It takes quite a bit of practice to get good at it. You need to structure your code in a way that makes it easy to unit test to make your tests effective.

When should it be done? Are there times or projects not to do it? Is everything unit-testable?

You should do it where it makes sense. Not everything is suited to unit testing. For example UI code is very hard to unit test and you often get little benefit from doing so. Business Layer code however is often very suitable for tests and that is where most unit testing is focused.

Unit testing is a massive topic and to fully get an understanding of how it can best benefit you I'd recommend getting hold of a book on unit testing such as "Test Driven Development by Example" which will give you a good grasp on the concepts and how you can apply them to your code.

Python TypeError must be str not int

you need to cast int to str before concatenating. for that use str(temperature). Or you can print the same output using , if you don't want to convert like this.

print("the furnace is now",temperature , "degrees!")

Formatting text in a TextBlock

This is my solution....

    <TextBlock TextWrapping="Wrap" Style="{DynamicResource InstructionStyle}"> 
        <Run Text="This wizard will take you through the purge process in the correct order." FontWeight="Bold"></Run>
        <LineBreak></LineBreak>
        <Run Text="To Begin, select" FontStyle="Italic"></Run>
        <Run x:Name="InstructionSection" Text="'REPLACED AT RUNTIME'" FontWeight="Bold"></Run>
        <Run Text="from the menu." FontStyle="Italic"></Run>
    </TextBlock>

I am learning... so if anyone has thaughts on the above solution please share! :)

How to make circular background using css?

Maybe you should use a display inline-block too:

.circle {
    display: inline-block;
    height: 25px;
    width: 25px;
    background-color: #bbb;
    border-radius: 50%;
    z-index: -1;
}

Convert varchar2 to Date ('MM/DD/YYYY') in PL/SQL

First you convert VARCHAR to DATE and then back to CHAR. I do this almost every day and never found any better way.

select TO_CHAR(TO_DATE(DOJ,'MM/DD/YYYY'), 'MM/DD/YYYY') from EmpTable

How to dismiss a Twitter Bootstrap popover by clicking outside?

There's an issue with the latest update of the accepted answer: If you have some tooltips enabled and you open a popover and then click on a tooltip-having element, the text of the tooltip will be displayed as a popover to.

To prevent this, just add

 if ($(this).data('bs.popover')) {

inside the if-statement (or add it concatenated with && to the if-statement)

// only show one popover at the time and hide on clicking outside
$(document).on('click', function (e) {
    $('[data-toggle="popover"],[data-original-title]').each(function () {
        //the 'is' for buttons that trigger popups
        //the 'has' for icons within a button that triggers a popup
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            if ($(this).data('bs.popover')) {
                (($(this).popover('hide').data('bs.popover') || {}).inState || {}).click = false  // fix for BS 3.3.6
            }
        }
    });
});

R dates "origin" must be supplied

My R use 1970-01-01:

>as.Date(15103, origin="1970-01-01")
[1] "2011-05-09"

and this matches the calculation from

>as.numeric(as.Date(15103, origin="1970-01-01"))

Convert NVARCHAR to DATETIME in SQL Server 2008

DECLARE @chr nvarchar(50) = (SELECT CONVERT(nvarchar(50), GETDATE(), 103))

SELECT @chr chars, CONVERT(date, @chr, 103) date_again

JSHint and jQuery: '$' is not defined

To fix this error when using the online JSHint implementation:

  • Click "CONFIGURE" (top of the middle column on the page)
  • Enable "jQuery" (under the "ASSUME" section at the bottom)

What is the difference between docker-compose ports vs expose

Ports

The ports section will publish ports on the host. Docker will setup a forward for a specific port from the host network into the container. By default this is implemented with a userspace proxy process (docker-proxy) that listens on the first port, and forwards into the container, which needs to listen on the second point. If the container is not listening on the destination port, you will still see something listening on the host, but get a connection refused if you try to connect to that host port, from the failed forward into your container.

Note, the container must be listening on all network interfaces since this proxy is not running within the container's network namespace and cannot reach 127.0.0.1 inside the container. The IPv4 method for that is to configure your application to listen on 0.0.0.0.

Also note that published ports do not work in the opposite direction. You cannot connect to a service on the host from the container by publishing a port. Instead you'll find docker errors trying to listen to the already-in-use host port.

Expose

Expose is documentation. It sets metadata on the image, and when running, on the container too. Typically you configure this in the Dockerfile with the EXPOSE instruction, and it serves as documentation for the users running your image, for them to know on which ports by default your application will be listening. When configured with a compose file, this metadata is only set on the container. You can see the exposed ports when you run a docker inspect on the image or container.

There are a few tools that rely on exposed ports. In docker, the -P flag will publish all exposed ports onto ephemeral ports on the host. There are also various reverse proxies that will default to using an exposed port when sending traffic to your application if you do not explicitly set the container port.

Other than those external tools, expose has no impact at all on the networking between containers. You only need a common docker network, and connecting to the container port, to access one container from another. If that network is user created (e.g. not the default bridge network named bridge), you can use DNS to connect to the other containers.

How to run .NET Core console app from the command line

Go to ...\bin\Debug\net5.0 (net5.0 can also be something like "netcoreapp2.2" depending on the framework you use.)

enter image description here

Open the power shell by clicking on it like shown in the picture.

Type in powershell: .\yourApp.exe

You don't need dotnet publish just make sure you build it before to include all changes.

codeigniter model error: Undefined property

It solved throung second parameter in Model load:

$this->load->model('user','User');

first parameter is the model's filename, and second it defining the name of model to be used in the controller:

function alluser() 
{
$this->load->model('User');
$result = $this->User->showusers();
}

Convert SQL Server result set into string

DECLARE @result varchar(1000)

SELECT @result = ISNULL(@result, '') + StudentId + ',' FROM Student WHERE condition = xyz

select substring(@result, 0, len(@result) - 1) --trim extra "," at end

How to redirect to action from JavaScript method?

Use the @Url.Action method. This will work and determines the correct route regardless of what IIS server you deploy to.

Example- window.location.href="@Url.Action("Action", "Controller")";

so in the case of the Index action on the Home controller - window.location.href="@Url.Action("Index", "Home")";

Best way to convert list to comma separated string in java

You could count the total length of the string first, and pass it to the StringBuilder constructor. And you do not need to convert the Set first.

Set<String> abc = new HashSet<String>();
abc.add("A");
abc.add("B");
abc.add("C");

String separator = ", ";
int total = abc.size() * separator.length();
for (String s : abc) {
    total += s.length();
}

StringBuilder sb = new StringBuilder(total);
for (String s : abc) {
    sb.append(separator).append(s);
}

String result = sb.substring(separator.length()); // remove leading separator

Can you call Directory.GetFiles() with multiple filters?

Nop... I believe you have to make as many calls as the file types you want.

I would create a function myself taking an array on strings with the extensions I need and then iterate on that array making all the necessary calls. That function would return a generic list of the files matching the extensions I'd sent.

Hope it helps.

HTML5 Pre-resize images before uploading

Correction to above:

<img src="" id="image">
<input id="input" type="file" onchange="handleFiles()">
<script>

function handleFiles()
{
    var filesToUpload = document.getElementById('input').files;
    var file = filesToUpload[0];

    // Create an image
    var img = document.createElement("img");
    // Create a file reader
    var reader = new FileReader();
    // Set the image once loaded into file reader
    reader.onload = function(e)
    {
        img.src = e.target.result;

        var canvas = document.createElement("canvas");
        //var canvas = $("<canvas>", {"id":"testing"})[0];
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);

        var MAX_WIDTH = 400;
        var MAX_HEIGHT = 300;
        var width = img.width;
        var height = img.height;

        if (width > height) {
          if (width > MAX_WIDTH) {
            height *= MAX_WIDTH / width;
            width = MAX_WIDTH;
          }
        } else {
          if (height > MAX_HEIGHT) {
            width *= MAX_HEIGHT / height;
            height = MAX_HEIGHT;
          }
        }
        canvas.width = width;
        canvas.height = height;
        var ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0, width, height);

        var dataurl = canvas.toDataURL("image/png");
        document.getElementById('image').src = dataurl;     
    }
    // Load files into file reader
    reader.readAsDataURL(file);


    // Post the data
    /*
    var fd = new FormData();
    fd.append("name", "some_filename.jpg");
    fd.append("image", dataurl);
    fd.append("info", "lah_de_dah");
    */
}</script>

How to disable anchor "jump" when loading a page?

I think I've found a way for UI Tabs without redoing the functionality. So far I haven't found any problems.

    $( ".tabs" ).tabs();
    $( ".tabs" ).not(".noHash").bind("tabsshow", function(event, ui) { 
        window.location.hash = "tab_"+ui.tab.hash.replace(/#/,"");
        return false;
    });

    var selectedTabHash = window.location.hash.replace(/tab_/,"");
    var index = $( ".tabs li a" ).index($(".tabs li a[href='"+selectedTabHash+"']"));
    $( ".tabs" ).not(".noHash").tabs('select', index);

All within a ready event. It prepends "tab_" for the hash but work both when clicked and page loaded with hash.

jQuery Multiple ID selectors

You can use multiple id's the way you wrote:

$('#upload_link, #upload_link2, #upload_link3')

However, that doesn't mean that those ids exist within the DOM when you've executed your code. It also doesn't mean that upload is a legitimate function. It also doesn't mean that upload has been built in a way that allows for multiple elements in a selection.

upload is a custom jQuery plugin, so you'll have to show what's going on with upload for us to be able to help you.

What is the OAuth 2.0 Bearer Token exactly?

A bearer token is like a currency note e.g 100$ bill . One can use the currency note without being asked any/many questions.

Bearer Token A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).

How to get method parameter names?

In CPython, the number of arguments is

a_method.func_code.co_argcount

and their names are in the beginning of

a_method.func_code.co_varnames

These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython.

One portable way to admit "pass-through" arguments is to define your function with the signature func(*args, **kwargs). This is used a lot in e.g. matplotlib, where the outer API layer passes lots of keyword arguments to the lower-level API.

How to change date format (MM/DD/YY) to (YYYY-MM-DD) in date picker

Thanks for all. I got my expected output

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" type="text/css" media="all">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js"></script>

<script>
$(function(){
        $("#to").datepicker({ dateFormat: 'yy-mm-dd' });
        $("#from").datepicker({ dateFormat: 'yy-mm-dd' }).bind("change",function(){
            var minValue = $(this).val();
            minValue = $.datepicker.parseDate("yy-mm-dd", minValue);
            minValue.setDate(minValue.getDate()+1);
            $("#to").datepicker( "option", "minDate", minValue );
        })
    });

</script> 

<div class="">
    <p>From Date: <input type="text" id="from"></p>

    <p>To Date: <input type="text" id="to"></p>
</div>

Get screen width and height in Android

Full way to do it, that returns the true resolution:

            WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
            Point size = new Point();
            wm.getDefaultDisplay().getRealSize(size);
            final int width = size.x, height = size.y;

And since this can change on different orientation, here's a solution (in Kotlin), to get it right no matter the orientation:

/**
 * returns the natural orientation of the device: Configuration.ORIENTATION_LANDSCAPE or Configuration.ORIENTATION_PORTRAIT .<br></br>
 * The result should be consistent no matter the orientation of the device
 */
@JvmStatic
fun getScreenNaturalOrientation(context: Context): Int {
    //based on : http://stackoverflow.com/a/9888357/878126
    val windowManager = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val config = context.resources.configuration
    val rotation = windowManager.defaultDisplay.rotation
    return if ((rotation == Surface.ROTATION_0 || rotation == Surface.ROTATION_180) && config.orientation == Configuration.ORIENTATION_LANDSCAPE || (rotation == Surface.ROTATION_90 || rotation == Surface.ROTATION_270) && config.orientation == Configuration.ORIENTATION_PORTRAIT)
        Configuration.ORIENTATION_LANDSCAPE
    else
        Configuration.ORIENTATION_PORTRAIT
}

/**
 * returns the natural screen size (in pixels). The result should be consistent no matter the orientation of the device
 */
@JvmStatic
fun getScreenNaturalSize(context: Context): Point {
    val screenNaturalOrientation = getScreenNaturalOrientation(context)
    val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val point = Point()
    wm.defaultDisplay.getRealSize(point)
    val currentOrientation = context.resources.configuration.orientation
    if (currentOrientation == screenNaturalOrientation)
        return point
    else return Point(point.y, point.x)
}

Array slices in C#

static byte[] SliceMe(byte[] source, int length)
{
    byte[] destfoo = new byte[length];
    Array.Copy(source, 0, destfoo, 0, length);
    return destfoo;
}

//

var myslice = SliceMe(sourcearray,41);

BLOB to String, SQL Server

Found this...

bcp "SELECT top 1 BlobText FROM TableName" queryout "C:\DesinationFolder\FileName.txt" -T -c'

If you need to know about different options of bcp flags...

http://msdn.microsoft.com/en-us/library/ms162802.aspx

Bootstrap number validation

It's not Twitter bootstrap specific, it is a normal HTML5 component and you can specify the range with the min and max attributes (in your case only the first attribute). For example:

_x000D_
_x000D_
<div>                       _x000D_
    <input type="number" id="replyNumber" min="0" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

I'm not sure if only integers are allowed by default in the control or not, but else you can specify the step attribute:

_x000D_
_x000D_
<div>                       _x000D_
    <input type="number" id="replyNumber" min="0" step="1" data-bind="value:replyNumber" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Now only numbers higher (and equal to) zero can be used and there is a step of 1, which means the values are 0, 1, 2, 3, 4, ... .

BE AWARE: Not all browsers support the HTML5 features, so it's recommended to have some kind of JavaScript fallback (and in your back-end too) if you really want to use the constraints.

For a list of browsers that support it, you can look at caniuse.com.

How do I authenticate a WebClient request?

Public Function getWeb(ByRef sURL As String) As String
    Dim myWebClient As New System.Net.WebClient()

    Try
        Dim myCredentialCache As New System.Net.CredentialCache()
        Dim myURI As New Uri(sURL)
        myCredentialCache.Add(myURI, "ntlm", System.Net.CredentialCache.DefaultNetworkCredentials)
        myWebClient.Encoding = System.Text.Encoding.UTF8
        myWebClient.Credentials = myCredentialCache
        Return myWebClient.DownloadString(myURI)
    Catch ex As Exception
        Return "Exception " & ex.ToString()
    End Try
End Function

Sorting dictionary keys in python

[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]

Round number to nearest integer

round(value,significantDigit) is the ordinary solution, however this does not operate as one would expect from a math perspective when round values ending in 5. If the 5 is in the digit just after the one you're rounded to, these values are only sometimes rounded up as expected (i.e. 8.005 rounding to two decimal digits gives 8.01). For certain values due to the quirks of floating point math, they are rounded down instead!

i.e.

>>> round(1.0005,3)
1.0
>>> round(2.0005,3)
2.001
>>> round(3.0005,3)
3.001
>>> round(4.0005,3)
4.0
>>> round(1.005,2)
1.0
>>> round(5.005,2)
5.0
>>> round(6.005,2)
6.0
>>> round(7.005,2)
7.0
>>> round(3.005,2)
3.0
>>> round(8.005,2)
8.01

Weird.

Assuming your intent is to do the traditional rounding for statistics in the sciences, this is a handy wrapper to get the round function working as expected needing to import extra stuff like Decimal.

>>> round(0.075,2)

0.07

>>> round(0.075+10**(-2*5),2)

0.08

Aha! So based on this we can make a function...

def roundTraditional(val,digits):
   return round(val+10**(-len(str(val))-1), digits)

Basically this adds a value guaranteed to be smaller than the least given digit of the string you're trying to use round on. By adding that small quantity it preserve's round's behavior in most cases, while now ensuring if the digit inferior to the one being rounded to is 5 it rounds up, and if it is 4 it rounds down.

The approach of using 10**(-len(val)-1) was deliberate, as it the largest small number you can add to force the shift, while also ensuring that the value you add never changes the rounding even if the decimal . is missing. I could use just 10**(-len(val)) with a condiditional if (val>1) to subtract 1 more... but it's simpler to just always subtract the 1 as that won't change much the applicable range of decimal numbers this workaround can properly handle. This approach will fail if your values reaches the limits of the type, this will fail, but for nearly the entire range of valid decimal values it should work.

You can also use the decimal library to accomplish this, but the wrapper I propose is simpler and may be preferred in some cases.


Edit: Thanks Blckknght for pointing out that the 5 fringe case occurs only for certain values. Also an earlier version of this answer wasn't explicit enough that the odd rounding behavior occurs only when the digit immediately inferior to the digit you're rounding to has a 5.

How to execute a Ruby script in Terminal?

Assuming ruby interpreter is in your PATH (it should be), you simply run

ruby your_file.rb

How to call same method for a list of objects?

It seems like there would be a more Pythonic way of doing this, but I haven't found it yet.

I use "map" sometimes if I'm calling the same function (not a method) on a bunch of objects:

map(do_something, a_list_of_objects)

This replaces a bunch of code that looks like this:

 do_something(a)
 do_something(b)
 do_something(c)
 ...

But can also be achieved with a pedestrian "for" loop:

  for obj in a_list_of_objects:
       do_something(obj)

The downside is that a) you're creating a list as a return value from "map" that's just being throw out and b) it might be more confusing that just the simple loop variant.

You could also use a list comprehension, but that's a bit abusive as well (once again, creating a throw-away list):

  [ do_something(x) for x in a_list_of_objects ]

For methods, I suppose either of these would work (with the same reservations):

map(lambda x: x.method_call(), a_list_of_objects)

or

[ x.method_call() for x in a_list_of_objects ]

So, in reality, I think the pedestrian (yet effective) "for" loop is probably your best bet.

Convert DataTable to CSV stream

I don't know if this converted from VB to C# ok but if you don't want quotes around your numbers, you might compare the data type as follows..

public string DataTableToCSV(DataTable dt)
{
    StringBuilder sb = new StringBuilder();
    if (dt == null)
        return "";

    try {
        // Create the header row
        for (int i = 0; i <= dt.Columns.Count - 1; i++) {
            // Append column name in quotes
            sb.Append("\"" + dt.Columns[i].ColumnName + "\"");
            // Add carriage return and linefeed if last column, else add comma
            sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
        }


        foreach (DataRow row in dt.Rows) {
            for (int i = 0; i <= dt.Columns.Count - 1; i++) {
                // Append value in quotes
                //sb.Append("""" & row.Item(i) & """")

                // OR only quote items that that are equivilant to strings
                sb.Append(object.ReferenceEquals(dt.Columns[i].DataType, typeof(string)) || object.ReferenceEquals(dt.Columns[i].DataType, typeof(char)) ? "\"" + row[i] + "\"" : row[i]);

                // Append CR+LF if last field, else add Comma
                sb.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
            }
        }
        return sb.ToString;
    } catch (Exception ex) {
        // Handle the exception however you want
        return "";
    }

}

Is it possible to force row level locking in SQL Server?

Use the ALLOW_PAGE_LOCKS clause of ALTER/CREATE INDEX:

ALTER INDEX indexname ON tablename SET (ALLOW_PAGE_LOCKS = OFF);

Null or empty check for a string variable

Yes, you could also use COALESCE(@value,'')='' which is based on the ANSI SQL standard:

SELECT CASE WHEN COALESCE(@value,'')='' 
    THEN 'Yes, it is null or empty' ELSE 'No, not null or empty' 
    END AS IsNullOrEmpty

DEMO

How to check if my string is equal to null?

You have to check with null if(str != null).

How to compile C program on command line using MinGW?

Instead of setting the %PATH% you may enter your msys shell. In standard msys and mingw installation gcc is in path, so you can run gcc or which gcc.

I have a batch file sh.bat on my Windows 7, in %PATH%:

C:\lang\msys\bin\sh.exe --login %*

Whenever I want to use gcc I enter cmd, then sh, then gcc. I find it very convenient.

When working with linux originated software avoid spaced directories like Program Files. Install them rather to Program_Files. The same regards to tools that you may want to run from msys environment.

How to prevent long words from breaking my div?

I just found out about hyphenator from this question. That might solve the problem.

Import pfx file into particular certificate store from command line

Here is the complete code, import pfx, add iis website, add ssl binding:

$SiteName = "MySite"
$HostName = "localhost"
$CertificatePassword = '1234'
$SiteFolder = Join-Path -Path 'C:\inetpub\wwwroot' -ChildPath $SiteName
$certPath = 'c:\cert.pfx'


Write-Host 'Import pfx certificate' $certPath
$certRootStore = “LocalMachine”
$certStore = "My"
$pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import($certPath,$CertificatePassword,"Exportable,PersistKeySet") 
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store($certStore,$certRootStore) 
$store.Open('ReadWrite')
$store.Add($pfx) 
$store.Close() 
$certThumbprint = $pfx.Thumbprint


Write-Host 'Add website' $SiteName
New-WebSite -Name $SiteName -PhysicalPath $SiteFolder -Force
$IISSite = "IIS:\Sites\$SiteName"
Set-ItemProperty $IISSite -name  Bindings -value @{protocol="https";bindingInformation="*:443:$HostName"}
if($applicationPool) { Set-ItemProperty $IISSite -name  ApplicationPool -value $IISApplicationPool }


Write-Host 'Bind certificate with Thumbprint' $certThumbprint
$obj = get-webconfiguration "//sites/site[@name='$SiteName']"
$binding = $obj.bindings.Collection[0]
$method = $binding.Methods["AddSslCertificate"]
$methodInstance = $method.CreateInstance()
$methodInstance.Input.SetAttributeValue("certificateHash", $certThumbprint)
$methodInstance.Input.SetAttributeValue("certificateStoreName", $certStore)
$methodInstance.Execute()

Transparent background in JPEG image

JPG does not support a transparent background, you can easily convert it to a PNG which does support a transparent background by opening it in near any photo editor and save it as a.PNG

Making heatmap from pandas DataFrame

You want matplotlib.pcolor:

import numpy as np 
from pandas import DataFrame
import matplotlib.pyplot as plt

index = ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
columns = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=index, columns=columns)

plt.pcolor(df)
plt.yticks(np.arange(0.5, len(df.index), 1), df.index)
plt.xticks(np.arange(0.5, len(df.columns), 1), df.columns)
plt.show()

This gives:

Output sample

Capturing a single image from my webcam in Java or Python

It can be done by using ecapture First, run

pip install ecapture

Then in a new python script type:

    from ecapture import ecapture as ec

    ec.capture(0,"test","img.jpg")

More information from thislink

How do I restart a service on a remote machine in Windows?

One way would be to enable telnet server on the machin you want to control services on (add/remove windows components)

Open dos prompt
Type telnet yourmachineip/name
Log on
type net start &serviceName* e.g. w3svc

This will start IIS or you can use net stop to stop a service.

Depending on your setup you need to look at a way of securing the telnet connection as I think its unencrypted.

How does an SSL certificate chain bundle work?

The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2

This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.

See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.

But I still don't know why they wrote the spec so that the order matters.

Why use Select Top 100 Percent?

TOP (100) PERCENT is completely meaningless in recent versions of SQL Server, and it (along with the corresponding ORDER BY, in the case of a view definition or derived table) is ignored by the query processor.

You're correct that once upon a time, it could be used as a trick, but even then it wasn't reliable. Sadly, some of Microsoft's graphical tools put this meaningless clause in.

As for why this might appear in dynamic SQL, I have no idea. You're correct that there's no reason for it, and the result is the same without it (and again, in the case of a view definition or derived table, without both the TOP and ORDER BY clauses).

mssql '5 (Access is denied.)' error during restoring database

The fix for me was to go into Options when trying to Restore the database and change the path to the new path. Here is the screenshot

Return rows in random order

SQL Server / MS Access Syntax:

SELECT TOP 1 * FROM table_name ORDER BY RAND()

MySQL Syntax:

SELECT * FROM table_name ORDER BY RAND() LIMIT 1

Can Google Chrome open local links?

It's not really an anwser but a workaround to open a local link in chrome using python.

Copy the local link you want to run then run the code bellow (using a shortcut), it will open your link.

import win32clipboard
import os

win32clipboard.OpenClipboard()
clipboard_data= win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()

os.system("start "+clipboard_data)

Oracle: Call stored procedure inside the package

You're nearly there, just take out the EXECUTE:

DECLARE
  procId NUMBER;

BEGIN
  PKG1.INIT(1143824, 0, procId);
  DBMS_OUTPUT.PUT_LINE(procId);
END;

Align vertically using CSS 3

a couple ways:

1. Absolute positioning-- you need to have a declared height to make this work:

<div>
   <div class='center'>Hey</div>
</div>

div {height: 100%; width: 100%; position: relative}
div.center {
     width: 100px;
     height: 100px;
     top: 50%;
     margin-top: -50px;
}

*2. Use display: table http://jsfiddle.net/B7CpL/2/ *

<div>
     <img src="/img.png" />
     <div class="text">text centered with image</div>
</div>


div {
     display: table;
     vertical-align: middle
}

div img,
div.text {
     display: table-cell;
     vertical-align: middle
}
  1. A more detailed tutorial using display: table

http://css-tricks.com/vertically-center-multi-lined-text/

'if' statement in jinja2 template

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

How do I apply a perspective transform to a UIView?

You can only use Core Graphics (Quartz, 2D only) transforms directly applied to a UIView's transform property. To get the effects in coverflow, you'll have to use CATransform3D, which are applied in 3-D space, and so can give you the perspective view you want. You can only apply CATransform3Ds to layers, not views, so you're going to have to switch to layers for this.

Check out the "CovertFlow" sample that comes with Xcode. It's mac-only (ie not for iPhone), but a lot of the concepts transfer well.

How do I trim whitespace from a string?

As pointed out in answers above

my_string.strip()

will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space .

For more flexibility use the following

  • Removes only leading whitespace chars: my_string.lstrip()
  • Removes only trailing whitespace chars: my_string.rstrip()
  • Removes specific whitespace chars: my_string.strip('\n') or my_string.lstrip('\n\r') or my_string.rstrip('\n\t') and so on.

More details are available in the docs.

Java's L number (long) specification

By default any integral primitive data type (byte, short, int, long) will be treated as int type by java compiler. For byte and short, as long as value assigned to them is in their range, there is no problem and no suffix required. If value assigned to byte and short exceeds their range, explicit type casting is required.

Ex:

byte b = 130; // CE: range is exceeding.

to overcome this perform type casting.

byte b = (byte)130; //valid, but chances of losing data is there.

In case of long data type, it can accept the integer value without any hassle. Suppose we assign like

Long l = 2147483647; //which is max value of int

in this case no suffix like L/l is required. By default value 2147483647 is considered by java compiler is int type. Internal type casting is done by compiler and int is auto promoted to Long type.

Long l = 2147483648; //CE: value is treated as int but out of range 

Here we need to put suffix as L to treat the literal 2147483648 as long type by java compiler.

so finally

Long l = 2147483648L;// works fine.

Redirecting 404 error with .htaccess via 301 for SEO etc

You will need to know something about the URLs, like do they have a specific directory or some query string element because you have to match for something. Otherwise you will have to redirect on the 404. If this is what is required then do something like this in your .htaccess:

ErrorDocument 404 /index.php

An error page redirect must be relative to root so you cannot use www.mydomain.com.

If you have a pattern to match too then use 301 instead of 302 because 301 is permanent and 302 is temporary. A 301 will get the old URLs removed from the search engines and the 302 will not.

Mod Rewrite Reference: http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html

Is there any way to install Composer globally on Windows?

I use Composer-Setup.exe and it works fine. Just in case you need to know where is the composer.phar (to use with PhpStorm) :

C:\ProgramData\ComposerSetup\bin\composer.phar

addEventListener vs onclick

Using inline handlers is incompatible with Content Security Policy so the addEventListener approach is more secure from that point of view. Of course you can enable the inline handlers with unsafe-inline but, as the name suggests, it's not safe as it brings back the whole hordes of JavaScript exploits that CSP prevents.

How to programmatically log out from Facebook SDK 3.0 without using Facebook login/logout button?

Facebook provides two ways to login and logout from an account. One is to use LoginButton and the other is to use LoginManager. LoginButton is just a button which on clicked, the logging in is accomplished. On the other side LoginManager does this on its own. In your case you have use LoginManager to logout automatically.

LoginManager.getInstance().logout() does this work for you.

The requested operation cannot be performed on a file with a user-mapped section open

I am a developer and do not like apps injected to Registery like Unlocker. I used SysInternals Process Explorer which process locked my dll Find > Find Handle or Dll [Ctrl-F] and killed the process.

Can I make dynamic styles in React Native?

Here is what worked for me:

render() {
  const { styleValue } = this.props;
  const dynamicStyleUpdatedFromProps = {
    height: styleValue,
    width: styleValue,
    borderRadius: styleValue,
  }

  return (
    <View style={{ ...styles.staticStyleCreatedFromStyleSheet, ...dynamicStyleUpdatedFromProps }} />
  );
}

For some reason, this was the only way that mine would update properly.

Possible heap pollution via varargs parameter

When you declare

public static <T> void foo(List<T>... bar) the compiler converts it to

public static <T> void foo(List<T>[] bar) then to

public static void foo(List[] bar)

The danger then arises that you'll mistakenly assign incorrect values into the list and the compiler will not trigger any error. For example, if T is a String then the following code will compile without error but will fail at runtime:

// First, strip away the array type (arrays allow this kind of upcasting)
Object[] objectArray = bar;

// Next, insert an element with an incorrect type into the array
objectArray[0] = Arrays.asList(new Integer(42));

// Finally, try accessing the original array. A runtime error will occur
// (ClassCastException due to a casting from Integer to String)
T firstElement = bar[0].get(0);

If you reviewed the method to ensure that it doesn't contain such vulnerabilities then you can annotate it with @SafeVarargs to suppress the warning. For interfaces, use @SuppressWarnings("unchecked").

If you get this error message:

Varargs method could cause heap pollution from non-reifiable varargs parameter

and you are sure that your usage is safe then you should use @SuppressWarnings("varargs") instead. See Is @SafeVarargs an appropriate annotation for this method? and https://stackoverflow.com/a/14252221/14731 for a nice explanation of this second kind of error.

References:

ssh server connect to host xxx port 22: Connection timed out on linux-ubuntu

Update the security group of that instance. Your local IP must have updated. Every time it’s IP flips. You will have to go update the Security group.

Synchronization vs Lock

I am wondering which one of these is better in practice and why?

I've found that Lock and Condition (and other new concurrent classes) are just more tools for the toolbox. I could do most everything I needed with my old claw hammer (the synchronized keyword), but it was awkward to use in some situations. Several of those awkward situations became much simpler once I added more tools to my toolbox: a rubber mallet, a ball-peen hammer, a prybar, and some nail punches. However, my old claw hammer still sees its share of use.

I don't think one is really "better" than the other, but rather each is a better fit for different problems. In a nutshell, the simple model and scope-oriented nature of synchronized helps protect me from bugs in my code, but those same advantages are sometimes hindrances in more complex scenarios. Its these more complex scenarios that the concurrent package was created to help address. But using this higher level constructs requires more explicit and careful management in the code.

===

I think the JavaDoc does a good job of describing the distinction between Lock and synchronized (the emphasis is mine):

Lock implementations provide more extensive locking operations than can be obtained using synchronized methods and statements. They allow more flexible structuring, may have quite different properties, and may support multiple associated Condition objects.

...

The use of synchronized methods or statements provides access to the implicit monitor lock associated with every object, but forces all lock acquisition and release to occur in a block-structured way: when multiple locks are acquired they must be released in the opposite order, and all locks must be released in the same lexical scope in which they were acquired.

While the scoping mechanism for synchronized methods and statements makes it much easier to program with monitor locks, and helps avoid many common programming errors involving locks, there are occasions where you need to work with locks in a more flexible way. For example, **some algorithms* for traversing concurrently accessed data structures require the use of "hand-over-hand" or "chain locking": you acquire the lock of node A, then node B, then release A and acquire C, then release B and acquire D and so on. Implementations of the Lock interface enable the use of such techniques by allowing a lock to be acquired and released in different scopes, and allowing multiple locks to be acquired and released in any order.

With this increased flexibility comes additional responsibility. The absence of block-structured locking removes the automatic release of locks that occurs with synchronized methods and statements. In most cases, the following idiom should be used:

...

When locking and unlocking occur in different scopes, care must be taken to ensure that all code that is executed while the lock is held is protected by try-finally or try-catch to ensure that the lock is released when necessary.

Lock implementations provide additional functionality over the use of synchronized methods and statements by providing a non-blocking attempt to acquire a lock (tryLock()), an attempt to acquire the lock that can be interrupted (lockInterruptibly(), and an attempt to acquire the lock that can timeout (tryLock(long, TimeUnit)).

...

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

AST_NODE* Statement(AST_NODE* node)

is missing a semicolon (a major clue was the error message "In function ‘Statement’: ...") and so is line 24,

   return node

(Once you fix those, you will encounter other problems, some of which are mentioned by others here.)

JSON.parse vs. eval()

All JSON.parse implementations most likely use eval()

JSON.parse is based on Douglas Crockford's solution, which uses eval() right there on line 497.

// In the third stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

j = eval('(' + text + ')');

The advantage of JSON.parse is that it verifies the argument is correct JSON syntax.

What are best practices for REST nested resources?

I've moved what I've done from the question to an answer where more people are likely to see it.

What I've done is to have the creation endpoints at the nested endpoint, The canonical endpoint for modifying or querying an item is not at the nested resource.

So in this example (just listing the endpoints that change a resource)

  • POST /companies/ creates a new company returns a link to the created company.
  • POST /companies/{companyId}/departments when a department is put creates the new department returns a link to /departments/{departmentId}
  • PUT /departments/{departmentId} modifies a department
  • POST /departments/{deparmentId}/employees creates a new employee returns a link to /employees/{employeeId}

So there are root level resources for each of the collections. However the create is in the owning object.

What is the difference between fastcgi and fpm?

FPM is a process manager to manage the FastCGI SAPI (Server API) in PHP.

Basically, it replaces the need for something like SpawnFCGI. It spawns the FastCGI children adaptively (meaning launching more if the current load requires it).

Otherwise, there's not much operating difference between it and FastCGI (The request pipeline from start of request to end is the same). It's just there to make implementing it easier.

Storing Images in DB - Yea or Nay?

The problem with storing only filepaths to images in a database is that the database's integrity can no longer be forced.

If the actual image pointed to by the filepath becomes unavailable, the database unwittingly has an integrity error.

Given that the images are the actual data being sought after, and that they can be managed easier (the images won't suddenly disappear) in one integrated database rather than having to interface with some kind of filesystem (if the filesystem is independently accessed, the images MIGHT suddenly "disappear"), I'd go for storing them directly as a BLOB or such.

How to convert an image to base64 encoding?

Easy:

$imagedata = file_get_contents("/path/to/image.jpg");
             // alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);

bear in mind that this will enlarge the data by 33%, and you'll have problems with files whose size exceed your memory_limit.

What is the difference between VFAT and FAT32 file systems?

FAT32 along with FAT16 and FAT12 are File System Types, but vfat along with umsdos and msdos are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos driver don't have long filenames (they are 8.3 format). vfat is the most common driver for mounting FAT32 file systems nowadays.

Source: this wikipedia article

Output of commands like df and lsblk indeed show vfat as the File System Type. But sudo file -sL /dev/<partition> shows FAT (32 bit) if a File System is FAT32.

You can confirm vfat is a module and not a File System Type by running modinfo vfat.

Only read selected columns

You could also use JDBC to achieve this. Let's create a sample csv file.

write.table(x=mtcars, file="mtcars.csv", sep=",", row.names=F, col.names=T) # create example csv file

Download and save the the CSV JDBC driver from this link: http://sourceforge.net/projects/csvjdbc/files/latest/download

> library(RJDBC)

> path.to.jdbc.driver <- "jdbc//csvjdbc-1.0-18.jar"
> drv <- JDBC("org.relique.jdbc.csv.CsvDriver", path.to.jdbc.driver)
> conn <- dbConnect(drv, sprintf("jdbc:relique:csv:%s", getwd()))

> head(dbGetQuery(conn, "select * from mtcars"), 3)
   mpg cyl disp  hp drat    wt  qsec vs am gear carb
1   21   6  160 110  3.9  2.62 16.46  0  1    4    4
2   21   6  160 110  3.9 2.875 17.02  0  1    4    4
3 22.8   4  108  93 3.85  2.32 18.61  1  1    4    1

> head(dbGetQuery(conn, "select mpg, gear from mtcars"), 3)
   MPG GEAR
1   21    4
2   21    4
3 22.8    4

Get type of a generic parameter in Java with reflection

Actually I got this to work. Consider the following snippet:

Method m;
Type[] genericParameterTypes = m.getGenericParameterTypes();
for (int i = 0; i < genericParameterTypes.length; i++) {
     if( genericParameterTypes[i] instanceof ParameterizedType ) {
                Type[] parameters = ((ParameterizedType)genericParameterTypes[i]).getActualTypeArguments();
//parameters[0] contains java.lang.String for method like "method(List<String> value)"

     }
 }

I'm using jdk 1.6

MySQL Select Multiple VALUES

Try or:

WHERE id = 3 or id = 4

Or the equivalent in:

WHERE id in (3,4)

How to create Windows EventLog source from command line?

If someone is interested, it is also possible to create an event source manually by adding some registry values.

Save the following lines as a .reg file, then import it to registry by double clicking it:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application\YOUR_EVENT_SOURCE_NAME_GOES_HERE]
"EventMessageFile"="C:\\Windows\\Microsoft.NET\\Framework64\\v4.0.30319\\EventLogMessages.dll"
"TypesSupported"=dword:00000007

This creates an event source named YOUR_EVENT_SOURCE_NAME_GOES_HERE.

Append text to textarea with javascript

Tray to add text with html value to textarea but it wil not works

value :

$(document).on('click', '.edit_targets_btn', function() {
            $('#add_edit_targets').modal('show');
            $('#add_edit_targets_form')[0].reset();
            $('#targets_modal_title').text('Doel bijwerken');
            $('#action').val('targets_update');
            $('#targets_submit_btn').val('Opslaan');

            $('#callcenter_targets_id').val($(this).attr("callcenter_targets_id"));
            $('#targets_title').val($(this).attr("title"));
            $("#targets_content").append($(this).attr("content"));

            tinymce.init({
                selector: '#targets_content',
                setup: function (editor) {
                    editor.on('change', function () {
                        tinymce.triggerSave();
                    });
                },
                browser_spellcheck : true,
                plugins: ['advlist autolink lists image charmap print preview anchor', 'searchreplace visualblocks code fullscreen', 'insertdatetime media table paste code help wordcount', 'autoresize'],
                toolbar: 'undo redo | formatselect | ' + ' bold italic backcolor | alignleft aligncenter ' + ' alignright alignjustify | bullist numlist outdent indent |' + ' removeformat | image | help',
                relative_urls : false,
                remove_script_host : false,
                image_list: [<?php $stmt = $db->query('SELECT * FROM images WHERE users_id = ' . $get_user_users_id); foreach ($stmt as $row) { ?>{title: '<?=$row['name']?>', value: '<?=$imgurl?>/image_uploads/<?=$row['src']?>'},<?php } ?>],
                min_height: 250,
                branding: false
            });
        });

React Native: Getting the position of an element

If you use function components and don't want to use a forwardRef to measure your component's absolute layout, you can get a reference to it from the LayoutChangeEvent in the onLayout callback.

This way, you can get the absolute position of the element:

<MyFunctionComp
  onLayout={(event) => {
    event.target.measure(
      (x, y, width, height, pageX, pageX) => {
        doSomethingWithAbsolutePosition({
          x: x + pageX, 
          y: y + pageY,
        });
      },
    );
  }}
/>

Tested with React Native 0.63.3.

eslint: error Parsing error: The keyword 'const' is reserved

ESLint defaults to ES5 syntax-checking. You'll want to override to the latest well-supported version of JavaScript.

Try adding a .eslintrc file to your project. Inside it:

{
    "parserOptions": {
        "ecmaVersion": 2017
    },

    "env": {
        "es6": true
    }
}

Hopefully this helps.

EDIT: I also found this example .eslintrc which might help.

What is .Net Framework 4 extended?

It's the part of the .NET Framework that isn't contained within the Client Profile. See MSDN for more info; specifically:

The .NET Framework is made up of the .NET Framework 4 Client Profile and .NET Framework 4 Extended components that exist separately in Programs and Features.

Why do we have to specify FromBody and FromUri?

When the ASP.NET Web API calls a method on a controller, it must set values for the parameters, a process called parameter binding.

By default, Web API uses the following rules to bind parameters:

  • If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string.

  • For complex types, Web API tries to read the value from the message body, using a media-type formatter.

So, if you want to override the above default behaviour and force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter. To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.

So, to answer your question, the need of the [FromBody] and [FromUri] attributes in Web API is simply to override, if necessary, the default behaviour as described above. Note that you can use both attributes for a controller method, but only for different parameters, as demonstrated here.

There is a lot more information on the web if you google "web api parameter binding".

Untrack files from git temporarily

you could keep your files untracked after

git rm -r --cached <file>

add your files with

git add -u

them push or do whatever you want.

Maintain model of scope when changing between views in AngularJS

An alternative to services is to use the value store.

In the base of my app I added this

var agentApp = angular.module('rbAgent', ['ui.router', 'rbApp.tryGoal', 'rbApp.tryGoal.service', 'ui.bootstrap']);

agentApp.value('agentMemory',
    {
        contextId: '',
        sessionId: ''
    }
);
...

And then in my controller I just reference the value store. I don't think it holds thing if the user closes the browser.

angular.module('rbAgent')
.controller('AgentGoalListController', ['agentMemory', '$scope', '$rootScope', 'config', '$state', function(agentMemory, $scope, $rootScope, config, $state){

$scope.config = config;
$scope.contextId = agentMemory.contextId;
...

What exactly is Spring Framework for?

Spring contains (as Skaffman rightly pointed out) a MVC framework. To explain in short here are my inputs. Spring supports segregation of service layer, web layer and business layer, but what it really does best is "injection" of objects. So to explain that with an example consider the example below:

public interface FourWheel
{
   public void drive();
}

public class Sedan implements FourWheel
{
   public void drive()
   {
      //drive gracefully
   }
}

public class SUV implements FourWheel
{
   public void drive()
   {
      //Rule the rough terrain
   }
}

Now in your code you have a class called RoadTrip as follows

public class RoadTrip
{
    private FourWheel myCarForTrip;
}

Now whenever you want a instance of Trip; sometimes you may want a SUV to initialize FourWheel or sometimes you may want Sedan. It really depends what you want based on specific situation.

To solve this problem you'd want to have a Factory Pattern as creational pattern. Where a factory returns the right instance. So eventually you'll end up with lots of glue code just to instantiate objects correctly. Spring does the job of glue code best without that glue code. You declare mappings in XML and it initialized the objects automatically. It also does lot using singleton architecture for instances and that helps in optimized memory usage.

This is also called Inversion Of Control. Other frameworks to do this are Google guice, Pico container etc.

Apart from this, Spring has validation framework, extensive support for DAO layer in collaboration with JDBC, iBatis and Hibernate (and many more). Provides excellent Transactional control over database transactions.

There is lot more to Spring that can be read up in good books like "Pro Spring".

Following URLs may be of help too.
http://static.springframework.org/docs/Spring-MVC-step-by-step/
http://en.wikipedia.org/wiki/Spring_Framework
http://www.theserverside.com/tt/articles/article.tss?l=SpringFramework

How to check all versions of python installed on osx and centos

COMMAND: python --version && python3 --version

OUTPUT:

Python 2.7.10
Python 3.7.1

ALIAS COMMAND: pyver

OUTPUT:

Python 2.7.10
Python 3.7.1

You can make an alias like "pyver" in your .bashrc file or else using a text accelerator like AText maybe.

How can I access and process nested objects, arrays or JSON?

To access a nested attribute, you need to specify its name and then search through the object.

If you already know the exact path, then you can hardcode it in your script like so:

data['items'][1]['name']

these also work -

data.items[1].name
data['items'][1].name
data.items[1]['name']

When you don't know the exact name before hand, or a user is the one who provides the name for you. Then dynamically searching through the data structure is required. Some suggested here that the search can be done using a for loop, but there is a very simple way to traverse a path using Array.reduce.

const data = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }
const path = [ 'items', '1', 'name']
let result = path.reduce((a,v) => a[v], data)

The path is a way to say: First take the object with key items, which happens to be an array. Then take the 1-st element (0 index arrays). Last take the object with key name in that array element, which happens to be the string bar.

If you have a very long path, you might even use String.split to make all of this easier -

'items.1.name'.split('.').reduce((a,v) => a[v], data)

This is just plain JavaScript, without using any third party libraries like jQuery or lodash.

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

There are two crucial nonobvious settings that I've discovered when tuning linked servers on Excel under SQL Server 2014. With those settings, ' FROM OPENDATASOURCE(''Microsoft.ACE.OLEDB.16.0'', ...)' as well as '... FROM [' + @srv_name + ']...data AS xl ...' function properly.

Linked server creation

This is just for context.

DECLARE @DB_NAME NVARCHAR(30) = DB_NAME();
DECLARE @srv_name nvarchar(64) = N'<srv_base_name>@' + @DB_NAME; --to distinguish linked server usage by different databases

EXEC sp_addlinkedserver
    @server=@srv_name,
    @srvproduct=N'OLE DB Provider for ACE 16.0',
    @provider= N'Microsoft.ACE.OLEDB.16.0',
    @datasrc= '<local_file_path>\<excel_workbook_name>.xlsx',
    @provstr= N'Excel 12.0;HDR=YES;IMEX=0'
;
  1. @datasrc: Encoding is crucial here: varchar instead of nvarchar.
  2. @provstr: Verion, settings and sytax are important!
  3. @provider: Specify the provider installed in your SQL Server environment. Available providers are enumerated under Server Objects::Linked Servers::Providers in SSMS's Object Explorer.

Providing access to the linked server under specific SQL Server logins

This is the first crucial setting. Even for SA like for any other SQL Server login:

EXEC sp_addlinkedsrvlogin @rmtsrvname = @srv_name, @locallogin = N'sa', @useself = N'False', @rmtuser = N'admin', @rmtpassword = N''
;
  1. @rmtuser: It should be admin. Actually, there is no any admin in Windows logins on the system at the same time.
  2. @rmtpassword: It should be an empty string.

Providing access to the linked server via ad hoc queries

This is the second crucial setting. Setting Ad Hoc Distributed Queries to 1 is not enough. One should set to 0 the DisallowAdhocAccess registry key explicitly for the driver specified to @provider:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL12.DEF_INST\Providers\Microsoft.ACE.OLEDB.16.0]
"DisallowAdhocAccess"=dword:00000000

Is it possible to hide the cursor in a webpage using CSS or Javascript?

If you want to do it in CSS:

#ID { cursor: none !important; }

How would I stop a while loop after n amount of time?

You do not need to use the while True: loop in this case. There is a much simpler way to use the time condition directly:

import time

# timeout variable can be omitted, if you use specific value in the while condition
timeout = 300   # [seconds]

timeout_start = time.time()

while time.time() < timeout_start + timeout:
    test = 0
    if test == 5:
        break
    test -= 1

Need to get current timestamp in Java

Try this single line solution :

import java.util.Date;
String timestamp = 
    new java.text.SimpleDateFormat("MM/dd/yyyy h:mm:ss a").format(new Date());

how to enable sqlite3 for php?

The Debian/Ubuntu way for php-7.2, php-7.3 & php-7.4 (e.g. the [234] part)

sudo apt install php7.[234]-sqlite
sudo phpenmod sqlite3

Be sure to note that on Windows Subsystem for Linux version 1 (WSL1) the (file-)locking system for SQlite is broken.

How to display alt text for an image in chrome

You can use the title attribute.

<img height="90" width="90"
src="http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif"
alt="Google Images" title="Google Images" />

How to undo the last commit in git

I think you haven't messed up yet. Try:

git reset HEAD^

This will bring the dir to state before you've made the commit, HEAD^ means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).

How to open an external file from HTML

A simple link to the file is the obvious solution here. You just have to make shure that the link is valid and that it really points to a file ...

How to detect idle time in JavaScript elegantly?

<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
    //Increment the idle time counter every minute.
    idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    //Zero the idle timer on mouse movement.
    $('body').mousemove(function (e) {
     //alert("mouse moved" + idleTime);
     idleTime = 0;
    });

    $('body').keypress(function (e) {
      //alert("keypressed"  + idleTime);
        idleTime = 0;
    });



    $('body').click(function() {
      //alert("mouse moved" + idleTime);
       idleTime = 0;
    });

});

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 10) { // 10 minutes

        window.location.assign("http://www.google.com");
    }
}
</script> 

I think this jquery code is perfect one , though copied and modified from above answers!! donot forgot to include jquery library in your file!

Standardize data columns in R

'Caret' package provides methods for preprocessing data (e.g. centering and scaling). You could also use the following code:

library(caret)
# Assuming goal class is column 10
preObj <- preProcess(data[, -10], method=c("center", "scale"))
newData <- predict(preObj, data[, -10])

More details: http://www.inside-r.org/node/86978

Insert into a MySQL table or update if exists

In case that you wanted to make a non-primary fields as criteria/condition for ON DUPLICATE, you can make a UNIQUE INDEX key on that table to trigger the DUPLICATE.

ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`);

And in case you want to combine two fields to make it unique on the table, you can achieve this by adding more on the last parameter.

ALTER TABLE `table` ADD UNIQUE `unique_index`(`name`, `age`);

Note, just make sure to delete first all the data that has the same name and age value across the other rows.

DELETE table FROM table AS a, table AS b WHERE a.id < b.id 
AND a.name <=> b.name AND a.age <=> b.age;

After that, it should trigger the ON DUPLICATE event.

INSERT INTO table (id, name, age) VALUES(1, "A", 19) ON DUPLICATE KEY UPDATE    
name = VALUES(name), age = VALUES(age)

How can I symlink a file in Linux?

To the original question:


'ln -s '+basebuild+'/IpDome-kernel/kernel /home/build/sandbox/gen2/basebuild/IpDome-kernel/kernal'

This will indeed create a symbolic link (-s) from the file/directory:

<basebuild>/IpDome-kernel/kernel

to your new link

/home/build/sandbox/gen2/basebuild/IpDome-kernel/kernal

Here's a few ways to help you remember:

First, there's the man page for ln. You can access this via searching "man ln" in google, or just open a terminal window and type man ln and you'll get the same information. The man page clearly states:

ln [OPTION]... [-T] TARGET LINK_NAME (1st form)


If having to search or read through a man page every time isn't for you, maybe you'll have an easier time remembering that all nix commands work the same way:

cp /file/that/exists /location/for/new/file
mv /file/that/exists /location/its/moving/to
ln /file/that/exists /the/new/link

cp copies a file that currently exists (the first argument) to a new file (the second argument).
mv moves a file that currently exists (the first argument) to a new place (the second argument)

Likewise ln links a file that currently exists (the first argument) to a new link (the second argument)*


The final option I would like to suggest is you can create your own man pages that are easy to read and easy (for you) to find/remember. Just make a simple shell script that gives you the hint you need. For example?:

In your .bash_aliases file you can place something like:

commandsfx() {
    echo "Symlink:  ln -s /path/to/file /path/to/symlink"
    echo "Copy:     cp /file/to/copy /destination/to/send/copy"
}

alias 'cmds'=commandsfx

Then when you need it, from the command line just type cmds and you'll get back the proper syntax in a way you can quickly read and understand it. You can make these functions as advanced as you'd like to get what what information you need, it's up to you. You could even make them interactive so you just have to follow the prompts.. something like:

makesymlink() {
    echo "Symlink name:"
    read sym
    echo "File to link to:"
    read fil
    ln -s $fil $sym
}

alias 'symlink'=makesymlink

* - well obviously they can all take different parameters and do different things and can work on files as well as directories... but the premise is the same
? - examples using the bash shell

Why did Servlet.service() for servlet jsp throw this exception?

I had this error; it happened somewhat spontaneously, and the page would halt in the browser in the middle of an HTML tag (not a section of code). It was baffling!

Turns out, I let a variable go out of scope and the garbage collector swept it away and then I tried to use it. Thus the seemingly-random timing.

To give a more concrete example... Inside a method, I had something like:

Foo[] foos = new Foo[20];
// fill up the "foos" array...
return Arrays.asList(foos); // this returns type List<Foo>

Now in my JSP page, I called that method and used the List object returned by it. The List object is backed by that "foos" array; but, the array went out of scope when I returned from the method (since it is a local variable). So shortly after returning, the garbage collector swept away the "foos" array, and my access to the List caused a NullPointerException since its underlying array was now wiped away.

I actually wondered, as I wrote the above method, whether that would happen.

The even deeper underlying problem was premature optimization. I wanted a list, but I knew I would have exactly 20 elements, so I figured I'd try to be more efficient than new ArrayList<Foo>(20) which only sets an initial size of 20 but can possibly be less efficient than the method I used. So of course, to fix it, I just created my ArrayList, filled it up, and returned it. No more strange error.

Simple insecure two-way data "obfuscation"?

I know you said you don't care about how secure it is, but if you chose DES you might as well take AES it is the more up-to-date encryption method.

Binary numbers in Python

You can convert between a string representation of the binary using bin() and int()

>>> bin(88)
'0b1011000'
>>> int('0b1011000', 2)
88
>>> 

>>> a=int('01100000', 2)
>>> b=int('00100110', 2)
>>> bin(a & b)
'0b100000'
>>> bin(a | b)
'0b1100110'
>>> bin(a ^ b)
'0b1000110'

How to clean project cache in Intellij idea like Eclipse's clean?

Delete the "target" folder under the offending module. Then Build | Rebuild Project. Also make sure your clear the web browsers cache.

Math operations from string

You could use this function which is doing the same as the eval() function, but in a simple manner, using a function.

def numeric(equation):
    if '+' in equation:
        y = equation.split('+')
        x = int(y[0])+int(y[1])
    elif '-' in equation:
        y = equation.split('-')
        x = int(y[0])-int(y[1])
    return x

Better way to sort array in descending order

Yes, you can pass predicate to sort. That would be your reverse implementation.

form_for with nested resources

Travis R is correct. (I wish I could upvote ya.) I just got this working myself. With these routes:

resources :articles do
  resources :comments
end

You get paths like:

/articles/42
/articles/42/comments/99

routed to controllers at

app/controllers/articles_controller.rb
app/controllers/comments_controller.rb

just as it says at http://guides.rubyonrails.org/routing.html#nested-resources, with no special namespaces.

But partials and forms become tricky. Note the square brackets:

<%= form_for [@article, @comment] do |f| %>

Most important, if you want a URI, you may need something like this:

article_comment_path(@article, @comment)

Alternatively:

[@article, @comment]

as described at http://edgeguides.rubyonrails.org/routing.html#creating-paths-and-urls-from-objects

For example, inside a collections partial with comment_item supplied for iteration,

<%= link_to "delete", article_comment_path(@article, comment_item),
      :method => :delete, :confirm => "Really?" %>

What jamuraa says may work in the context of Article, but it did not work for me in various other ways.

There is a lot of discussion related to nested resources, e.g. http://weblog.jamisbuck.org/2007/2/5/nesting-resources

Interestingly, I just learned that most people's unit-tests are not actually testing all paths. When people follow jamisbuck's suggestion, they end up with two ways to get at nested resources. Their unit-tests will generally get/post to the simplest:

# POST /comments
post :create, :comment => {:article_id=>42, ...}

In order to test the route that they may prefer, they need to do it this way:

# POST /articles/42/comments
post :create, :article_id => 42, :comment => {...}

I learned this because my unit-tests started failing when I switched from this:

resources :comments
resources :articles do
  resources :comments
end

to this:

resources :comments, :only => [:destroy, :show, :edit, :update]
resources :articles do
  resources :comments, :only => [:create, :index, :new]
end

I guess it's ok to have duplicate routes, and to miss a few unit-tests. (Why test? Because even if the user never sees the duplicates, your forms may refer to them, either implicitly or via named routes.) Still, to minimize needless duplication, I recommend this:

resources :comments
resources :articles do
  resources :comments, :only => [:create, :index, :new]
end

Sorry for the long answer. Not many people are aware of the subtleties, I think.

ResourceDictionary in a separate assembly

Using XAML:

If you know the other assembly structure and want the resources in c# code, then use below code:

 ResourceDictionary dictionary = new ResourceDictionary();
 dictionary.Source = new Uri("pack://application:,,,/WpfControlLibrary1;Component/RD1.xaml", UriKind.Absolute);
 foreach (var item in dictionary.Values)
 {
    //operations
 }

Output: If we want to use ResourceDictionary RD1.xaml of Project WpfControlLibrary1 into StackOverflowApp project.

Structure of Projects:

Structure of Projects

Resource Dictionary: Resource Dictionary

Code Output:

Output

PS: All ResourceDictionary Files should have Build Action as 'Resource' or 'Page'.

Using C#:

If anyone wants the solution in purely c# code then see my this solution.

How does the Spring @ResponseBody annotation work?

Further to this, the return type is determined by

  1. What the HTTP Request says it wants - in its Accept header. Try looking at the initial request as see what Accept is set to.

  2. What HttpMessageConverters Spring sets up. Spring MVC will setup converters for XML (using JAXB) and JSON if Jackson libraries are on he classpath.

If there is a choice it picks one - in this example, it happens to be JSON.

This is covered in the course notes. Look for the notes on Message Convertors and Content Negotiation.

Convert varchar into datetime in SQL Server

OP wants mmddyy and a plain convert will not work for that:

select convert(datetime,'12312009')

Msg 242, Level 16, State 3, Line 1 
The conversion of a char data type to a datetime data type resulted in 
an out-of-range datetime value

so try this:

DECLARE @Date char(8)
set @Date='12312009'
SELECT CONVERT(datetime,RIGHT(@Date,4)+LEFT(@Date,2)+SUBSTRING(@Date,3,2))

OUTPUT:

-----------------------
2009-12-31 00:00:00.000

(1 row(s) affected)

How are cookies passed in the HTTP protocol?

Cookies are passed as HTTP headers, both in the request (client -> server), and in the response (server -> client).

How to perform grep operation on all files in a directory?

Use find. Seriously, it is the best way because then you can really see what files it's operating on:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.

How to remove a field completely from a MongoDB document?

{ name: 'book', tags: { words: ['abc','123'], lat: 33, long: 22 } }

Ans:

db.tablename.remove({'tags.words':['abc','123']})

jQuery - how to write 'if not equal to' (opposite of ==)

== => !=

=== => !==

Equal and its opposite

Python list directory, subdirectory, and files

You can take a look at this sample I made. It uses the os.path.walk function which is deprecated beware.Uses a list to store all the filepaths

root = "Your root directory"
ex = ".txt"
where_to = "Wherever you wanna write your file to"
def fileWalker(ext,dirname,names):
    '''
    checks files in names'''
    pat = "*" + ext[0]
    for f in names:
        if fnmatch.fnmatch(f,pat):
            ext[1].append(os.path.join(dirname,f))


def writeTo(fList):

    with open(where_to,"w") as f:
        for di_r in fList:
            f.write(di_r + "\n")






if __name__ == '__main__':
    li = []
    os.path.walk(root,fileWalker,[ex,li])

    writeTo(li)

Value of type 'T' cannot be converted to

Change this line:

if (typeof(T) == typeof(string))

For this line:

if (t.GetType() == typeof(string))

HTML5 Canvas Resize (Downscale) Image High Quality?

I really try to avoid running through image data, especially on larger images. Thus I came up with a rather simple way to decently reduce image size without any restrictions or limitations using a few extra steps. This routine goes down to the lowest possible half step before the desired target size. Then it scales it up to twice the target size and then half again. Sounds funny at first, but the results are astoundingly good and go there swiftly.

function resizeCanvas(canvas, newWidth, newHeight) {
  let ctx = canvas.getContext('2d');
  let buffer = document.createElement('canvas');
  buffer.width = ctx.canvas.width;
  buffer.height = ctx.canvas.height;
  let ctxBuf = buffer.getContext('2d');
  

  let scaleX = newWidth / ctx.canvas.width;
  let scaleY = newHeight / ctx.canvas.height;

  let scaler = Math.min(scaleX, scaleY);
  //see if target scale is less than half...
  if (scaler < 0.5) {
    //while loop in case target scale is less than quarter...
    while (scaler < 0.5) {
      ctxBuf.canvas.width = ctxBuf.canvas.width * 0.5;
      ctxBuf.canvas.height = ctxBuf.canvas.height * 0.5;
      ctxBuf.scale(0.5, 0.5);
      ctxBuf.drawImage(canvas, 0, 0);
      ctxBuf.setTransform(1, 0, 0, 1, 0, 0);
      ctx.canvas.width = ctxBuf.canvas.width;
      ctx.canvas.height = ctxBuf.canvas.height;
      ctx.drawImage(buffer, 0, 0);

      scaleX = newWidth / ctxBuf.canvas.width;
      scaleY = newHeight / ctxBuf.canvas.height;
      scaler = Math.min(scaleX, scaleY);
    }
    //only if the scaler is now larger than half, double target scale trick...
    if (scaler > 0.5) {
      scaleX *= 2.0;
      scaleY *= 2.0;
      ctxBuf.canvas.width = ctxBuf.canvas.width * scaleX;
      ctxBuf.canvas.height = ctxBuf.canvas.height * scaleY;
      ctxBuf.scale(scaleX, scaleY);
      ctxBuf.drawImage(canvas, 0, 0);
      ctxBuf.setTransform(1, 0, 0, 1, 0, 0);
      scaleX = 0.5;
      scaleY = 0.5;
    }
  } else
    ctxBuf.drawImage(canvas, 0, 0);

  //wrapping things up...
  ctx.canvas.width = newWidth;
  ctx.canvas.height = newHeight;
  ctx.scale(scaleX, scaleY);
  ctx.drawImage(buffer, 0, 0);
  ctx.setTransform(1, 0, 0, 1, 0, 0);
}

Parsing XML in Python using ElementTree example

So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:

import elementtree.ElementTree as ET

tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')

print thingy.attrib

and got the following back:

{'name': 'NWIS Time Series Instantaneous Values'}

It appears to have found the timeSeries element without needing to use numerical indices.

What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.

How to convert datatype:object to float64 in python?

You can try this:

df['2nd'] = pd.to_numeric(df['2nd'].str.replace(',', ''))
df['CTR'] = pd.to_numeric(df['CTR'].str.replace('%', ''))

How to find index of all occurrences of element in array?

You can write a simple readable solution to this by using both map and filter:

const nanoIndexes = Cars
  .map((car, i) => car === 'Nano' ? i : -1)
  .filter(index => index !== -1);

EDIT: If you don't need to support IE/Edge (or are transpiling your code), ES2019 gave us flatMap, which lets you do this in a simple one-liner:

const nanoIndexes = Cars.flatMap((car, i) => car === 'Nano' ? i : []);

Bootstrap carousel resizing image

i had this issue years back..but I got this. All you need to do is set the width and the height of the image to whatever you want..what i mean is your image in your carousel inner ...don't add the style attribut like "style:"(no not this) but something like this and make sure your codes ar correct its gonna work...Good luck

"Unicode Error "unicodeescape" codec can't decode bytes... Cannot open text files in Python 3

path = pd.read_csv(**'C:\Users\mravi\Desktop\filename'**)

The error is because of the path that is mentioned

Add 'r' before the path

path = pd.read_csv(**r'C:\Users\mravi\Desktop\filename'**)

This would work fine.

Add x and y labels to a pandas plot

what about ...

import pandas as pd
import matplotlib.pyplot as plt

values = [[1,2], [2,5]]

df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])

(df2.plot(lw=2,
          colormap='jet',
          marker='.',
          markersize=10,
          title='Video streaming dropout by category')
    .set(xlabel='x axis',
         ylabel='y axis'))

plt.show()

What are the differences between a superkey and a candidate key?

Candidate key is a super key from which you cannot remove any fields.

For instance, a software release can be identified either by major/minor version, or by the build date (we assume nightly builds).

Storing date in three fields is not a good idea of course, but let's pretend it is for demonstration purposes:

year  month date  major  minor
2008  01    13     0      1
2008  04    23     0      2
2009  11    05     1      0
2010  04    05     1      1

So (year, major, minor) or (year, month, date, major) are super keys (since they are unique) but not candidate keys, since you can remove year or major and the remaining set of columns will still be a super key.

(year, month, date) and (major, minor) are candidate keys, since you cannot remove any of the fields from them without breaking uniqueness.

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

I did something really stupid (and maybe you did too).

I was trying to call System.Web.Mvc.Html.Partial("<Partial Page>")

System.Web.Mvc.Html is a namespace and not a class and I didn't read my error message so well, so I interpreted my error as the class Html does not exist in the namespace System.Web.Mvc and that's how I ended up here (stupid I know).

All I needed to do was add a using statement @using System.Web.Mvc.Html to my page and then @Html.Partial worked as expected.

jQuery select option elements by value

Here's the simplest solution with a clear selector:

function select_option(i) {
  return $('span#span_id select option[value="' + i + '"]').html();
}

Check if a variable is between two numbers with Java

You can use this simply:

I'm using this function to check if the input int number is between 20 and 30

    static boolean isValidInput(int input) {
    return (input >= 20 && input <= 30);
}

how to split the ng-repeat data with three columns using bootstrap

My approach was a mixture of things.

My objective was to have a grid adapting to the screen size. I wanted 3 columns for lg, 2 columns for sm and md, and 1 column for xs.

First, I created the following scope function, using angular $window service:

$scope.findColNumberPerRow = function() {
    var nCols;
    var width = $window.innerWidth;

    if (width < 768) {
        // xs
        nCols = 1;
    }
    else if(width >= 768 && width < 1200) {
         // sm and md
         nCols = 2
    } else if (width >= 1200) {
        // lg
        nCols = 3;
    }
    return nCols;
};

Then, I used the class proposed by @Cumulo Nimbus:

.new-row {
    clear: left;
}

In the div containing the ng-repeat, I added the resizable directive, as explained in this page, so that every time window is resized, angular $window service is updated with the new values.

Ultimately, in the repeated div I have:

ng-repeat="user in users" ng-class="{'new-row': ($index % findColNumberPerRow() === 0) }"

Please, let me know any flaws in this approach.

Hope it can be helpful.

Best way to initialize (empty) array in PHP

In PHP an array is an array; there is no primitive vs. object consideration, so there is no comparable optimization to be had.

Datetime BETWEEN statement not working in SQL Server

Does the second query return any results from the 17th, or just from the 18th?

The first query will only return results from the 17th, or midnight on the 18th.

Try this instead

select * 
from LOGS 
where check_in >= CONVERT(datetime,'2013-10-17') 
and check_in< CONVERT(datetime,'2013-10-19')

Semaphore vs. Monitors - what's the difference?

Following explanation actually explains how wait() and signal() of monitor differ from P and V of semaphore.

The wait() and signal() operations on condition variables in a monitor are similar to P and V operations on counting semaphores.

A wait statement can block a process's execution, while a signal statement can cause another process to be unblocked. However, there are some differences between them. When a process executes a P operation, it does not necessarily block that process because the counting semaphore may be greater than zero. In contrast, when a wait statement is executed, it always blocks the process. When a task executes a V operation on a semaphore, it either unblocks a task waiting on that semaphore or increments the semaphore counter if there is no task to unlock. On the other hand, if a process executes a signal statement when there is no other process to unblock, there is no effect on the condition variable. Another difference between semaphores and monitors is that users awaken by a V operation can resume execution without delay. Contrarily, users awaken by a signal operation are restarted only when the monitor is unlocked. In addition, a monitor solution is more structured than the one with semaphores because the data and procedures are encapsulated in a single module and that the mutual exclusion is provided automatically by the implementation.

Link: here for further reading. Hope it helps.

Microsoft Web API: How do you do a Server.MapPath?

The selected answer did not work in my Web API application. I had to use

System.Web.HttpRuntime.AppDomainAppPath

Declaring a custom android UI element using XML

Addition to most voted answer.

obtainStyledAttributes()

I want to add some words about obtainStyledAttributes() usage, when we create custom view using android:xxx prdefined attributes. Especially when we use TextAppearance.
As was mentioned in "2. Creating constructors", custom view gets AttributeSet on its creation. Main usage we can see in TextView source code (API 16).

final Resources.Theme theme = context.getTheme();

// TextAppearance is inspected first, but let observe it later

TypedArray a = theme.obtainStyledAttributes(
            attrs, com.android.internal.R.styleable.TextView, defStyle, 0);

int n = a.getIndexCount();
for (int i = 0; i < n; i++) 
{
    int attr = a.getIndex(i);
    // huge switch with pattern value=a.getXXX(attr) <=> a.getXXX(a.getIndex(i))
}
a.recycle();

What we can see here?
obtainStyledAttributes(AttributeSet set, int[] attrs, int defStyleAttr, int defStyleRes)
Attribute set is processed by theme according to documentation. Attribute values are compiled step by step. First attributes are filled from theme, then values are replaced by values from style, and finally exact values from XML for special view instance replace others.
Array of requested attributes - com.android.internal.R.styleable.TextView
It is an ordinary array of constants. If we are requesting standard attributes, we can build this array manually.

What is not mentioned in documentation - order of result TypedArray elements.
When custom view is declared in attrs.xml, special constants for attribute indexes are generated. And we can extract values this way: a.getString(R.styleable.MyCustomView_android_text). But for manual int[] there are no constants. I suppose, that getXXXValue(arrayIndex) will work fine.

And other question is: "How we can replace internal constants, and request standard attributes?" We can use android.R.attr.* values.

So if we want to use standard TextAppearance attribute in custom view and read its values in constructor, we can modify code from TextView this way:

ColorStateList textColorApp = null;
int textSize = 15;
int typefaceIndex = -1;
int styleIndex = -1;

Resources.Theme theme = context.getTheme();

TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.CustomLabel, defStyle, 0);
TypedArray appearance = null;
int apResourceId = a.getResourceId(R.styleable.CustomLabel_android_textAppearance, -1);
a.recycle();
if (apResourceId != -1)
{
    appearance = 
        theme.obtainStyledAttributes(apResourceId, new int[] { android.R.attr.textColor, android.R.attr.textSize, 
            android.R.attr.typeface, android.R.attr.textStyle });
}
if (appearance != null)
{
    textColorApp = appearance.getColorStateList(0);
    textSize = appearance.getDimensionPixelSize(1, textSize);
    typefaceIndex = appearance.getInt(2, -1);
    styleIndex = appearance.getInt(3, -1);

    appearance.recycle();
}

Where CustomLabel is defined:

<declare-styleable name="CustomLabel">
    <!-- Label text. -->
    <attr name="android:text" />
    <!-- Label text color. -->
    <attr name="android:textColor" />
    <!-- Combined text appearance properties. -->
    <attr name="android:textAppearance" />
</declare-styleable>

Maybe, I'm mistaken some way, but Android documentation on obtainStyledAttributes() is very poor.

Extending standard UI component

At the same time we can just extend standard UI component, using all its declared attributes. This approach is not so good, because TextView for instance declares a lot of properties. And it will be impossible to implement full functionality in overriden onMeasure() and onDraw().

But we can sacrifice theoretical wide reusage of custom component. Say "I know exactly what features I will use", and don't share code with anybody.

Then we can implement constructor CustomComponent(Context, AttributeSet, defStyle). After calling super(...) we will have all attributes parsed and available through getter methods.

Why does overflow:hidden not work in a <td>?

I'm not familiar with the specific issue, but you could stick a div, etc inside the td and set overflow on that.

react-router go back a page how do you configure history?

Call the following component like so:

<BackButton history={this.props.history} />

And here is the component:

import React, { Component } from 'react'
import PropTypes from 'prop-types'
class BackButton extends Component {
  constructor() {
    super(...arguments)

    this.goBack = this.goBack.bind(this)
  }

  render() {
    return (
      <button
        onClick={this.goBack}>
          Back
      </button>
    )
  }

  goBack() {
    this.props.history.goBack()
  }
}

BackButton.propTypes = {
  history: PropTypes.object,
}

export default BackButton

I'm using:

"react": "15.6.1"
"react-router": "4.2.0"

What is the difference between Amazon SNS and Amazon SQS?

Here's a comparison of the two:

Entity Type

  • SQS: Queue (Similar to JMS)
  • SNS: Topic (Pub/Sub system)

Message consumption

  • SQS: Pull Mechanism - Consumers poll and pull messages from SQS
  • SNS: Push Mechanism - SNS Pushes messages to consumers

Use Case

  • SQS: Decoupling two applications and allowing parallel asynchronous processing
  • SNS: Fanout - Processing the same message in multiple ways

Persistence

  • SQS: Messages are persisted for some (configurable) duration if no consumer is available (maximum two weeks), so the consumer does not have to be up when messages are added to queue.
  • SNS: No persistence. Whichever consumer is present at the time of message arrival gets the message and the message is deleted. If no consumers are available then the message is lost after a few retries.

Consumer Type

  • SQS: All the consumers are typically identical and hence process the messages in the exact same way (each message is processed once by one consumer, though in rare cases messages may be resent)
  • SNS: The consumers might process the messages in different ways

Sample applications

  • SQS: Jobs framework: The Jobs are submitted to SQS and the consumers at the other end can process the jobs asynchronously. If the job frequency increases, the number of consumers can simply be increased to achieve better throughput.
  • SNS: Image processing. If someone uploads an image to S3 then watermark that image, create a thumbnail and also send a Thank You email. In that case S3 can publish notifications to an SNS topic with three consumers listening to it. The first one watermarks the image, the second one creates a thumbnail and the third one sends a Thank You email. All of them receive the same message (image URL) and do their processing in parallel.

Can we call the function written in one JavaScript in another JS file?

For those who want to do this in Node.js (running scripts on the server-side) another option is to use require and module.exports. Here is a short example on how to create a module and export it for use elsewhere:

file1.js

const print = (string) => {
    console.log(string);
};

exports.print = print;

file2.js

const file1 = require('./file1');

function printOne() {
    file1.print("one");
};

how to change directory using Windows command line

cd has a parameter /d, which will change drive and path with one command:

cd /d d:\temp

( see cd /?)

What is the difference between using constructor vs getInitialState in React / React Native?

The difference between constructor and getInitialState is the difference between ES6 and ES5 itself.
getInitialState is used with React.createClass and
constructor is used with React.Component.

Hence the question boils down to advantages/disadvantages of using ES6 or ES5.

Let's look at the difference in code

ES5

var TodoApp = React.createClass({ 
  propTypes: {
    title: PropTypes.string.isRequired
  },
  getInitialState () { 
    return {
      items: []
    }; 
  }
});

ES6

class TodoApp extends React.Component {
  constructor () {
    super()
    this.state = {
      items: []
    }
  }
};

There is an interesting reddit thread regarding this.

React community is moving closer to ES6. Also it is considered as the best practice.

There are some differences between React.createClass and React.Component. For instance, how this is handled in these cases. Read more about such differences in this blogpost and facebook's content on autobinding

constructor can also be used to handle such situations. To bind methods to a component instance, it can be pre-bonded in the constructor. This is a good material to do such cool stuff.

Some more good material on best practices
Best Practices for Component State in React.js
Converting React project from ES5 to ES6

Update: April 9, 2019,:

With the new changes in Javascript class API, you don't need a constructor.

You could do

class TodoApp extends React.Component {

    this.state = {items: []}
};

This will still get transpiled to constructor format, but you won't have to worry about it. you can use this format that is more readable.

react hooks image With React Hooks

From React version 16.8, there's a new API Called hooks.

Now, you don't even need a class component to have a state. It can even be done in a functional component.

import React, { useState } from 'react';

function TodoApp () {
  const items = useState([]);

Note that the initial state is passed as an argument to useState; useState([])

Read more about react hooks from the official docs

JavaScript string and number conversion

You can do it like this:

// step 1 
var one = "1" + "2" + "3"; // string value "123"

// step 2
var two = parseInt(one); // integer value 123

// step 3
var three = 123 + 100; // integer value 223

// step 4
var four = three.toString(); // string value "223"

What are the aspect ratios for all Android phone and tablet devices?

the best way to calculate the equation is simplified. That is, find the maximum divisor between two numbers and divide:

ex.

1920:1080 maximum common divisor 120 = 16:9
1024:768  maximum common divisor 256 = 4:3
1280:768  maximum common divisor 256 = 5:3

may happen also some approaches

Databound drop down list - initial value

I know this already has a chosen answer - but I wanted to toss in my two cents. I have a databound dropdown list:

<asp:DropDownList 
  id="country" 
  runat="server" 
  CssClass="selectOne" 
  DataSourceID="country_code" 
  DataTextField="Name" 
  DataValueField="CountryCode_PK"
></asp:DropDownList>
<asp:SqlDataSource 
  id="country_code" 
  runat="server" 
  ConnectionString="<%$ ConnectionStrings:DBConnectionString %>"
  SelectCommand="SELECT CountryCode_PK, CountryCode_PK + ' - ' + Name AS N'Name' FROM TBL_Country ORDER BY CountryCode_PK"
></asp:SqlDataSource>

In the codebehind, I have this - (which selects United States by default):

if (this.IsPostBack)
{
  //handle posted data
}
else 
{
  country.SelectedValue = "US";
}

The page initially loads based on the 'US' value rather than trying to worry about a selectedIndex (what if another item is added into the data table - I don't want to have to re-code)

Passing multiple values for same variable in stored procedure

You will need to do a couple of things to get this going, since your parameter is getting multiple values you need to create a Table Type and make your store procedure accept a parameter of that type.

Split Function Works Great when you are getting One String containing multiple values but when you are passing Multiple values you need to do something like this....

TABLE TYPE

CREATE TYPE dbo.TYPENAME AS TABLE   (     arg int    )  GO 

Stored Procedure to Accept That Type Param

 CREATE PROCEDURE mainValues   @TableParam TYPENAME READONLY  AS     BEGIN     SET NOCOUNT ON;   --Temp table to store split values   declare @tmp_values table (   value nvarchar(255) not null);        --function splitting values     INSERT INTO @tmp_values (value)    SELECT arg FROM @TableParam      SELECT * FROM @tmp_values  --<-- For testing purpose END 

EXECUTE PROC

Declare a variable of that type and populate it with your values.

 DECLARE @Table TYPENAME     --<-- Variable of this TYPE   INSERT INTO @Table                --<-- Populating the variable   VALUES (331),(222),(876),(932)  EXECUTE mainValues @Table   --<-- Stored Procedure Executed  

Result

╔═══════╗ ║ value ║ ╠═══════╣ ║   331 ║ ║   222 ║ ║   876 ║ ║   932 ║ ╚═══════╝ 

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

Your Customer class has to be discovered by CDI as a bean. For that you have two options:

  1. Put a bean defining annotation on it. As @Model is a stereotype it's why it does the trick. A qualifier like @Named is not a bean defining annotation, reason why it doesn't work

  2. Change the bean discovery mode in your bean archive from the default "annotated" to "all" by adding a beans.xml file in your jar.

Keep in mind that @Named has only one usage : expose your bean to the UI. Other usages are for bad practice or compatibility with legacy framework.

Cancel a vanilla ECMAScript 6 Promise chain

Set a "cancelled" property on the Promise to signal then() and catch() to exit early. It's very effective, especially in Web Workers that have existing microtasks queued up in Promises from onmessage handlers.

_x000D_
_x000D_
// Queue task to resolve Promise after the end of this script_x000D_
const promise = new Promise(resolve => setTimeout(resolve))_x000D_
_x000D_
promise.then(_ => {_x000D_
  if (promise.canceled) {_x000D_
    log('Promise cancelled.  Exiting early...');_x000D_
    return;_x000D_
  }_x000D_
_x000D_
  log('No cancelation signaled.  Continue...');_x000D_
})_x000D_
_x000D_
promise.canceled = true;_x000D_
_x000D_
function log(msg) {_x000D_
  document.body.innerHTML = msg;_x000D_
}
_x000D_
_x000D_
_x000D_

What is so bad about singletons?

The singleton pattern is not a problem in itself. The problem is that the pattern is often used by people developing software with object-oriented tools without having a solid grasp of OO concepts. When singletons are introduced in this context they tend to grow into unmanageable classes that contain helper methods for every little use.

Singletons are also a problem from a testing perspective. They tend to make isolated unit-tests difficult to write. Inversion of control (IoC) and dependency injection are patterns meant to overcome this problem in an object-oriented manner that lends itself to unit testing.

In a garbage collected environment singletons can quickly become an issue with regard to memory management.

There is also the multi-threaded scenario where singletons can become a bottleneck as well as a synchronization issue.

MYSQL Sum Query with IF Condition

How about this?

SUM(IF(PaymentType = "credit card", totalamount, 0)) AS CreditCardTotal

Mixing C# & VB In The Same Project

Walkthrough: Using Multiple Programming Languages in a Web Site Project http://msdn.microsoft.com/en-us/library/ms366714.aspx

By default, the App_Code folder does not allow multiple programming languages. However, in a Web site project you can modify your folder structure and configuration settings to support multiple programming languages such as Visual Basic and C#. This allows ASP.NET to create multiple assemblies, one for each language. For more information, see Shared Code Folders in ASP.NET Web Projects. Developers commonly include multiple programming languages in Web applications to support multiple development teams that operate independently and prefer different programming languages.

Best way to randomize an array with .NET

You can also make an extention method out of Matt Howells. Example.

   namespace System
    {
        public static class MSSystemExtenstions
        {
            private static Random rng = new Random();
            public static void Shuffle<T>(this T[] array)
            {
                rng = new Random();
                int n = array.Length;
                while (n > 1)
                {
                    int k = rng.Next(n);
                    n--;
                    T temp = array[n];
                    array[n] = array[k];
                    array[k] = temp;
                }
            }
        }
    }

Then you can just use it like:

        string[] names = new string[] {
                "Aaron Moline1", 
                "Aaron Moline2", 
                "Aaron Moline3", 
                "Aaron Moline4", 
                "Aaron Moline5", 
                "Aaron Moline6", 
                "Aaron Moline7", 
                "Aaron Moline8", 
                "Aaron Moline9", 
            };
        names.Shuffle<string>();

Node.js: socket.io close client connection

For socket.io version 1.4.5:

On server:

socket.on('end', function (){
    socket.disconnect(0);
});

On client:

var io = io();
io.emit('end');

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

I ran into this exact same error when connecting from MySQL workbench. Here's how I fixed it. My /etc/my.cnf configuration file had the bind-address value set to the server's IP address. This had to be done to setup replication. Anyway, I solved it by doing two things:

  1. create a user that can be used to connect from the bind address in the my.cnf file

e.g.

CREATE USER 'username'@'bind-address' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON schemaname.* TO 'username'@'bind-address';
FLUSH PRIVILEGES;
  1. change the MySQL hostname value in the connection details in MySQL workbench to match the bind-address

jQuery class within class selector

is just going to look for a div with class="outer inner", is that correct?

No, '.outer .inner' will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner' (no space) would give the results you're thinking of.

'.outer > .inner' will look for immediate children of an element with the .outer class for elements with the .inner class.

Both '.outer .inner' and '.outer > .inner' should work for your example, although the selectors are fundamentally different and you should be wary of this.

Rollback one specific migration in Laravel

Laravel 5.3+

Rollback one step. Natively.

php artisan migrate:rollback --step=1

And here's the manual page: docs.


Laravel 5.2 and before

No way to do without some hassle. For details, check Martin Bean's answer.

When to use extern in C++

It's all about the linkage.

The previous answers provided good explainations about extern.

But I want to add an important point.

You ask about extern in C++ not in C and I don't know why there is no answer mentioning about the case when extern comes with const in C++.

In C++, a const variable has internal linkage by default (not like C).

So this scenario will lead to linking error:

Source 1 :

const int global = 255; //wrong way to make a definition of global const variable in C++

Source 2 :

extern const int global; //declaration

It need to be like this:

Source 1 :

extern const int global = 255; //a definition of global const variable in C++

Source 2 :

extern const int global; //declaration

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

Display all dataframe columns in a Jupyter Python Notebook

If you want to show all the rows set like bellow

pd.options.display.max_rows = None

If you want to show all columns set like bellow

pd.options.display.max_columns = None

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

What is 'Context' on Android?

Just putting it out there for newbies;

So First understand Word Context :

In english-lib. it means:

"The circumstances that form the setting for an event, statement, or idea, and in terms of which it can be fully understood and assessed."

"The parts of something written or spoken that immediately precede and follow a word or passage and clarify its meaning."

Now take the same understanding to programming world:

context of current state of the application/object. It lets newly created objects understand what has been going on. Typically you call it to get information regarding another part of your program (activity, package/application)

You can get the context by invoking getApplicationContext(), getContext(), getBaseContext() or this (when in the activity class).

To Get Context Anywhere in application use following code:

Create new class AppContext inside your android application

public class AppContext extends Application {

    private static Context context;

    public void onCreate(){
        super.onCreate();
        AppContext.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return AppContext.context;
    }
}

Now any time you want application context in non-activity class, call this method and you have application context.

Hope this help ;)