Programs & Examples On #Swiftmailer

Swift Mailer is a library that integrates into any web app written in PHP, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features.

Expected response code 220 but got code "", with message "" in Laravel

I did as per sid saying my env after updating is

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<mygmailaddress>
MAIL_PASSWORD=<gmailpassword>
MAIL_ENCRYPTION=tls

this did work without 2 step verification. with 2 step verification enabled it did not work for me.

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

First check if there is any connectivity problem and you can reach the SMTP server:

In terminal type:

telnet servername portnumber 

If you receive the 220 response you can reach the SMTP server and there is no connectivity problem but if the connection to the server failed see what's wrong in your network.

If the server needs auth try to authenticate on the server by username and password and see if something goes wrong.

At last see if the server requires encryption and if yes openssl and other stuff are configured correctly.

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

(I'm using SwiftMailer in PHP)

I was getting an error like that when I was accidentally sending a string for $email

$email = "[email protected] <Some One>";

When what I meant to be sending was

$email = Array("[email protected]"=>"Some One");

I was accidentally running it through a stringify function that I was using for logging, so once I started sending the array again, the error went away.

Swift_TransportException Connection could not be established with host smtp.gmail.com

firstly,check for gmail SMTP server . you should have to allow access for less secured apps without allowing swift mailer is not possible.for this login in your email account first then go into privacy settings and then click on sign and security then click on apps without access and then make on to less secure apps option then try mailer again, it will work then.

Failed to authenticate on SMTP server error using gmail

This is how I solved this issue:

  1. Change the .env file as follow

Screenshot Reference

  1. Never forget to restart the server after you change the .env file

Handling Dialogs in WPF with MVVM

Why not just raise an event in the VM and subscribe to the event in the view? This would keep the application logic and the view seperate and still allow you to use a child window for dialogs.

Reverse / invert a dictionary mapping

If values aren't unique AND may be a hash (one dimension):

for k, v in myDict.items():
    if len(v) > 1:
        for item in v:
            invDict[item] = invDict.get(item, [])
            invDict[item].append(k)
    else:
        invDict[v] = invDict.get(v, [])
        invDict[v].append(k)

And with a recursion if you need to dig deeper then just one dimension:

def digList(lst):
    temp = []
    for item in lst:
        if type(item) is list:
            temp.append(digList(item))
        else:
            temp.append(item)
    return set(temp)

for k, v in myDict.items():
    if type(v) is list:
        items = digList(v)
        for item in items:
            invDict[item] = invDict.get(item, [])
            invDict[item].append(k)
    else:
        invDict[v] = invDict.get(v, [])
        invDict[v].append(k)

GoTo Next Iteration in For Loop in java

Try this,

1. If you want to skip a particular iteration, use continue.

2. If you want to break out of the immediate loop use break

3 If there are 2 loop, outer and inner.... and you want to break out of both the loop from the inner loop, use break with label.

eg:

continue

for(int i=0 ; i<5 ; i++){

    if (i==2){

      continue;
    }
 }

eg:

break

for(int i=0 ; i<5 ; i++){

        if (i==2){

          break;
        }
     }

eg:

break with label

lab1: for(int j=0 ; j<5 ; j++){
     for(int i=0 ; i<5 ; i++){

        if (i==2){

          break lab1;
        }
     }
  }

R Markdown - changing font size and font type in html output

You can change the font size in R Markdown with HTML code tags <font size="1"> your text </font> . This code is added to the R Markdown document and will alter the output of the HTML output.

For example:

_x000D_
_x000D_
 <font size="1"> This is my text number1</font> _x000D_
_x000D_
 <font size="2"> This is my text number 2 </font>_x000D_
 _x000D_
 <font size="3"> This is my text number 3</font> _x000D_
 _x000D_
 <font size="4"> This is my text number 4</font> _x000D_
 _x000D_
 <font size="5"> This is my text number 5</font> _x000D_
 _x000D_
 <font size="6"> This is my text number 6</font>
_x000D_
_x000D_
_x000D_

Split comma-separated input box values into array in jquery, and loop through it

var array = searchTerms.split(",");

for (var i in array){
     alert(array[i]);
}

How to align texts inside of an input?

The accepted answer here is correct but I'd like to add a little info. If you are using a library / framework like bootstrap there may be built in classes for this. For example bootstrap uses the text-right class. Use it like this:

<input type="text" class="text-right"/> 
<input type="number" class="text-right"/>

As a note this works on other input types as well, like numeric as shown above.

If you aren't using a nice framework like bootstrap then you can make your own version of this helper class. Similar to other answers but we are not going to add it directly to the input class so it won't apply to every single input on your site or page, this might not be desired behavior. So this would create a nice easy css class to align things right without needing inline styling or affecting every single input box.

.text-right{
    text-align: right;
}

Now you can use this class exactly the same as the inputs above with class="text-right". I know it isn't saving that many key strokes but it makes your code cleaner.

Protractor : How to wait for page complete after click a button?

With Protractor, you can use the following approach

var EC = protractor.ExpectedConditions;
// Wait for new page url to contain newPageName
browser.wait(EC.urlContains('newPageName'), 10000);

So your code will look something like,

emailEl.sendKeys('jack');
passwordEl.sendKeys('123pwd');

btnLoginEl.click();

var EC = protractor.ExpectedConditions;
// Wait for new page url to contain efg
ptor.wait(EC.urlContains('efg'), 10000);

expect(ptor.getCurrentUrl()).toEqual(url + 'abc#/efg');

Note: This may not mean that new page has finished loading and DOM is ready. The subsequent 'expect()' statement will ensure Protractor waits for DOM to be available for test.

Reference: Protractor ExpectedConditions

MySQL INSERT INTO ... VALUES and SELECT

 
INSERT INTO table_name1
            (id,
             name,
             address,
             contact_number) 
SELECT id, name, address, contact_number FROM table_name2;   

Python, creating objects

class Student(object):
    name = ""
    age = 0
    major = ""

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

def make_student(name, age, major):
    student = Student(name, age, major)
    return student

Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:

class Student(object):
    name = ""
    age = 0
    major = ""

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    # Note: I didn't need to create a variable in the class definition before doing this.
    student.gpa = float(4.0)
    return student

I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.

What is the difference between a .cpp file and a .h file?

The C++ build system (compiler) knows no difference, so it's all one of conventions.

The convention is that .h files are declarations, and .cpp files are definitions.

That's why .h files are #included -- we include the declarations.

Git merge error "commit is not possible because you have unmerged files"

You can use git stash to save the current repository before doing the commit you want to make (after merging the changes from the upstream repo with git stash pop). I had to do this yesterday when I had the same problem.

How to change value of ArrayList element in java

Where you say you're changing the value of the first element;

x = Integer.valueOf(9);

You're changing x to point to an entirely new Integer, but never using it again. You're not changing the collection in any way.

Since you're working with ArrayList, you can use ListIterator if you want an iterator that allows you to change the elements, this is the snippet of your code that would need to be changed;

//initialize the Iterator
ListIterator<Integer> i = a.listIterator();

//changed the value of frist element in List
if(i.hasNext()) {
    i.next();
    i.set(Integer.valueOf(9));    // Change the element the iterator is currently at
}

// New iterator, and print all the elements
Iterator iter = a.iterator();
while(iter.hasNext())
    System.out.print(iter.next());

>> 912345678

Sadly the same cannot be extended to other collections like Set<T>. Implementation details (a HashSet for example being implemented as a hash table and changing the object could change the hash value and therefore the iteration order) makes Set<T> a "add new/remove only" type of data structure, and changing the content at all while iterating over it is not safe.

Angularjs $q.all

$http is a promise too, you can make it simpler:

return $q.all(tasks.map(function(d){
        return $http.post('upload/tasks',d).then(someProcessCallback, onErrorCallback);
    }));

how to check if the input is a number or not in C?

You can use a function like strtol() which will convert a character array to a long.

It has a parameter which is a way to detect the first character that didn't convert properly. If this is anything other than the end of the string, then you have a problem.

See the following program for an example:

#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[]) {
    int i;
    long val;
    char *next;

    // Process each argument given.

    for (i = 1; i < argc; i++) {
        // Get value with failure detection.

        val = strtol (argv[i], &next, 10);

        // Check for empty string and characters left after conversion.

        if ((next == argv[i]) || (*next != '\0')) {
            printf ("'%s' is not valid\n", argv[i]);
        } else {
            printf ("'%s' gives %ld\n", argv[i], val);
        }
    }

    return 0;
}

Running this, you can see it in operation:

pax> testprog hello "" 42 12.2 77x

'hello' is not valid
'' is not valid
'42' gives 42
'12.2' is not valid
'77x' is not valid

Is an entity body allowed for an HTTP DELETE request?

It seems ElasticSearch uses this: https://www.elastic.co/guide/en/elasticsearch/reference/5.x/search-request-scroll.html#_clear_scroll_api

Which means Netty support this.

Like mentionned in comments it may not be the case anymore

Module is not available, misspelled or forgot to load (but I didn't)

Using AngularJS 1.6.9+

There is one more incident, it also happen when you declare variable name different of module name.

var indexPageApp = angular.module('indexApp', []);

to get rid of this error,

Error: [$injector:nomod] Module 'indexPageApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

change the module name similar to var declared name or vice versa -

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

Convert string to variable name in python

This is the best way, I know of to create dynamic variables in python.

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

I found a similar, but not the same question here Creating dynamically named variables from user input

Extract first and last row of a dataframe in pandas

You can also use head and tail:

In [29]: pd.concat([df.head(1), df.tail(1)])
Out[29]:
   a  b
0  1  a
3  4  d

What's the difference between identifying and non-identifying relationships?

A complement to Daniel Dinnyes' answer:

On a non-identifying relationship, you can't have the same Primary Key column (let's say, "ID") twice with the same value.

However, with an identifyinig relationship, you can have the same value show up twice for the "ID" column, as long as it has a different "otherColumn_ID" Foreign Key value, because the primary key is the combination of both columns.

Note that it doesn't matter if the FK is "non-null" or not! ;-)

Add quotation at the start and end of each line in Notepad++

You won't be able to do it in a single replacement; you'll have to perform a few steps. Here's how I'd do it:

  1. Find (in regular expression mode):

    (.+)
    

    Replace with:

    "\1"
    

    This adds the quotes:

    "AliceBlue"
    "AntiqueWhite"
    "Aqua"
    "Aquamarine"
    "Azure"
    "Beige"
    "Bisque"
    "Black"
    "BlanchedAlmond"
    
  2. Find (in extended mode):

    \r\n
    

    Replace with (with a space after the comma, not shown):

    , 
    

    This converts the lines into a comma-separated list:

    "AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"
    

  3. Add the var myArray = assignment and braces manually:

    var myArray = ["AliceBlue", "AntiqueWhite", "Aqua", "Aquamarine", "Azure", "Beige", "Bisque", "Black", "BlanchedAlmond"];
    

Script to Change Row Color when a cell changes text

//Sets the row color depending on the value in the "Status" column.
function setRowColors() {
  var range = SpreadsheetApp.getActiveSheet().getDataRange();
  var statusColumnOffset = getStatusColumnOffset();

  for (var i = range.getRow(); i < range.getLastRow(); i++) {
    rowRange = range.offset(i, 0, 1);
    status = rowRange.offset(0, statusColumnOffset).getValue();
    if (status == 'Completed') {
      rowRange.setBackgroundColor("#99CC99");
    } else if (status == 'In Progress') {
      rowRange.setBackgroundColor("#FFDD88");    
    } else if (status == 'Not Started') {
      rowRange.setBackgroundColor("#CC6666");          
    }
  }
}

//Returns the offset value of the column titled "Status"
//(eg, if the 7th column is labeled "Status", this function returns 6)
function getStatusColumnOffset() {
  lastColumn = SpreadsheetApp.getActiveSheet().getLastColumn();
  var range = SpreadsheetApp.getActiveSheet().getRange(1,1,1,lastColumn);

  for (var i = 0; i < range.getLastColumn(); i++) {
    if (range.offset(0, i, 1, 1).getValue() == "Status") {
      return i;
    } 
  }
}

When 1 px border is added to div, Div size increases, Don't want to do that

You can create the element with border with the same color of your background, then when you want the border to show, just change its color.

How to redirect cin and cout to files?

Just write

#include <cstdio>
#include <iostream>
using namespace std;

int main()
{
    freopen("output.txt","w",stdout);
    cout<<"write in file";
    return 0;
}

Invoke-WebRequest, POST with parameters

This just works:

$body = @{
 "UserSessionId"="12345678"
 "OptionalEmail"="[email protected]"
} | ConvertTo-Json

$header = @{
 "Accept"="application/json"
 "connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
 "Content-Type"="application/json"
} 

Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML

jQuery hasAttr checking to see if there is an attribute on an element

The best way to do this would be with filter():

$("nav>ul>li>a").filter("[data-page-id]");

It would still be nice to have .hasAttr(), but as it doesn't exist there is this way.

Use grep to report back only line numbers

If you're open to using AWK:

awk '/textstring/ {print FNR}' textfile

In this case, FNR is the line number. AWK is a great tool when you're looking at grep|cut, or any time you're looking to take grep output and manipulate it.

How to create an Array with AngularJS's ng-model

It works fine for me: http://jsfiddle.net/qwertynl/htb9h/

My javascript:

var app = angular.module("myApp", [])
app.controller("MyCtrl", ['$scope', function($scope) {
    $scope.telephone = []; // << remember to set this
}]);

How do I drop a MongoDB database from the command line?

use following command from mongo shell to drop db

use ; db.dropDatabase();

Parse HTML table to Python list?

Sven Marnach excellent solution is directly translatable into ElementTree which is part of recent Python distributions:

from xml.etree import ElementTree as ET

s = """<table>
  <tr><th>Event</th><th>Start Date</th><th>End Date</th></tr>
  <tr><td>a</td><td>b</td><td>c</td></tr>
  <tr><td>d</td><td>e</td><td>f</td></tr>
  <tr><td>g</td><td>h</td><td>i</td></tr>
</table>
"""

table = ET.XML(s)
rows = iter(table)
headers = [col.text for col in next(rows)]
for row in rows:
    values = [col.text for col in row]
    print(dict(zip(headers, values)))

same output as Sven Marnach's answer...

How to ORDER BY a SUM() in MySQL?

This is how you do it

SELECT ID,NAME, (C_COUNTS+F_COUNTS) AS SUM_COUNTS 
FROM TABLE 
ORDER BY SUM_COUNTS LIMIT 20

The SUM function will add up all rows, so the order by clause is useless, instead you will have to use the group by clause.

css h1 - only as wide as the text

Somewhat like the other suggestions you could use the following code. However, if you do go the margin: 0 auto; route I'd recommend having the margin for the top and bottom of an H1 be set to something other than 0. So, perhaps margin: 6px auto; or something.

.centercol h1{
    display: inline-block;
    color: #006bb6;
    font-weight: normal;
    font-size: 18px;
    padding:3px 3px 3px 6px;
    border-left:3px solid #c6c1b8;
    background:#f2efe9;
    display:block;
}

How to set the focus for a particular field in a Bootstrap modal, once it appears

A little cleaner and more modular solution might be:

$(document).ready(function(){
    $('.modal').success(function() { 
        $('input:text:visible:first').focus();
    });  
});

Or using your ID as an example instead:

$(document).ready(function(){
    $('#modal-content').modal('show').success(function() {
        $('input:text:visible:first').focus();
    });  
});

Hope that helps..

PHP Checking if the current date is before or after a set date

if(strtotime($db_date) > time()) {
  echo $db_date;
} else {
  echo 'go ahead';
}

Seaborn Barplot - Displaying Values

A simple way to do so is to add the below code (for Seaborn):

for p in splot.patches:
    splot.annotate(format(p.get_height(), '.1f'), 
                   (p.get_x() + p.get_width() / 2., p.get_height()), 
                   ha = 'center', va = 'center', 
                   xytext = (0, 9), 
                   textcoords = 'offset points') 

Example :

splot = sns.barplot(df['X'], df['Y'])
# Annotate the bars in plot
for p in splot.patches:
    splot.annotate(format(p.get_height(), '.1f'), 
                   (p.get_x() + p.get_width() / 2., p.get_height()), 
                   ha = 'center', va = 'center', 
                   xytext = (0, 9), 
                   textcoords = 'offset points')    
plt.show()

Unix - copy contents of one directory to another

Quite simple, with a * wildcard.

cp -r Folder1/* Folder2/

But according to your example recursion is not needed so the following will suffice:

cp Folder1/* Folder2/

EDIT:

Or skip the mkdir Folder2 part and just run:

cp -r Folder1 Folder2

Javascript - get array of dates between 2 dates

Here's a one liner that doesn't require any libraries in-case you don't want to create another function. Just replace startDate (in two places) and endDate (which are js date objects) with your variables or date values. Of course you could wrap it in a function if you prefer

Array(Math.floor((endDate - startDate) / 86400000) + 1).fill().map((_, idx) => (new Date(startDate.getTime() + idx * 86400000)))

Modify a Column's Type in sqlite3

If you prefer a GUI, DB Browser for SQLite will do this with a few clicks.

  1. "File" - "Open Database"
  2. In the "Database Structure" tab, click on the table content (not table name), then "Edit" menu, "Modify table", and now you can change the data type of any column with a drop down menu. I changed a 'text' field to 'numeric' in order to retrieve data in a number range.

DB Browser for SQLite is open source and free. For Linux it is available from the repository.

Enabling refreshing for specific html elements only

Try this in your script:

$("#YourElement").html(htmlData);

I do this in my table refreshment.

XOR operation with two strings in java

Note: this only works for low characters i.e. below 0x8000, This works for all ASCII characters.

I would do an XOR each charAt() to create a new String. Like

String s, key;

StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++)
    sb.append((char)(s.charAt(i) ^ key.charAt(i % key.length())));
String result = sb.toString();

In response to @user467257's comment

If your input/output is utf-8 and you xor "a" and "æ", you are left with an invalid utf-8 string consisting of one character (decimal 135, a continuation character).

It is the char values which are being xor'ed, but the byte values and this produces a character whichc an be UTF-8 encoded.

public static void main(String... args) throws UnsupportedEncodingException {
    char ch1 = 'a';
    char ch2 = 'æ';
    char ch3 = (char) (ch1 ^ ch2);
    System.out.println((int) ch3 + " UTF-8 encoded is " + Arrays.toString(String.valueOf(ch3).getBytes("UTF-8")));
}

prints

135 UTF-8 encoded is [-62, -121]

How do I use hexadecimal color strings in Flutter?

You can use this package from_css_color to get Color out of a hex string. It supports both three and six digit RGB hex notation.

Color color = fromCSSColor('#ff00aa')

For optimisation sake create Color instance once for each color and store it somewhere for later usage.

How to get last month/year in java?

Your solution is here but instead of addition you need to use subtraction

c.add(Calendar.MONTH, -1);

Then you can call getter on the Calendar to acquire proper fields

int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year  = c.get(Calendar.YEAR);

android: how to align image in the horizontal center of an imageview?

you can horizontal your image view in a linear layout using:

 android:layout_gravity="center"

it will center your image to the parent element, if you just want to center horizontally you can use:

 android:layout_gravity="center_horizontal"

How to get Spinner value?

View view =(View) getActivity().findViewById(controlId);
Spinner spinner = (Spinner)view.findViewById(R.id.spinner1);
String valToSet = spinner.getSelectedItem().toString();

How does one parse XML files?

I'm not sure whether "best practice for parsing XML" exists. There are numerous technologies suited for different situations. Which way to use depends on the concrete scenario.

You can go with LINQ to XML, XmlReader, XPathNavigator or even regular expressions. If you elaborate your needs, I can try to give some suggestions.

How do I update a model value in JavaScript in a Razor view?

This should work

function updatePostID(val)
{
    document.getElementById('PostID').value = val;

    //and probably call document.forms[0].submit();
}

Then have a hidden field or other control for the PostID

@Html.Hidden("PostID", Model.addcomment.PostID)
//OR
@Html.HiddenFor(model => model.addcomment.PostID)

Django Cookies, how can I set them?

Anyone interested in doing this should read the documentation of the Django Sessions framework. It stores a session ID in the user's cookies, but maps all the cookies-like data to your database. This is an improvement on the typical cookies-based workflow for HTTP requests.

Here is an example with a Django view ...

def homepage(request):

    request.session.setdefault('how_many_visits', 0)
    request.session['how_many_visits'] += 1

    print(request.session['how_many_visits'])

    return render(request, 'home.html', {})

If you keep visiting the page over and over, you'll see the value start incrementing up from 1 until you clear your cookies, visit on a new browser, go incognito, or do anything else that sidesteps Django's Session ID cookie.

What are the best PHP input sanitizing functions?

It depends on the kind of data you are using. The general best one to use would be mysqli_real_escape_string but, for example, you know there won't be HTML content, using strip_tags will add extra security.

You can also remove characters you know shouldn't be allowed.

MySQL Join Where Not Exists

I'd use a 'where not exists' -- exactly as you suggest in your title:

SELECT `voter`.`ID`, `voter`.`Last_Name`, `voter`.`First_Name`,
       `voter`.`Middle_Name`, `voter`.`Age`, `voter`.`Sex`,
       `voter`.`Party`, `voter`.`Demo`, `voter`.`PV`,
       `household`.`Address`, `household`.`City`, `household`.`Zip`
FROM (`voter`)
JOIN `household` ON `voter`.`House_ID`=`household`.`id`
WHERE `CT` = '5'
AND `Precnum` = 'CTY3'
AND  `Last_Name`  LIKE '%Cumbee%'
AND  `First_Name`  LIKE '%John%'

AND NOT EXISTS (
  SELECT * FROM `elimination`
   WHERE `elimination`.`voter_id` = `voter`.`ID`
)

ORDER BY `Last_Name` ASC
LIMIT 30

That may be marginally faster than doing a left join (of course, depending on your indexes, cardinality of your tables, etc), and is almost certainly much faster than using IN.

Difference between [routerLink] and routerLink

Router Link

routerLink with brackets and none - simple explanation.

The difference between routerLink= and [routerLink] is mostly like relative and absolute path.

Similar to a href you may want to navigate to ./about.html or https://your-site.com/about.html.

When you use without brackets then you navigate relative and without params;

my-app.com/dashboard/client

"jumping" from my-app.com/dashboard to my-app.com/dashboard/client

<a routerLink="client/{{ client.id }}" .... rest the same

When you use routerLink with brackets then you execute app to navigate absolute and you can add params how is the puzzle of your new link

first of all it will not include the "jump" from dashboard/ to dashboard/client/client-id and bring you data of client/client-id which is more helpful for EDIT CLIENT

<a [routerLink]="['/client', client.id]" ... rest the same

The absolute way or brackets routerLink require additional set up of you components and app.routing.module.ts

The code without error will "tell you more/what is the purpose of []" when you make the test. Just check this with or without []. Than you may experiments with selectors which - as mention above - helps with dynamics routing.

Angular.io Selectors

See whats the routerLink construct

https://angular.io/api/router/RouterLink#selectors

How to abort makefile if variable not set?

TL;DR: Use the error function:

ifndef MY_FLAG
$(error MY_FLAG is not set)
endif

Note that the lines must not be indented. More precisely, no tabs must precede these lines.


Generic solution

In case you're going to test many variables, it's worth defining an auxiliary function for that:

# Check that given variables are set and all have non-empty values,
# die with an error otherwise.
#
# Params:
#   1. Variable name(s) to test.
#   2. (optional) Error message to print.
check_defined = \
    $(strip $(foreach 1,$1, \
        $(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
    $(if $(value $1),, \
      $(error Undefined $1$(if $2, ($2))))

And here is how to use it:

$(call check_defined, MY_FLAG)

$(call check_defined, OUT_DIR, build directory)
$(call check_defined, BIN_DIR, where to put binary artifacts)
$(call check_defined, \
            LIB_INCLUDE_DIR \
            LIB_SOURCE_DIR, \
        library path)


This would output an error like this:

Makefile:17: *** Undefined OUT_DIR (build directory).  Stop.

Notes:

The real check is done here:

$(if $(value $1),,$(error ...))

This reflects the behavior of the ifndef conditional, so that a variable defined to an empty value is also considered "undefined". But this is only true for simple variables and explicitly empty recursive variables:

# ifndef and check_defined consider these UNDEFINED:
explicitly_empty =
simple_empty := $(explicitly_empty)

# ifndef and check_defined consider it OK (defined):
recursive_empty = $(explicitly_empty)

As suggested by @VictorSergienko in the comments, a slightly different behavior may be desired:

$(if $(value $1) tests if the value is non-empty. It's sometimes OK if the variable is defined with an empty value. I'd use $(if $(filter undefined,$(origin $1)) ...

And:

Moreover, if it's a directory and it must exist when the check is run, I'd use $(if $(wildcard $1)). But would be another function.

Target-specific check

It is also possible to extend the solution so that one can require a variable only if a certain target is invoked.

$(call check_defined, ...) from inside the recipe

Just move the check into the recipe:

foo :
    @:$(call check_defined, BAR, baz value)

The leading @ sign turns off command echoing and : is the actual command, a shell no-op stub.

Showing target name

The check_defined function can be improved to also output the target name (provided through the $@ variable):

check_defined = \
    $(strip $(foreach 1,$1, \
        $(call __check_defined,$1,$(strip $(value 2)))))
__check_defined = \
    $(if $(value $1),, \
        $(error Undefined $1$(if $2, ($2))$(if $(value @), \
                required by target `$@')))

So that, now a failed check produces a nicely formatted output:

Makefile:7: *** Undefined BAR (baz value) required by target `foo'.  Stop.

check-defined-MY_FLAG special target

Personally I would use the simple and straightforward solution above. However, for example, this answer suggests using a special target to perform the actual check. One could try to generalize that and define the target as an implicit pattern rule:

# Check that a variable specified through the stem is defined and has
# a non-empty value, die with an error otherwise.
#
#   %: The name of the variable to test.
#   
check-defined-% : __check_defined_FORCE
    @:$(call check_defined, $*, target-specific)

# Since pattern rules can't be listed as prerequisites of .PHONY,
# we use the old-school and hackish FORCE workaround.
# You could go without this, but otherwise a check can be missed
# in case a file named like `check-defined-...` exists in the root 
# directory, e.g. left by an accidental `make -t` invocation.
.PHONY : __check_defined_FORCE
__check_defined_FORCE :

Usage:

foo :|check-defined-BAR

Notice that the check-defined-BAR is listed as the order-only (|...) prerequisite.

Pros:

  • (arguably) a more clean syntax

Cons:

I believe, these limitations can be overcome using some eval magic and secondary expansion hacks, although I'm not sure it's worth it.

Javascript equivalent of php's strtotime()?

Maybe you can exploit a sample function like :

_x000D_
_x000D_
function strtotime(date, addTime){_x000D_
  let generatedTime=date.getTime();_x000D_
  if(addTime.seconds) generatedTime+=1000*addTime.seconds; //check for additional seconds _x000D_
  if(addTime.minutes) generatedTime+=1000*60*addTime.minutes;//check for additional minutes _x000D_
  if(addTime.hours) generatedTime+=1000*60*60*addTime.hours;//check for additional hours _x000D_
  return new Date(generatedTime);_x000D_
}_x000D_
_x000D_
let futureDate = strtotime(new Date(), {_x000D_
    hours: 1, //Adding one hour_x000D_
    minutes: 45 //Adding fourty five minutes_x000D_
  });_x000D_
document.body.innerHTML = futureDate;
_x000D_
_x000D_
_x000D_

`

Bash Shell Script - Check for a flag and grab its value

Use $# to grab the number of arguments, if it is unequal to 2 there are not enough arguments provided:

if [ $# -ne 2 ]; then
   usage;
fi

Next, check if $1 equals -t, otherwise an unknown flag was used:

if [ "$1" != "-t" ]; then
  usage;
fi

Finally store $2 in FLAG:

FLAG=$2

Note: usage() is some function showing the syntax. For example:

function usage {
   cat << EOF
Usage: script.sh -t <application>

Performs some activity
EOF
   exit 1
}

Check, using jQuery, if an element is 'display:none' or block on click

Use this condition:

if (jQuery(".profile-page-cont").css('display') == 'block'){
    // Condition 
}

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

In my case, I experienced this error because my webapp was .NET v4, and the application pool was configured for .NET v2.

Double-clicking on the application pool brings up a popup window, where we can select the desired version of .NET Framework.

Java how to sort a Linked List?

Elegant solution since JAVA 8:

LinkedList<String>list = new LinkedList<String>();
list.add("abc");
list.add("Bcd");
list.add("aAb");

list.sort(String::compareToIgnoreCase);

Another option would be using lambda expressions:

list.sort((o1, o2) -> o1.compareToIgnoreCase(o2));

JMS Topic vs Queues

If you have N consumers then:

JMS Topics deliver messages to N of N JMS Queues deliver messages to 1 of N

You said you are "looking to have a 'thing' that will send a copy of the message to each subscriber in the same sequence as that in which the message was received by the ActiveMQ broker."

So you want to use a Topic in order that all N subscribers get a copy of the message.

How can I check if a URL exists via PHP?

Other way to check if a URL is valid or not can be:

<?php

  if (isValidURL("http://www.gimepix.com")) {
      echo "URL is valid...";
  } else {
      echo "URL is not valid...";
  }

  function isValidURL($url) {
      $file_headers = @get_headers($url);
      if (strpos($file_headers[0], "200 OK") > 0) {
         return true;
      } else {
        return false;
      }
  }
?>

How to autowire RestTemplate using annotations

Errors you'll see if a RestTemplate isn't defined

Consider defining a bean of type 'org.springframework.web.client.RestTemplate' in your configuration.

or

No qualifying bean of type [org.springframework.web.client.RestTemplate] found

How to define a RestTemplate via annotations

Depending on which technologies you're using and what versions will influence how you define a RestTemplate in your @Configuration class.

Spring >= 4 without Spring Boot

Simply define an @Bean:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

Spring Boot <= 1.3

No need to define one, Spring Boot automatically defines one for you.

Spring Boot >= 1.4

Spring Boot no longer automatically defines a RestTemplate but instead defines a RestTemplateBuilder allowing you more control over the RestTemplate that gets created. You can inject the RestTemplateBuilder as an argument in your @Bean method to create a RestTemplate:

@Bean
public RestTemplate restTemplate(RestTemplateBuilder builder) {
   // Do any additional configuration here
   return builder.build();
}

Using it in your class

@Autowired
private RestTemplate restTemplate;

or

@Inject
private RestTemplate restTemplate;

django - get() returned more than one topic

In your Topic model you're allowing for more than one element to have the same topic field. You have created two with the same one already.

topic=models.TextField(verbose_name='Thema')

Now when trying to add a new learningObjective you seem to want to add it to only one Topic that matches what you're sending on the form. Since there's more than one with the same topic field get is finding 2, hence the exception.

You can either add the learningObjective to all Topics with that topic field:

for t in topic.objects.filter(topic=request.POST['Thema']):
    t.learningObjectivesTopic.add(neuesLernziel)

or restrict the Topic model to have a unique topic field and keep using get, but that might not be what you want.

How do I find the authoritative name-server for a domain name?

An easy way is to use an online domain tool. My favorite is Domain Tools (formerly whois.sc). I'm not sure if they can resolve conflicting DNS records though. As an example, the DNS servers for stackoverflow.com are

  NS51.DOMAINCONTROL.COM
  NS52.DOMAINCONTROL.COM

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

You are including the CSS code as text in your PHP page. Why not just link it in the traditional fashion?

<link rel="stylesheet" href="CSS/main.css" type="text/css">

Execute php file from another php

exec is shelling to the operating system, and unless the OS has some special way of knowing how to execute a file, then it's going to default to treating it as a shell script or similar. In this case, it has no idea how to run your php file. If this script absolutely has to be executed from a shell, then either execute php passing the filename as a parameter, e.g

exec ('/usr/local/bin/php -f /opt/lampp/htdocs/.../name.php)') ;

or use the punct at the top of your php script

#!/usr/local/bin/php
<?php ... ?>

Display all post meta keys and meta values of the same post ID in wordpress

WordPress have the function get_metadata this get all meta of object (Post, term, user...)

Just use

get_metadata( 'post', 15 );

How to create a generic array in Java?

What about this solution?

@SafeVarargs
public static <T> T[] toGenericArray(T ... elems) {
    return elems;
}

It works and looks too simple to be true. Is there any drawback?

How to list the certificates stored in a PKCS12 keystore with keytool?

You can also use openssl to accomplish the same thing:

$ openssl pkcs12 -nokeys -info \
    -in </path/to/file.pfx> \
    -passin pass:<pfx's password>

MAC Iteration 2048
MAC verified OK
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Certificate bag
Bag Attributes
    localKeyID: XX XX XX XX XX XX XX XX XX XX XX XX XX 48 54 A0 47 88 1D 90
    friendlyName: jedis-server
subject=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXX/CN=something1
issuer=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXXX/CN=something1
-----BEGIN CERTIFICATE-----
...
...
...
-----END CERTIFICATE-----
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048

Difference between Role and GrantedAuthority in Spring Security

Like others have mentioned, I think of roles as containers for more granular permissions.

Although I found the Hierarchy Role implementation to be lacking fine control of these granular permission.
So I created a library to manage the relationships and inject the permissions as granted authorities in the security context.

I may have a set of permissions in the app, something like CREATE, READ, UPDATE, DELETE, that are then associated with the user's Role.

Or more specific permissions like READ_POST, READ_PUBLISHED_POST, CREATE_POST, PUBLISH_POST

These permissions are relatively static, but the relationship of roles to them may be dynamic.

Example -

@Autowired 
RolePermissionsRepository repository;

public void setup(){
  String roleName = "ROLE_ADMIN";
  List<String> permissions = new ArrayList<String>();
  permissions.add("CREATE");
  permissions.add("READ");
  permissions.add("UPDATE");
  permissions.add("DELETE");
  repository.save(new RolePermissions(roleName, permissions));
}

You may create APIs to manage the relationship of these permissions to a role.

I don't want to copy/paste another answer, so here's the link to a more complete explanation on SO.
https://stackoverflow.com/a/60251931/1308685

To re-use my implementation, I created a repo. Please feel free to contribute!
https://github.com/savantly-net/spring-role-permissions

php how to go one level up on dirname(__FILE__)

I use this, if there is an absolute path (this is an example):

$img = imagecreatefromjpeg($_SERVER['DOCUMENT_ROOT']."/Folder-B/image1.jpg");

if there is a picture to show, this is enough:

echo("<img src='/Folder-B/image1.jpg'>");

How to crop an image using PIL?

You need to import PIL (Pillow) for this. Suppose you have an image of size 1200, 1600. We will crop image from 400, 400 to 800, 800

from PIL import Image
img = Image.open("ImageName.jpg")
area = (400, 400, 800, 800)
cropped_img = img.crop(area)
cropped_img.show()

How to draw a filled circle in Java?

public void paintComponent(Graphics g) {
   super.paintComponent(g);
   Graphics2D g2d = (Graphics2D)g;
   // Assume x, y, and diameter are instance variables.
   Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
   g2d.fill(circle);
   ...
}

Here are some docs about paintComponent (link).

You should override that method in your JPanel and do something similar to the code snippet above.

In your ActionListener you should specify x, y, diameter and call repaint().

Scroll back to the top of scrollable div

The ID Should have the id of the corresponding div that has the overflow css property.

document.querySelector('#YOUR_OVERFLOWED_DIV').scrollTop = 0;

Efficiency of Java "Double Brace Initialization"?

Double-brace initialization is an unnecessary hack that can introduce memory leaks and other issues

There's no legitimate reason to use this "trick". Guava provides nice immutable collections that include both static factories and builders, allowing you to populate your collection where it's declared in a clean, readable, and safe syntax.

The example in the question becomes:

Set<String> flavors = ImmutableSet.of(
    "vanilla", "strawberry", "chocolate", "butter pecan");

Not only is this shorter and easier to read, but it avoids the numerous issues with the double-braced pattern described in other answers. Sure, it performs similarly to a directly-constructed HashMap, but it's dangerous and error-prone, and there are better options.

Any time you find yourself considering double-braced initialization you should re-examine your APIs or introduce new ones to properly address the issue, rather than take advantage of syntactic tricks.

Error-Prone now flags this anti-pattern.

How to loop over a Class attributes in Java?

There is no linguistic support to do what you're asking for.

You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields() to get an array of Field), but depending on what you're trying to do, this may not be the best solution.

See also

Related questions


Example

Here's a simple example to show only some of what reflection is capable of doing.

import java.lang.reflect.*;

public class DumpFields {
    public static void main(String[] args) {
        inspect(String.class);
    }
    static <T> void inspect(Class<T> klazz) {
        Field[] fields = klazz.getDeclaredFields();
        System.out.printf("%d fields:%n", fields.length);
        for (Field field : fields) {
            System.out.printf("%s %s %s%n",
                Modifier.toString(field.getModifiers()),
                field.getType().getSimpleName(),
                field.getName()
            );
        }
    }
}

The above snippet uses reflection to inspect all the declared fields of class String; it produces the following output:

7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER

Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection

These are excerpts from the book:

Given a Class object, you can obtain Constructor, Method, and Field instances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:

  • You lose all the benefits of compile-time checking.
  • The code required to perform reflective access is clumsy and verbose.
  • Performance suffers.

As a rule, objects should not be accessed reflectively in normal applications at runtime.

There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.

Are there any Java method ordering conventions?

Some conventions list all the public methods first, and then all the private ones - that means it's easy to separate the API from the implementation, even when there's no interface involved, if you see what I mean.

Another idea is to group related methods together - this makes it easier to spot seams where you could split your existing large class into several smaller, more targeted ones.

correct PHP headers for pdf file download

Example 2 on w3schools shows what you are trying to achieve.

<?php
header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf
readfile("original.pdf");
?>

Also remember that,

It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)

How does a Linux/Unix Bash script know its own PID?

The variable '$$' contains the PID.

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

Is HTML considered a programming language?

The 'M' stands for a 'Markup'. It's a 'Markup Language' not a programming language. Some people will disagree with this, but my opinion is that if it lacks logical constructs (conditional branching, iteration, etc) its not really a programming language.

As for the resume, I would suggest putting HTML and XML under a section like 'Technologies'. I usually have a section like this where I list things like version control software, OS's I've developed for, build systems, etc.

Force table column widths to always be fixed regardless of contents

Try looking into the following CSS:

word-wrap:break-word;

Web browsers should not break-up "words" by default so what you are experiencing is normal behaviour of a browser. However you can override this with the word-wrap CSS directive.

You would need to set a width on the overall table then a width on the columns. "width:100%;" should also be OK depending on your requirements.

Using word-wrap may not be what you want however it is useful for showing all of the data without deforming the layout.

Removing duplicate rows in Notepad++

Notepad++

-> Replace window

Ensure that in Search mode you have selected the Regular expression radio button

Find what:

^(.*)(\r?\n\1)+$

Replace with:

$1

Before:

and we think there

and we think there

single line

Is it possible to

Is it possible to

After:

and we think there

single line

Is it possible to

Lazy Loading vs Eager Loading

Eager Loading When you are sure that want to get multiple entities at a time, for example you have to show user, and user details at the same page, then you should go with eager loading. Eager loading makes single hit on database and load the related entities.

Lazy loading When you have to show users only at the page, and by clicking on users you need to show user details then you need to go with lazy loading. Lazy loading make multiple hits, to get load the related entities when you bind/iterate related entities.

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

Long Press in JavaScript?

The Diodeus's answer is awesome, but it prevent you to add a onClick function, it'll never run hold function if you put an onclick. And the Razzak's answer is almost perfect, but it run hold function only on mouseup, and generally, the function runs even if user keep holding.

So, I joined both, and made this:

$(element).on('click', function () {
    if(longpress) { // if detect hold, stop onclick function
        return false;
    };
});

$(element).on('mousedown', function () {
    longpress = false; //longpress is false initially
    pressTimer = window.setTimeout(function(){
    // your code here

    longpress = true; //if run hold function, longpress is true
    },1000)
});

$(element).on('mouseup', function () {
    clearTimeout(pressTimer); //clear time on mouseup
});

Android ImageButton with a selected state?

This works for me:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- NOTE: order is important (the first matching state(s) is what is rendered) -->
    <item 
        android:state_selected="true" 
        android:drawable="@drawable/info_icon_solid_with_shadow" />
    <item 
        android:drawable="@drawable/info_icon_outline_with_shadow" />
 </selector>

And then in java:

//assign the image in code (or you can do this in your layout xml with the src attribute)
imageButton.setImageDrawable(getBaseContext().getResources().getDrawable(R.drawable....));

//set the click listener
imageButton.setOnClickListener(new OnClickListener() {

    public void onClick(View button) {
        //Set the button's appearance
        button.setSelected(!button.isSelected());

        if (button.isSelected()) {
            //Handle selected state change
        } else {
            //Handle de-select state change
        }

    }

});

For smooth transition you can also mention animation time:

<selector xmlns:android="http://schemas.android.com/apk/res/android" android:exitFadeDuration="@android:integer/config_mediumAnimTime">

How to really read text file from classpath in Java

You say "I am trying to read a text file which is set in CLASSPATH system variable." My guess this is on Windows and you are using this ugly dialog to edit the "System Variables".

Now you run your Java program in the console. And that doesn't work: The console gets a copy of the values of the system variables once when it is started. This means any change in the dialog afterwards doesn't have any effect.

There are these solutions:

  1. Start a new console after every change

  2. Use set CLASSPATH=... in the console to set the copy of the variable in the console and when your code works, paste the last value into the variable dialog.

  3. Put the call to Java into .BAT file and double click it. This will create a new console every time (thus copying the current value of the system variable).

BEWARE: If you also have a User variable CLASSPATH then it will shadow your system variable. That is why it is usually better to put the call to your Java program into a .BAT file and set the classpath in there (using set CLASSPATH=) rather than relying on a global system or user variable.

This also makes sure that you can have more than one Java program working on your computer because they are bound to have different classpaths.

Showing all errors and warnings

Set these on php.ini:

;display_startup_errors = On
display_startup_errors=off
display_errors =on
html_errors= on

From your PHP page, use a suitable filter for error reporting.

error_reporting(E_ALL);

Filers can be made according to requirements.

E_ALL
E_ALL | E_STRICT

How to create a timer using tkinter?

The root.after(ms, func) is the method you need to use. Just call it once before the mainloop starts and reschedule it inside the bound function every time it is called. Here is an example:

from tkinter import *
import time


def update_clock():
    timer_label.config(text=time.strftime('%H:%M:%S',time.localtime()),
                  font='Times 25')  # change the text of the time_label according to the current time
    root.after(100, update_clock)  # reschedule update_clock function to update time_label every 100 ms

root = Tk()  # create the root window
timer_label = Label(root, justify='center')  # create the label for timer
timer_label.pack()  # show the timer_label using pack geometry manager
root.after(0, update_clock)  # schedule update_clock function first call
root.mainloop()  # start the root window mainloop

Remove tracking branches no longer on remote

grep gone <(git branch -v) | cut -d ' ' -f 3 | xargs git branch -d

The above command can be used to fetch branches which are merged and deleted in remote and it deletes the local branch which no longer available in remote

get current page from url

A simple function like below will help :

public string GetCurrentPageName() 
{ 
    string sPath = System.Web.HttpContext.Current.Request.Url.AbsolutePath; 
    System.IO.FileInfo oInfo = new System.IO.FileInfo(sPath); 
    string sRet = oInfo.Name; 
    return sRet; 
} 

What is duck typing?

Simple Explanation (without code)

Discussion of the semantics of the question is fairly nuanced (and very academic), but here's the general idea:

Duck Typing

(“If it walks like a duck and quacks like a duck then it is a duck.”) - YES! but what does that mean??! This is best illustrated by example:

Examples of Duck Typing functionality:

Imagine I have a magic wand. It has special powers. If I wave the wand and say "Drive!" to a car, well then, it drives!

Does it work on other things? Not sure: so I try it on a truck. Wow - it drives too! I then try it on planes, trains and 1 Woods (they are a type of golf club which people use to 'drive' a golf ball). They all drive!

But would it work on say, a teacup? Error: KAAAA-BOOOOOOM! that didn't work out so good. ====> Teacups can't drive!! duh!?

This is basically the concept of duck typing. It's a try-before-you-buy system. If it works, all is well. But if it fails, like a grenade still in your hand, it's gonna blow up in your face.

In other words, we are interested in what the object can do, rather than with what the object is.

Example: statically typed languages

If we were concerned with what the object actually was, then our magic trick will work only on pre-set, authorised types - in this case cars, but will fail on other objects which can drive: trucks, mopeds, tuk-tuks etc. It won't work on trucks because our magic wand is expecting it to only work on cars.

In other words, in this scenario, the magic wand looks very closely at what the object is (is it a car?) rather than what the object can do (e.g. whether cars, trucks etc. can drive).

The only way you can get a truck to drive is if you can somehow get the magic wand to expect both trucks and cars (perhaps by "implementing a common interface"). If you don't know what that means then just ignore it for the moment.

Summary: Key take-out

What's important in duck typing is what the object can actually do, rather than what the object is.

Eclipse IDE: How to zoom in on text?

The tarlog plugin, combined with removing -Dorg.eclipse.swt.internal.carbon.smallFonts from eclipse.ini, helps my tired eyes on MacOS Yosemite with Eclipse Luna (4.4).

Problem: Didn't work for me for a PyDev foo.py Python file. Workaround: Open a file named foo.java - change the font size. Go back to foo.py and voila!! - the python font size matches the java font size.

Git copy file preserving history

All you have to do is:

  1. move the file to two different locations,
  2. merge the two commits that do the above, and
  3. move one copy back to the original location.

You will be able to see historical attributions (using git blame) and full history of changes (using git log) for both files.

Suppose you want to create a copy of file foo called bar. In that case the workflow you'd use would look like this:

git mv foo bar
git commit

SAVED=`git rev-parse HEAD`
git reset --hard HEAD^
git mv foo copy
git commit

git merge $SAVED     # This will generate conflicts
git commit -a        # Trivially resolved like this

git mv copy foo
git commit

Why this works

After you execute the above commands, you end up with a revision history that looks like this:

( revision history )            ( files )

    ORIG_HEAD                      foo
     /     \                      /   \
SAVED       ALTERNATE          bar     copy
     \     /                      \   /
      MERGED                     bar,copy
        |                           |
     RESTORED                    bar,foo

When you ask Git about the history of foo, it will:

  1. detect the rename from copy between MERGED and RESTORED,
  2. detect that copy came from the ALTERNATE parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and ALTERNATE.

From there it will dig into the history of foo.

When you ask Git about the history of bar, it will:

  1. notice no change between MERGED and RESTORED,
  2. detect that bar came from the SAVED parent of MERGED, and
  3. detect the rename from foo between ORIG_HEAD and SAVED.

From there it will dig into the history of foo.

It's that simple. :)

You just need to force Git into a merge situation where you can accept two traceable copies of the file(s), and we do this with a parallel move of the original (which we soon revert).

How to get the azure account tenant Id?

In PowerShell:

Add-AzureRmAccount #if not already logged in 
Get-AzureRmSubscription -SubscriptionName <SubscriptionName> | Select-Object -Property TenantId

Create a Path from String in Java7

Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is a static method in Path class that allows to do this straight away:

With all the path in one String:

Path.of("/tmp/foo");

With the path broken down in several Strings:

Path.of("/tmp","foo");

Memory errors and list limits?

There is no memory limit imposed by Python. However, you will get a MemoryError if you run out of RAM. You say you have 20301 elements in the list. This seems too small to cause a memory error for simple data types (e.g. int), but if each element itself is an object that takes up a lot of memory, you may well be running out of memory.

The IndexError however is probably caused because your ListTemp has got only 19767 elements (indexed 0 to 19766), and you are trying to access past the last element.

It is hard to say what you can do to avoid hitting the limit without knowing exactly what it is that you are trying to do. Using numpy might help. It looks like you are storing a huge amount of data. It may be that you don't need to store all of it at every stage. But it is impossible to say without knowing.

How to use forEach in vueJs?

In VueJS you can loop through an array like this : const array1 = ['a', 'b', 'c'];

Array.from(array1).forEach(element => 
 console.log(element)
      );

in my case I want to loop through files and add their types to another array:

 Array.from(files).forEach((file) => {
       if(this.mediaTypes.image.includes(file.type)) {
            this.media.images.push(file)
             console.log(this.media.images)
       }
   }

Session variables not working php

I was also facing the same problem i did the following steps to resolve the issue

  1. I edited the file /etc/php.ini and searched the path session.save_path = "/var/lib/php/session" you have to give your session info

2 After that just changed the permission given below *chown root.apache /var/lib/php/session * That's it. These above steps resolve my issue

What is the difference between precision and scale?

precision: Its the total number of digits before or after the radix point. EX: 123.456 here precision is 6.

Scale: Its the total number of digits after the radix point. EX: 123.456 here Scaleis 3

Maven plugin not using Eclipse's proxy settings

Maven plugin uses a settings file where the configuration can be set. Its path is available in Eclipse at Window|Preferences|Maven|User Settings. If the file doesn't exist, create it and put on something like this:

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                      http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>
  <pluginGroups/>
  <servers/>
  <mirrors/>
  <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <host>192.168.1.100</host>
      <port>6666</port>
      <username></username>
      <password></password>
      <nonProxyHosts>localhost|127.0.0.1</nonProxyHosts>
    </proxy>
  </proxies>
  <profiles/>
  <activeProfiles/>
</settings>

After editing the file, it's just a matter of clicking on Update Settings button and it's done. I've just done it and it worked :)

remove empty lines from text file with PowerShell

You can't do replacing, you have to replace SOMETHING with SOMETHING, and you neither have both.

How can I make space between two buttons in same div?

I ended up doing something similar to what mark dibe did, but I needed to figure out the spacing for a slightly different manner.

The col-x classes in bootstrap can be an absolute lifesaver. I ended up doing something similar to this:

<div class="row col-12">
    <div class="col-3">Title</div>
</div>
<div class="row col-12">
    <div class="col-3">Bootstrap Switch</div>
<div>

This allowed me to align titles and input switches in a nicely spaced manner. The same idea can be applied to the buttons and allow you to stop the buttons from touching.

(Side note: I wanted this to be a comment on the above link, but my reputation is not high enough)

Best way to do nested case statement logic in SQL Server

You can combine multiple conditions to avoid the situation:

CASE WHEN condition1 = true AND condition2 = true THEN calculation1 
     WHEN condition1 = true AND condition2 = false 
     ELSE 'what so ever' END,

Laravel 5 PDOException Could Not Find Driver

You should install PDO on your server. Edit your php.ini (look at your phpinfo(), "Loaded Configuration File" line, to find the php.ini file path). Find and uncomment the following line (remove the ; character):

;extension=pdo_mysql.so

Then, restart your Apache server. For more information, please read the documentation.

Pattern matching using a wildcard

glob2rx() converts a pattern including a wildcard into the equivalent regular expression. You then need to pass this regular expression onto one of R's pattern matching tools.

If you want to match "blue*" where * has the usual wildcard, not regular expression, meaning we use glob2rx() to convert the wildcard pattern into a useful regular expression:

> glob2rx("blue*")
[1] "^blue"

The returned object is a regular expression.

Given your data:

x <- c('red','blue1','blue2', 'red2')

we can pattern match using grep() or similar tools:

> grx <- glob2rx("blue*")
> grep(grx, x)
[1] 2 3
> grep(grx, x, value = TRUE)
[1] "blue1" "blue2"
> grepl(grx, x)
[1] FALSE  TRUE  TRUE FALSE

As for the selecting rows problem you posted

> a <- data.frame(x =  c('red','blue1','blue2', 'red2'))
> with(a, a[grepl(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2
> with(a, a[grep(grx, x), ])
[1] blue1 blue2
Levels: blue1 blue2 red red2

or via subset():

> with(a, subset(a, subset = grepl(grx, x)))
      x
2 blue1
3 blue2

Hope that explains what grob2rx() does and how to use it?

MySQL foreach alternative for procedure

Here's the mysql reference for cursors. So I'm guessing it's something like this:

  DECLARE done INT DEFAULT 0;
  DECLARE products_id INT;
  DECLARE result varchar(4000);
  DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

  OPEN cur1;

  REPEAT
    FETCH cur1 INTO products_id;
    IF NOT done THEN
      CALL generate_parameter_list(@product_id, @result);
      SET param = param + "," + result; -- not sure on this syntax
    END IF;
  UNTIL done END REPEAT;

  CLOSE cur1;

  -- now trim off the trailing , if desired

Download single files from GitHub

This is now possible in GitHub for any file. You need to translate your files for raw.github.com. For example, if your file is in your repository at:

https://github.com/<username>/<repo>/some_directory/file.rb

Using wget you can grab the raw file from:

https://raw.github.com/<username>/<repo>/<branch>/some_directory/file.rb

Rails Composer is a great example of this.

Submit a form using jQuery

jQuery("a[id=atag]").click( function(){

    jQuery('#form-id').submit();      

            **OR**

    jQuery(this).parents("#form-id").submit();
});

What's the PowerShell syntax for multiple values in a switch statement?

switch($someString.ToLower())
{
    "yes"   { $_ = "y" }
    "y"     { "You entered Yes." }
    default { "You entered No." }
}

You can arbitrarily branch, cascade, and merge cases in this fashion, as long as the target case is located below/after the case or cases where the $_ variable is respectively reassigned.


n.b. As cute as this behavior is, it seems to reveal that the PowerShell interpreter is not implementing switch/case as efficiently as one might hope or assume. For one, stepping with the ISE debugger suggests that instead of optimized lookup, hashing, or binary branching, each case is tested in turn, like so many if-else statements. (If so, consider putting your most common cases first.) Also, as shown in this answer, PowerShell continues testing cases after having satisfied one. And cruelly enough, there even happens to be a special optimized 'switch' opcode available in .NET CIL which, because of this behavior, PowerShell can't take advantage of.

Maven is not working in Java 8 when Javadoc tags are incomplete

So, save yourself some hours that I didn't and try this if it seems not to work:

 <additionalJOption>-Xdoclint:none</additionalJOption>

The tag is changed for newer versions.

Support for "border-radius" in IE

Use -ms-border-radius: 15px, any element that uses css -ms- is compatible with IE.

How to asynchronously call a method in Java

It's probably not a real solution, but now - in Java 8 - You can make this code look at least a little better using lambda expression.

final String x = "somethingelse";
new Thread(() -> {
        x.matches("something");             
    }
).start();

And You could even do this in one line, still having it pretty readable.

new Thread(() -> x.matches("something")).start();

Returning value from called function in a shell script

A Bash function can't return a string directly like you want it to. You can do three things:

  1. Echo a string
  2. Return an exit status, which is a number, not a string
  3. Share a variable

This is also true for some other shells.

Here's how to do each of those options:

1. Echo strings

lockdir="somedir"
testlock(){
    retval=""
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval="true"
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval="false"
    fi
    echo "$retval"
}

retval=$( testlock )
if [ "$retval" == "true" ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

2. Return exit status

lockdir="somedir"
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
    return "$retval"
}

testlock
retval=$?
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

3. Share variable

lockdir="somedir"
retval=-1
testlock(){
    if mkdir "$lockdir"
    then # Directory did not exist, but it was created successfully
         echo >&2 "successfully acquired lock: $lockdir"
         retval=0
    else
         echo >&2 "cannot acquire lock, giving up on $lockdir"
         retval=1
    fi
}

testlock
if [ "$retval" == 0 ]
then
     echo "directory not created"
else
     echo "directory already created"
fi

What is the difference between UTF-8 and ISO-8859-1?

UTF

UTF is a family of multi-byte encoding schemes that can represent Unicode code points which can be representative of up to 2^31 [roughly 2 billion] characters. UTF-8 is a flexible encoding system that uses between 1 and 4 bytes to represent the first 2^21 [roughly 2 million] code points.

Long story short: any character with a code point/ordinal representation below 127, aka 7-bit-safe ASCII is represented by the same 1-byte sequence as most other single-byte encodings. Any character with a code point above 127 is represented by a sequence of two or more bytes, with the particulars of the encoding best explained here.

ISO-8859

ISO-8859 is a family of single-byte encoding schemes used to represent alphabets that can be represented within the range of 127 to 255. These various alphabets are defined as "parts" in the format ISO-8859-n, the most familiar of these likely being ISO-8859-1 aka 'Latin-1'. As with UTF-8, 7-bit-safe ASCII remains unaffected regardless of the encoding family used.

The drawback to this encoding scheme is its inability to accommodate languages comprised of more than 128 symbols, or to safely display more than one family of symbols at one time. As well, ISO-8859 encodings have fallen out of favor with the rise of UTF. The ISO "Working Group" in charge of it having disbanded in 2004, leaving maintenance up to its parent subcommittee.

Set the Value of a Hidden field using JQuery

Drop the hash - that's for identifying the id attribute.

Using a scanner to accept String input and storing in a String Array

One of the problem with this code is here :

name += contactName[];

This instruction won't insert anything in the array. Instead it will concatenate the current value of the variable name with the string representation of the contactName array.

Instead use this:

contactName[index] = name;

this instruction will store the variable name in the contactName array at the index index.

The second problem you have is that you don't have the variable index.

What you can do is a loop with 12 iterations to fill all your arrays. (and index will be your iteration variable)

Combine two or more columns in a dataframe into a new column with a new name

For inserting a separator:

df$x <- paste(df$n, "-", df$s)

Oracle: If Table Exists

I have been looking for the same but I ended up writing a procedure to help me out:

CREATE OR REPLACE PROCEDURE DelObject(ObjName varchar2,ObjType varchar2)
IS
 v_counter number := 0;   
begin    
  if ObjType = 'TABLE' then
    select count(*) into v_counter from user_tables where table_name = upper(ObjName);
    if v_counter > 0 then          
      execute immediate 'drop table ' || ObjName || ' cascade constraints';        
    end if;   
  end if;
  if ObjType = 'PROCEDURE' then
    select count(*) into v_counter from User_Objects where object_type = 'PROCEDURE' and OBJECT_NAME = upper(ObjName);
      if v_counter > 0 then          
        execute immediate 'DROP PROCEDURE ' || ObjName;        
      end if; 
  end if;
  if ObjType = 'FUNCTION' then
    select count(*) into v_counter from User_Objects where object_type = 'FUNCTION' and OBJECT_NAME = upper(ObjName);
      if v_counter > 0 then          
        execute immediate 'DROP FUNCTION ' || ObjName;        
      end if; 
  end if;
  if ObjType = 'TRIGGER' then
    select count(*) into v_counter from User_Triggers where TRIGGER_NAME = upper(ObjName);
      if v_counter > 0 then          
        execute immediate 'DROP TRIGGER ' || ObjName;
      end if; 
  end if;
  if ObjType = 'VIEW' then
    select count(*) into v_counter from User_Views where VIEW_NAME = upper(ObjName);
      if v_counter > 0 then          
        execute immediate 'DROP VIEW ' || ObjName;        
      end if; 
  end if;
  if ObjType = 'SEQUENCE' then
    select count(*) into v_counter from user_sequences where sequence_name = upper(ObjName);
      if v_counter > 0 then          
        execute immediate 'DROP SEQUENCE ' || ObjName;        
      end if; 
  end if;
end;

Hope this helps

Get the row(s) which have the max value in groups using groupby

For me, the easiest solution would be keep value when count is equal to the maximum. Therefore, the following one line command is enough :

df[df['count'] == df.groupby(['Mt'])['count'].transform(max)]

Removing whitespace from strings in Java

Using Pattern And Matcher it is more Dynamic.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RemovingSpace {

    /**
     * @param args
     * Removing Space Using Matcher
     */
    public static void main(String[] args) {
        String str= "jld fdkjg jfdg ";
        String pattern="[\\s]";
        String replace="";

        Pattern p= Pattern.compile(pattern);
        Matcher m=p.matcher(str);

        str=m.replaceAll(replace);
        System.out.println(str);    
    }
}

Passing parameters to a Bash function

Another way to pass named parameters to Bash... is passing by reference. This is supported as of Bash 4.0

#!/bin/bash
function myBackupFunction(){ # directory options destination filename
local directory="$1" options="$2" destination="$3" filename="$4";
  echo "tar cz ${!options} ${!directory} | ssh root@backupserver \"cat > /mnt/${!destination}/${!filename}.tgz\"";
}

declare -A backup=([directory]=".." [options]="..." [destination]="backups" [filename]="backup" );

myBackupFunction backup[directory] backup[options] backup[destination] backup[filename];

An alternative syntax for Bash 4.3 is using a nameref.

Although the nameref is a lot more convenient in that it seamlessly dereferences, some older supported distros still ship an older version, so I won't recommend it quite yet.

How to force IE to reload javascript?

If you are running ASP.Net, check out the Bundling and Minification module available in ASP.Net 4.5.

http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification

You can declare a "bundle" that points to your javascript file. Every time your file changes, it will generate a new querystring suffix... but will only do so when the file changes. This makes it super simple to deploy updates, because you don't even have to think about updating your tags with new version numbers.

It can also bundle multiple .js files together into one file, and minify them, all in one step. Ditto for css.

Check if process returns 0 with batch file

ERRORLEVEL will contain the return code of the last command. Sadly you can only check >= for it.

Note specifically this line in the MSDN documentation for the If statement:

errorlevel Number

Specifies a true condition only if the previous program run by Cmd.exe returned an exit code equal to or greater than Number.

So to check for 0 you need to think outside the box:

IF ERRORLEVEL 1 GOTO errorHandling
REM no error here, errolevel == 0
:errorHandling

Or if you want to code error handling first:

IF NOT ERRORLEVEL 1 GOTO no_error
REM errorhandling, errorlevel >= 1
:no_error

Further information about BAT programming: http://www.ericphelps.com/batch/ Or more specific for Windows cmd: MSDN using batch files

LocalDate to java.util.Date and vice versa simplest conversion?

Converting LocalDateTime to java.util.Date

    LocalDateTime localDateTime = LocalDateTime.now();

    ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneOffset.systemDefault());

    Instant instant = zonedDateTime.toInstant();

    Date date = Date.from(instant);

System.out.println("Result Date is : "+date);

Ansible date variable

The filter option filters only the first level subkey below ansible_facts

MVC 4 client side validation not working

I had the same problem. It seems that the unobtrusive validation scripts were not loaded (see screenshot at the end). I fixed it by adding at the end of _Layout.cshtml

 @Scripts.Render("~/bundles/jqueryval")

The end result:

   @Scripts.Render("~/bundles/jquery")
   @Scripts.Render("~/bundles/jqueryval")
   @RenderSection("scripts", required: false)

Except for my pretty standard CRUD views everything is Visual studio project template defaults.

Loaded scripts after fixing the problem: enter image description here

ASP.NET MVC get textbox input value

Another way by using ajax method:

View:

@Html.TextBox("txtValue", null, new { placeholder = "Input value" })
<input type="button" value="Start" id="btnStart"  />

<script>
    $(function () {
        $('#btnStart').unbind('click');
        $('#btnStart').on('click', function () {
            $.ajax({
                url: "/yourControllerName/yourMethod",
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify({
                    txtValue: $("#txtValue").val()
                }),
                async: false
            });
       });
   });
</script>

Controller:

[HttpPost]
public EmptyResult YourMethod(string txtValue)
{
    // do what you want with txtValue
    ...
}

Is ASCII code 7-bit or 8-bit?

On Linux man ascii says:

ASCII is the American Standard Code for Information Interchange. It is a 7-bit code.

What is the difference between origin and upstream on GitHub?

In a nutshell answer.

  • origin: the fork
  • upstream: the forked

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

Select the project in Project Explorer, right-click and select Properties -> Java Build Path -> Source -> Check the box for Allow output folders for source folders

Storing Objects in HTML5 localStorage

In theory, it is possible to store objects with functions:

function store (a)
{
  var c = {f: {}, d: {}};
  for (var k in a)
  {
    if (a.hasOwnProperty(k) && typeof a[k] === 'function')
    {
      c.f[k] = encodeURIComponent(a[k]);
    }
  }

  c.d = a;
  var data = JSON.stringify(c);
  window.localStorage.setItem('CODE', data);
}

function restore ()
{
  var data = window.localStorage.getItem('CODE');
  data = JSON.parse(data);
  var b = data.d;

  for (var k in data.f)
  {
    if (data.f.hasOwnProperty(k))
    {
      b[k] = eval("(" + decodeURIComponent(data.f[k]) + ")");
    }
  }

  return b;
}

However, Function serialization/deserialization is unreliable because it is implementation-dependent.

How to pause in C?

I assume you are on Windows. Instead of trying to run your program by double clicking on it's icon or clicking a button in your IDE, open up a command prompt, cd to the directory your program is in, and run it by typing its name on the command line.

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

For a lot of projects, there is actually 0% difference between the different pythons in terms of speed. That is those that are dominated by engineering time and where all pythons have the same amount of library support.

Multiple conditions in ngClass - Angular 4

<section [ngClass]="{'class1': expression1, 'class2': expression2, 
'class3': expression3}">

Don't forget to add single quotes around class names.

Fatal error: Call to undefined function mb_detect_encoding()

Under Windows / WAMP there doesn't seem to be any php_mbstring.dll dependencies on the GD2 extension, the MySQL extensions, nor on external dlls/libs:

deplister.exe ext\php_mbstring.dll

php5ts.dll,OK
MSVCR110.dll,OK
KERNEL32.dll,OK

deplister.exe ext\php_gd2.dll

php5ts.dll,OK
USER32.dll,OK
GDI32.dll,OK
KERNEL32.dll,OK
MSVCR110.dll,OK

Whatever php_mbstring already needs, it's built-in (statically compiled right into the DLL).

Call to undefined function mb_detect_encoding()

This error is also very specific and deterministic...

The function mb_detect_encoding() didn't fail because php_gd, php_mysql, php_mysqli, or another extension was not loaded; it simply was NOT found.

I'm guessing that all the answers that are reported as valid (for Windows / WAMP), that say to load other extensions, to change php.ini extension_dir paths (if this one was wrong to begin with, NO extensions would load), etc, work more due to a) un-commenting the extension = php_mbstring.dll line, or b) restarting Apache or the computer (for changes to take effect).

On Windows, most of the time the problem is that php_mbstring.dll is either:

  • Blocked by Windows. Unblock it by right-clicking it, check Properties.

  • Or PHP can't load php_mbstring.dll due to another version getting loaded (e.g., from some improper PHP DLLs install into C:\Windows\system32), some version mismatch, missing run-time DLLs, etc. Check Apache's and PHP's error log files first for clues.

More in-depth answer here: Call to undefined function mb_detect_encoding

CSS Circle with border

Here is a jsfiddle so you can see an example of this working.

HTML code:

<div class="circle"></div>

CSS code:

_x000D_
_x000D_
.circle {_x000D_
        /*This creates a 1px solid red border around your element(div) */_x000D_
        border:1px solid red;_x000D_
        background-color: #FFFFFF;_x000D_
        height: 100px;_x000D_
        /* border-radius 50% will make it fully rounded. */_x000D_
        border-radius: 50%;_x000D_
        -moz-border-radius:50%;_x000D_
        -webkit-border-radius: 50%;_x000D_
        width: 100px;_x000D_
    }
_x000D_
<div class='circle'></div>
_x000D_
_x000D_
_x000D_

Convert Java String to sql.Timestamp

Have you tried using Timestamp.valueOf(String)? It looks like it should do almost exactly what you want - you just need to change the separator between your date and time to a space, and the ones between hours and minutes, and minutes and hours, to colons:

import java.sql.*;

public class Test {
    public static void main(String[] args) {
        String text = "2011-10-02 18:48:05.123456";
        Timestamp ts = Timestamp.valueOf(text);
        System.out.println(ts.getNanos());
    }
}

Assuming you've already validated the string length, this will convert to the right format:

static String convertSeparators(String input) {
    char[] chars = input.toCharArray();
    chars[10] = ' ';
    chars[13] = ':';
    chars[16] = ':';
    return new String(chars);
}

Alternatively, parse down to milliseconds by taking a substring and using Joda Time or SimpleDateFormat (I vastly prefer Joda Time, but your mileage may vary). Then take the remainder of the string as another string and parse it with Integer.parseInt. You can then combine the values pretty easily:

Date date = parseDateFromFirstPart();
int micros = parseJustLastThreeDigits();

Timestamp ts = new Timestamp(date.getTime());
ts.setNanos(ts.getNanos() + micros * 1000);

Equivalent of explode() to work with strings in MySQL

I try with SUBSTRING_INDEX(string,delimiter,count)

mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', 2);
-> 'www.mysql'

mysql> SELECT SUBSTRING_INDEX('www.mysql.com', '.', -2);
-> 'mysql.com'

see more on mysql.com http://dev.mysql.com/doc/refman/5.1/en/string-functions.html#function_substring-index

How to add a touch event to a UIView?

Swift 3 & Swift 4

import UIKit

extension UIView {
  func addTapGesture(tapNumber: Int, target: Any, action: Selector) {
    let tap = UITapGestureRecognizer(target: target, action: action)
    tap.numberOfTapsRequired = tapNumber
    addGestureRecognizer(tap)
    isUserInteractionEnabled = true
  }
}

Use

yourView.addTapGesture(tapNumber: 1, target: self, action: #selector(yourMethod))

What does the "at" (@) symbol do in Python?

If you are referring to some code in a python notebook which is using Numpy library, then @ operator means Matrix Multiplication. For example:

import numpy as np
def forward(xi, W1, b1, W2, b2):
    z1 = W1 @ xi + b1
    a1 = sigma(z1)
    z2 = W2 @ a1 + b2
    return z2, a1

C# find biggest number

I needed to find a way to do this too, using numbers from different places and not in a collection. I was sure there was a method to do this in c#...though by the looks of it I'm muddling my languages...

Anyway, I ended up writing a couple of generic methods to do it...

    static T Max<T>(params T[] numberItems)
    {
        return numberItems.Max();
    }

    static T Min<T>(params T[] numberItems)
    {
        return numberItems.Min();
    }

...call them this way...

    int intTest = Max(1, 2, 3, 4);
    float floatTest = Min(0f, 255.3f, 12f, -1.2f);

Java: Check if command line arguments are null

To expand upon this point:

It is possible that the args variable itself will be null, but not via normal execution. Normal execution will use java.exe as the entry point from the command line. However, I have seen some programs that use compiled C++ code with JNI to use the jvm.dll, bypassing the java.exe entirely. In this case, it is possible to pass NULL to the main method, in which case args will be null.

I recommend always checking if ((args == null) || (args.length == 0)), or if ((args != null) && (args.length > 0)) depending on your need.

Prevent multiple instances of a given app in .NET?

Using Visual Studio 2005 or 2008 when you create a project for an executable, on the properties windows inside the "Application" panel there is a check box named “Make single instance application” that you can activate to convert the application on a single instance application.

Here is a capture of the window I'm talking of: enter image description here This is a Visual Studio 2008 windows application project.

How can I combine flexbox and vertical scroll in a full-height app?

The current spec says this regarding flex: 1 1 auto:

Sizes the item based on the width/height properties, but makes them fully flexible, so that they absorb any free space along the main axis. If all items are either flex: auto, flex: initial, or flex: none, any positive free space after the items have been sized will be distributed evenly to the items with flex: auto.

http://www.w3.org/TR/2012/CR-css3-flexbox-20120918/#flex-common

It sounds to me like if you say an element is 100px tall, it is treated more like a "suggested" size, not an absolute. Because it is allowed to shrink and grow, it takes up as much space as its allowed to. That's why adding this line to your "main" element works: height: 0 (or any other smallish number).

In Java, how do I get the difference in seconds between 2 dates?

You can use org.apache.commons.lang.time.DateUtils to make it cleaner:

(firstDate.getTime() - secondDate.getTime()) / DateUtils.MILLIS_PER_SECOND

How to get query params from url in Angular 2?

Even though the question specifies version beta 7, this question also comes up as top search result on Google for common phrases like angular 2 query parameters. For that reason here's an answer for the newest router (currently in alpha.7).

The way the params are read has changed dramatically. First you need to inject dependency called Router in your constructor parameters like:

constructor(private router: Router) { }

and after that we can subscribe for the query parameters on our ngOnInit method (constructor is okay too, but ngOnInit should be used for testability) like

this.router
  .routerState
  .queryParams
  .subscribe(params => {
    this.selectedId = +params['id'];
  });

In this example we read the query param id from URL like example.com?id=41.

There are still few things to notice:

  1. Accessing property of params like params['id'] always returns a string, and this can be converted to number by prefixing it with +.
  2. The reason why the query params are fetched with observable is that it allows re-using the same component instance instead of loading a new one. Each time query param is changed, it will cause a new event that we have subscribed for and thus we can react on changes accordingly.

Set the absolute position of a view

Just in case it may help somebody, you may also try this animator ViewPropertyAnimator as below

myView.animate().x(50f).y(100f);

myView.animate().translateX(pixelInScreen) 

Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.

credits to bpr10 answer

Invariant Violation: _registerComponent(...): Target container is not a DOM element

just a wild guess, how about adding to index.html the following:

type="javascript"

like this:

<script type="javascript" src="public/bundle.js"> </script>

For me it worked! :-)

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Perhaps you're looking for the x86_64 ABI?

If that's not precisely what you're after, use 'x86_64 abi' in your preferred search engine to find alternative references.

Python regular expressions return true/false

Here is my method:

import re
# Compile
p = re.compile(r'hi')
# Match and print
print bool(p.match("abcdefghijkl"))

How to slice an array in Bash

Array slicing like in Python (From the rebash library):

array_slice() {
    local __doc__='
    Returns a slice of an array (similar to Python).

    From the Python documentation:
    One way to remember how slices work is to think of the indices as pointing
    between elements, with the left edge of the first character numbered 0.
    Then the right edge of the last element of an array of length n has
    index n, for example:
    ```
    +---+---+---+---+---+---+
    | 0 | 1 | 2 | 3 | 4 | 5 |
    +---+---+---+---+---+---+
    0   1   2   3   4   5   6
    -6  -5  -4  -3  -2  -1
    ```

    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 1:-2 "${a[@]}")
    1 2 3
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 0:1 "${a[@]}")
    0
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice 1:1 "${a[@]}")" ] && echo empty
    empty
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice 2:1 "${a[@]}")" ] && echo empty
    empty
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice -2:-3 "${a[@]}")" ] && echo empty
    empty
    >>> [ -z "$(array.slice -2:-2 "${a[@]}")" ] && echo empty
    empty

    Slice indices have useful defaults; an omitted first index defaults to
    zero, an omitted second index defaults to the size of the string being
    sliced.
    >>> local a=(0 1 2 3 4 5)
    >>> # from the beginning to position 2 (excluded)
    >>> echo $(array.slice 0:2 "${a[@]}")
    >>> echo $(array.slice :2 "${a[@]}")
    0 1
    0 1

    >>> local a=(0 1 2 3 4 5)
    >>> # from position 3 (included) to the end
    >>> echo $(array.slice 3:"${#a[@]}" "${a[@]}")
    >>> echo $(array.slice 3: "${a[@]}")
    3 4 5
    3 4 5

    >>> local a=(0 1 2 3 4 5)
    >>> # from the second-last (included) to the end
    >>> echo $(array.slice -2:"${#a[@]}" "${a[@]}")
    >>> echo $(array.slice -2: "${a[@]}")
    4 5
    4 5

    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -4:-2 "${a[@]}")
    2 3

    If no range is given, it works like normal array indices.
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -1 "${a[@]}")
    5
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -2 "${a[@]}")
    4
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 0 "${a[@]}")
    0
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 1 "${a[@]}")
    1
    >>> local a=(0 1 2 3 4 5)
    >>> array.slice 6 "${a[@]}"; echo $?
    1
    >>> local a=(0 1 2 3 4 5)
    >>> array.slice -7 "${a[@]}"; echo $?
    1
    '
    local start end array_length length
    if [[ $1 == *:* ]]; then
        IFS=":"; read -r start end <<<"$1"
        shift
        array_length="$#"
        # defaults
        [ -z "$end" ] && end=$array_length
        [ -z "$start" ] && start=0
        (( start < 0 )) && let "start=(( array_length + start ))"
        (( end < 0 )) && let "end=(( array_length + end ))"
    else
        start="$1"
        shift
        array_length="$#"
        (( start < 0 )) && let "start=(( array_length + start ))"
        let "end=(( start + 1 ))"
    fi
    let "length=(( end - start ))"
    (( start < 0 )) && return 1
    # check bounds
    (( length < 0 )) && return 1
    (( start < 0 )) && return 1
    (( start >= array_length )) && return 1
    # parameters start with $1, so add 1 to $start
    let "start=(( start + 1 ))"
    echo "${@: $start:$length}"
}
alias array.slice="array_slice"

RAW POST using cURL in PHP

Implementation with Guzzle library:

use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;

$httpClient = new Client();

$response = $httpClient->post(
    'https://postman-echo.com/post',
    [
        RequestOptions::BODY => 'POST raw request content',
        RequestOptions::HEADERS => [
            'Content-Type' => 'application/x-www-form-urlencoded',
        ],
    ]
);

echo(
    $response->getBody()->getContents()
);

PHP CURL extension:

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
    CURLOPT_URL => 'https://postman-echo.com/post',
    CURLOPT_RETURNTRANSFER => true,

    /**
     * Specify POST method
     */
    CURLOPT_POST => true,

    /**
     * Specify request content
     */
    CURLOPT_POSTFIELDS => 'POST raw request content',
]);

$response = curl_exec($curlHandler);

curl_close($curlHandler);

echo($response);

Source code

Convert Unix timestamp to a date string

date -d @1278999698 +'%Y-%m-%d %H:%M:%S' Where the number behind @ is the number in seconds

What is a unix command for deleting the first N characters of a line?

sed 's/^.\{5\}//' logfile 

and you replace 5 by the number you want...it should do the trick...

EDIT if for each line sed 's/^.\{5\}//g' logfile

Best way to combine two or more byte arrays in C#

Can use generics to combine arrays. Following code can easily be expanded to three arrays. This way you never need to duplicate code for different type of arrays. Some of the above answers seem overly complex to me.

private static T[] CombineTwoArrays<T>(T[] a1, T[] a2)
    {
        T[] arrayCombined = new T[a1.Length + a2.Length];
        Array.Copy(a1, 0, arrayCombined, 0, a1.Length);
        Array.Copy(a2, 0, arrayCombined, a1.Length, a2.Length);
        return arrayCombined;
    }

VBA Public Array : how to?

Declare array as global across subs in a application:

Public GlobalArray(10) as String
GlobalArray = Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')

Sub DisplayArray()
    Dim i As Integer

    For i = 0 to UBound(GlobalArray, 1)
        MsgBox GlobalArray(i)

    Next i
End Sub

Method 2: Pass an array to sub. Use ParamArray.

Sub DisplayArray(Name As String, ParamArray Arr() As Variant)
    Dim i As Integer

    For i = 0 To UBound(Arr())
        MsgBox Name & ": " & Arr(i)
    Next i
End Sub

ParamArray must be the last parameter.

JSON response parsing in Javascript to get key/value pair

Ok, here is the JS code:

var data = JSON.parse('{"c":{"a":{"name":"cable - black","value":2}}}')

for (var event in data) {
    var dataCopy = data[event];
    for (data in dataCopy) {
        var mainData = dataCopy[data];
        for (key in mainData) {
            if (key.match(/name|value/)) {
                alert('key : ' + key + ':: value : ' + mainData[key])
            }
        }
    }
}?

FIDDLE HERE

Tool to compare directories (Windows 7)

The tool that richardtz suggests is excellent.

Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.

You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge

Unable to establish SSL connection, how do I fix my SSL cert?

There are a few possibilities:

  1. Your workstation doesn't have the root CA cert used to sign your server's cert. How exactly you fix that depends on what OS you're running and what release, etc. (I suspect this is not related)
  2. Your cert isn't installed properly. If your SSL cert requires an intermediate cert to be presented and you didn't set that up, you can get these warnings.
  3. Are you sure you've enabled SSL on port 443?

For starters, to eliminate (3), what happens if you telnet to that port?

Assuming it's not (3), then depending on your needs you may be fine with ignoring these errors and just passing --no-certificate-check. You probably want to use a regular browser (which generally will bundle the root certs directly) and see if things are happy.

If you want to manually verify the cert, post more details from the openssl s_client output. Or use openssl x509 -text -in /path/to/cert to print it out to your terminal.

Headers and client library minor version mismatch

The root reason for this error is that PHP separated itself from the MySQL Client libraries some time ago. So what's happening (mainly on older compiles of linux) is that people will compile PHP against a given build of the MySQL Client (meaning the version of MySQL installed is irrelevant) and not upgrade (in CentOS this package is listed as mysqlclientXX, where XX represents the package number). This also allows the package maintainer to support lower versions of MySQL. It's a messy way to do it, but it was the only way given how PHP and MySQL use different licensing.

MySQLND solves the problem by using PHP's own native driver (the ND), which no longer relies on MySQL Client. It's also compiled for the version of PHP you're using. This is a better solution all around, if for no other reason that MySQLND is made to have PHP talk to MySQL.

If you can't install MySQLND you can actually safely ignore this error for the most part. It's just more of an FYI notice than anything. It just sounds scary.

Cross-Domain Cookies

Cross-site cookies are allowed if:

  1. the Set-Cookie response header includes SameSite=None; Secure as seen here and here
  2. and your browser hasn't disabled 3rd-party cookies.*

Let's clarify a "domain" vs a "site"; I always find a quick reminder of "anatomy of a URL" helps me. In this URL https://example.com:8888/examples/index.html, remember these main parts (got from this paper):

  • the "protocol": https://
  • the "hostname/host": example.com
  • the "port": 8888
  • the "path":/examples/index.html.

Notice the difference between "path" and "site" for Cookie purposes. "path" is not security-related; "site" is security-related:

path

Servers can set a Path attribute in the Set-Cookie, but it doesn't seem security related:

Note that path was intended for performance, not security. Web pages having the same origin still can access cookie via document.cookie even though the paths are mismatched.

site

The SameSite attribute, according to web.dev article, can restrict or allow cross-site cookies; but what is a "site"?

It's helpful to understand exactly what 'site' means here. The site is the combination of the domain suffix and the part of the domain just before it. For example, the www.web.dev domain is part of the web.dev site.

This means what's to the left of web.dev is a subdomain; yep, www is the subdomain (but the subdomain is a part of the host; see the BONUS reply in this answer)

In this URL https://www.example.com:8888/examples/index.html, remember these parts:

  • the "protocol": https://
  • the "hostname" aka "host": example.com
  • (in cases like "en.wikipedia.org", the entire "en.example.com" is also a hostname)
  • the "port": 8888
  • the "site": www.example.com
  • the "domain": example.com
  • the "subdomain": www
  • the "path": /examples/index.html

Useful links:

(Be careful; I was testing my feature in Chrome Incognito tab; according to my chrome://settings/cookies; my settings were "Block third party cookies in Incognito", so I can't test Cross-site cookies in Incognito.)

a browser is open to the URL chrome://settings/cookies, which shows that "Block third-party cookies in Incognito" setting is set, choose a setting in your browser that will allow third-party cookies

Android difference between Two Dates

Date userDob = new SimpleDateFormat("yyyy-MM-dd").parse(dob);
Date today = new Date();
long diff =  today.getTime() - userDob.getTime();
int numOfDays = (int) (diff / (1000 * 60 * 60 * 24));
int hours = (int) (diff / (1000 * 60 * 60));
int minutes = (int) (diff / (1000 * 60));
int seconds = (int) (diff / (1000));

How to configure "Shorten command line" method for whole project in IntelliJ

Thanks to Rajesh Goel in Android Studio:

Run > Edit Configurations...

enter image description here

Select a test (better to select a parent test class) and set a Shorten command line: option to classpath file. Then OK (or Apply, OK).

enter image description here

Are HTTP headers case-sensitive?

officially, headers are case insensitive, however, it is common practice to capitalize the first letter of every word.
but, because it is common practice, certain programs like IE assume the headers are capitalized.
so while the docs say the are case insensitive, bad programmers have basically changed the docs.

How do I REALLY reset the Visual Studio window layout?

If you want to reset the window layout. Then

go to "WINDOW" -> "RESET WINDOW LAYOUT"

Convert string to List<string> in one line?

string given="Welcome To Programming";
List<string> listItem= given.Split(' ').ToList();//Split according to space in the string and added into the list

output:

Welcome

To 

Programming

How to embed a SWF file in an HTML page?

Thi works on IE, Edge, Firefox, Safari and Chrome.

<object type="application/x-shockwave-flash" data="movie.swf" width="720" height="480">
  <param name="movie" value="movie.swf" />
  <param name="quality" value="high" />
  <param name="bgcolor" value="#000000" />
  <param name="play" value="true" />
  <param name="loop" value="true" />
  <param name="wmode" value="window" />
  <param name="scale" value="showall" />
  <param name="menu" value="true" />
  <param name="devicefont" value="false" />
  <param name="salign" value="" />
  <param name="allowScriptAccess" value="sameDomain" />
  <a href="http://www.adobe.com/go/getflash">
    <img src="http://www.adobe.com/images/shared/download_buttons/get_flash_player.gif" alt="Get Adobe Flash player" />
  </a>
</object>

How to call getResources() from a class which has no context?

A Context is a handle to the system; it provides services like resolving resources, obtaining access to databases and preferences, and so on. It is an "interface" that allows access to application specific resources and class and information about application environment. Your activities and services also extend Context to they inherit all those methods to access the environment information in which the application is running.

This means you must have to pass context to the specific class if you want to get/modify some specific information about the resources. You can pass context in the constructor like

public classname(Context context, String s1) 
{
...
}

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

How do I reset a sequence in Oracle?

In my project, once it happened that someone manually entered the records without using sequence, hence I have to reset sequence value manually, for which I wrote below sql code snippet:

declare
max_db_value number(10,0);
cur_seq_value number(10,0);
counter number(10,0);
difference number(10,0);
dummy_number number(10);

begin

-- enter table name here
select max(id) into max_db_value from persons;
-- enter sequence name here
select last_number into cur_seq_value from user_sequences where  sequence_name = 'SEQ_PERSONS';

difference  := max_db_value - cur_seq_value;

 for counter in 1..difference
 loop
    -- change sequence name here as well
    select SEQ_PERSONS.nextval into dummy_number from dual;
 end loop;
end;

Please note, the above code will work if the sequence is lagging.

adding and removing classes in angularJs using ng-click

You just need to bind a variable into the directive "ng-class" and change it from the controller. Here is an example of how to do this:

_x000D_
_x000D_
var app = angular.module("ap",[]);_x000D_
_x000D_
app.controller("con",function($scope){_x000D_
  $scope.class = "red";_x000D_
  $scope.changeClass = function(){_x000D_
    if ($scope.class === "red")_x000D_
      $scope.class = "blue";_x000D_
    else_x000D_
      $scope.class = "red";_x000D_
  };_x000D_
});
_x000D_
.red{_x000D_
  color:red;_x000D_
}_x000D_
_x000D_
.blue{_x000D_
  color:blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<body ng-app="ap" ng-controller="con">_x000D_
  <div ng-class="class">{{class}}</div>_x000D_
  <button ng-click="changeClass()">Change Class</button>    _x000D_
</body>
_x000D_
_x000D_
_x000D_

Here is the example working on jsFiddle

How can I make a JPA OneToOne relation lazy

As already perfectly explained by ChssPly76, Hibernate's proxies don't help with unconstrained (nullable) one-to-one associations, BUT there is a trick explained here to avoid to set up instrumentation. The idea is to fool Hibernate that the entity class which we want to use has been already instrumented: you instrument it manually in the source code. It's easy! I've implemented it with CGLib as bytecode provider and it works (ensure that you configure lazy="no-proxy" and fetch="select", not "join", in your HBM).

I think this is a good alternative to real (I mean automatic) instrumentation when you have just one one-to-one nullable relation that you want to make lazy. The main drawback is that the solution depends on the bytecode provider you are using, so comment your class accurately because you could have to change the bytecode provider in the future; of course, you are also modifying your model bean for a technical reason and this is not fine.

Java logical operator short-circuiting

if(demon!=0&& num/demon>10)

Since the short-circuit form of AND(&&) is used, there is no risk of causing a run-time exception when demon is zero.

Ref. Java 2 Fifth Edition by Herbert Schildt

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

How to select only 1 row from oracle sql?

I found this "solution" hidden in one of the comments. Since I was looking it up for a while, I'd like to highlight it a bit (can't yet comment or do such stuff...), so this is what I used:

SELECT * FROM (SELECT [Column] FROM [Table] ORDER BY [Date] DESC) WHERE ROWNUM = 1

This will print me the desired [Column] entry from the newest entry in the table, assuming that [Date] is always inserted via SYSDATE.

Android Studio does not show layout preview

Changing the theme(near the android symbol for changing API version) from AppTheme to anything else like DeviceDefault or Holo fixed the problem easily.

How to preSelect an html dropdown list with php?

First of all give a name to your select. Then do:

<select name="my_select">
<option value="1" <?= ($_POST['my_select'] == "1")? "selected":"";?>>Yes</options>
<option value="2" <?= ($_POST['my_select'] == "2")? "selected":"";?>>No</options>
<option value="3" <?= ($_POST['my_select'] == "3")? "selected":"";?>>Fine</options>
</select>

What that does is check if what was selected is the same for each and when its found echo "selected".

scikit-learn random state in splitting dataset

The random_state splits a randomly selected data but with a twist. And the twist is the order of the data will be same for a particular value of random_state.You need to understand that it's not a bool accpeted value. starting from 0 to any integer no, if you pass as random_state,it'll be a permanent order for it. Ex: the order you will get in random_state=0 remain same. After that if you execuit random_state=5 and again come back to random_state=0 you'll get the same order. And like 0 for all integer will go same. How ever random_state=None splits randomly each time.

If still having doubt watch this

Convert a tensor to numpy array in Tensorflow?

I have faced and solved the tensor->ndarray conversion in the specific case of tensors representing (adversarial) images, obtained with cleverhans library/tutorials.

I think that my question/answer (here) may be an helpful example also for other cases.

I'm new with TensorFlow, mine is an empirical conclusion:

It seems that tensor.eval() method may need, in order to succeed, also the value for input placeholders. Tensor may work like a function that needs its input values (provided into feed_dict) in order to return an output value, e.g.

array_out = tensor.eval(session=sess, feed_dict={x: x_input})

Please note that the placeholder name is x in my case, but I suppose you should find out the right name for the input placeholder. x_input is a scalar value or array containing input data.

In my case also providing sess was mandatory.

My example also covers the matplotlib image visualization part, but this is OT.

Maven Error: Could not find or load main class

For me the problem was nothing to do with Maven but to do with how I was running the .jar. I wrote some code and packaged it as a .jar with Maven. I ran it with

java target/gs-maven-0.1.0.jar

and got the error in the OP. Actually you need the -jar option:

java -jar target/gs-maven-0.1.0.jar

Why is null an object and what's the difference between null and undefined?

For example window.someWeirdProperty is undefined, so

"window.someWeirdProperty === null" evaluates to false while

"window.someWeirdProperty === undefined" evaluates to true.

Moreover checkif if (!o) is not the same as checking if (o == null) for o being false.

How to resolve git status "Unmerged paths:"?

All you should need to do is:

# if the file in the right place isn't already committed:
git add <path to desired file>

# remove the "both deleted" file from the index:
git rm --cached ../public/images/originals/dog.ai

# commit the merge:
git commit

jQuery .val() vs .attr("value")

In order to get the value of any input field, you should always use $element.val() because jQuery handles to retrieve the correct value based on the browser of the element type.

How do you run a single query through mysql from the command line?

mysql -u <user> -p -e "select * from schema.table"

Difference between pre-increment and post-increment in a loop?

i++ ; ++i ; both are similar as they are not used in an expression.

class A {

     public static void main (String []args) {

     int j = 0 ;
     int k = 0 ;
     ++j;
     k++;
    System.out.println(k+" "+j);

}}

prints out :  1 1

Spring Data JPA find by embedded object property

According to me, Spring doesn't handle all the cases with ease. In your case the following should do the trick

Page<QueuedBook> findByBookIdRegion(Region region, Pageable pageable);  

or

Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);

However, it also depends on the naming convention of fields that you have in your @Embeddable class,

e.g. the following field might not work in any of the styles that mentioned above

private String cRcdDel;

I tried with both the cases (as follows) and it didn't work (it seems like Spring doesn't handle this type of naming conventions(i.e. to many Caps , especially in the beginning - 2nd letter (not sure about if this is the only case though)

Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable); 

or

Page<QueuedBook> findByBookIdCRcdDel(String cRcdDel, Pageable pageable);

When I renamed column to

private String rcdDel;

my following solutions work fine without any issue:

Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable); 

OR

Page<QueuedBook> findByBookIdRcdDel(String rcdDel, Pageable pageable);

Where do I get servlet-api.jar from?

Grab it from here

Just choose required version and click 'Binary'. e.g direct link to version 2.5

Stop and Start a service via batch or cmd file?

I just used Jonas' example above and created full list of 0 to 24 errorlevels. Other post is correct that net start and net stop only use errorlevel 0 for success and 2 for failure.

But this is what worked for me:

net stop postgresql-9.1
if %errorlevel% == 2 echo Access Denied - Could not stop service
if %errorlevel% == 0 echo Service stopped successfully
echo Errorlevel: %errorlevel%

Change stop to start and works in reverse.

C# delete a folder and all files and folders within that folder

Err, what about just calling Directory.Delete(path, true); ?

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

fix json values, it's add \ before u{xxx} to all +" "

  $item = preg_replace_callback('/"(.+?)":"(u.+?)",/', function ($matches) {
        $matches[2] = preg_replace('/(u)/', '\u', $matches[2]);
            $matches[2] = preg_replace('/(")/', '&quot;', $matches[2]); 
            $matches[2] = json_decode('"' . $matches[2] . '"'); 
            return '"' . $matches[1] . '":"' . $matches[2] . '",';
        }, $item);

Converting Numpy Array to OpenCV Array

This is what worked for me...

import cv2
import numpy as np

#Created an image (really an ndarray) with three channels 
new_image = np.ndarray((3, num_rows, num_cols), dtype=int)

#Did manipulations for my project where my array values went way over 255
#Eventually returned numbers to between 0 and 255

#Converted the datatype to np.uint8
new_image = new_image.astype(np.uint8)

#Separated the channels in my new image
new_image_red, new_image_green, new_image_blue = new_image

#Stacked the channels
new_rgb = np.dstack([new_image_red, new_image_green, new_image_blue])

#Displayed the image
cv2.imshow("WindowNameHere", new_rgbrgb)
cv2.waitKey(0)

Fastest way to convert an iterator to a list

@Robino was suggesting to add some tests which make sense, so here is a simple benchmark between 3 possible ways (maybe the most used ones) to convert an iterator to a list:

  1. by type constructor

list(my_iterator)

  1. by unpacking

[*my_iterator]

  1. using list comprehension

[e for e in my_iterator]

I have been using simple_bechmark library

from simple_benchmark import BenchmarkBuilder
from heapq import nsmallest

b = BenchmarkBuilder()

@b.add_function()
def convert_by_type_constructor(size):
    list(iter(range(size)))

@b.add_function()
def convert_by_list_comprehension(size):
    [e for e in iter(range(size))]

@b.add_function()
def convert_by_unpacking(size):
    [*iter(range(size))]


@b.add_arguments('Convert an iterator to a list')
def argument_provider():
    for exp in range(2, 22):
        size = 2**exp
        yield size, size

r = b.run()
r.plot()

enter image description here

As you can see there is very hard to make a difference between conversion by the constructor and conversion by unpacking, conversion by list comprehension is the “slowest” approach.


I have been testing also across different Python versions (3.6, 3.7, 3.8, 3.9) by using the following simple script:

import argparse
import timeit

parser = argparse.ArgumentParser(
    description='Test convert iterator to list')
parser.add_argument(
    '--size', help='The number of elements from iterator')

args = parser.parse_args()

size = int(args.size)
repeat_number = 10000

# do not wait too much if the size is too big
if size > 10000:
    repeat_number = 100


def test_convert_by_type_constructor():
    list(iter(range(size)))


def test_convert_by_list_comprehension():
    [e for e in iter(range(size))]


def test_convert_by_unpacking():
    [*iter(range(size))]


def get_avg_time_in_ms(func):
    avg_time = timeit.timeit(func, number=repeat_number) * 1000 / repeat_number
    return round(avg_time, 6)


funcs = [test_convert_by_type_constructor,
         test_convert_by_unpacking, test_convert_by_list_comprehension]

print(*map(get_avg_time_in_ms, funcs))

The script will be executed via a subprocess from a Jupyter Notebook (or a script), the size parameter will be passed through command-line arguments and the script results will be taken from standard output.

from subprocess import PIPE, run

import pandas

simple_data = {'constructor': [], 'unpacking': [], 'comprehension': [],
        'size': [], 'python version': []}


size_test = 100, 1000, 10_000, 100_000, 1_000_000
for version in ['3.6', '3.7', '3.8', '3.9']:
    print('test for python', version)
    for size in size_test:
        command = [f'python{version}', 'perf_test_convert_iterator.py', f'--size={size}']
        result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
        constructor, unpacking,  comprehension = result.stdout.split()
        
        simple_data['constructor'].append(float(constructor))
        simple_data['unpacking'].append(float(unpacking))
        simple_data['comprehension'].append(float(comprehension))
        simple_data['python version'].append(version)
        simple_data['size'].append(size)

df_ = pandas.DataFrame(simple_data)
df_

enter image description here

You can get my full notebook from here.

In most of the cases, in my tests, unpacking shows to be faster, but the difference is so small that the results may change from a run to the other. Again, the comprehension approach is the slowest, in fact, the other 2 methods are up to ~ 60% faster.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Although I use the following code.

.carousel.fade
{
    opacity: 1;

    .item
    {
        -moz-transition: opacity ease-in-out .7s;
        -o-transition: opacity ease-in-out .7s;
        -webkit-transition: opacity ease-in-out .7s;
        transition: opacity ease-in-out .7s;
        left: 0 !important;
        opacity: 0;
        top:0;
        position:absolute;
        width: 100%;
        display:block !important;
        z-index:1;
        &:first-child{
            top:auto;
            position:relative;
        }

        &.active
        {
            opacity: 1;
            -moz-transition: opacity ease-in-out .7s;
            -o-transition: opacity ease-in-out .7s;
            -webkit-transition: opacity ease-in-out .7s;
            transition: opacity ease-in-out .7s;
            z-index:2;
        }
    }
}

Then change the class on the carousel from "carousel slide" to "carousel fade". This works in safari, chrome, firefox, and IE 10. It will correctly downgrade in IE 9, however, the nice face effect doesn't happen.

Edit: Since this answer has gotten so popular I've added the following which rewritten as pure CSS instead of the above which was LESS:

.carousel.fade {
  opacity: 1;
}
.carousel.fade .item {
  -moz-transition: opacity ease-in-out .7s;
  -o-transition: opacity ease-in-out .7s;
  -webkit-transition: opacity ease-in-out .7s;
  transition: opacity ease-in-out .7s;
  left: 0 !important;
  opacity: 0;
  top:0;
  position:absolute;
  width: 100%;
  display:block !important;
  z-index:1;
}
.carousel.fade .item:first-child {
  top:auto;
  position:relative;
}
.carousel.fade .item.active {
  opacity: 1;
  -moz-transition: opacity ease-in-out .7s;
  -o-transition: opacity ease-in-out .7s;
  -webkit-transition: opacity ease-in-out .7s;
  transition: opacity ease-in-out .7s;
  z-index:2;
}

How to fix docker: Got permission denied issue

you can follow these steps and this will work for you:

  1. create a docker group sudo groupadd docker
  2. add your user to this group sudo usermod -aG docker $USER
  3. list the groups to make sure that docker group created successfully by running this command groups
  4. run the following command also to change the session for docker group newgrp docker
  5. change the group ownership for file docker.socksudo chown root:docker /var/run/docker.sock
  6. change the ownership for .docker directory sudo chown "$USER":"$USER" /home/"$USER"/.docker -R
  7. finally sudo chmod g+rwx "$HOME/.docker" -R

After that test you can run docker ps -a

How can I select from list of values in Oracle

Starting from Oracle 12.2, you don't need the TABLE function, you can directly select from the built-in collection.

SQL> select * FROM sys.odcinumberlist(5,2,6,3,78);

COLUMN_VALUE
------------
           5
           2
           6
           3
          78

SQL> select * FROM sys.odcivarchar2list('A','B','C','D');

COLUMN_VALUE
------------
A
B
C
D

How to convert an int value to string in Go?

fmt.Sprintf("%v",value);

If you know the specific type of value use the corresponding formatter for example %d for int

More info - fmt

Toolbar navigation icon never set

In case you don't wish to set the toolbar as the action bar, you can use this:

        val toggle = ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
        toggle.isDrawerSlideAnimationEnabled = false
        toggle.isDrawerIndicatorEnabled = false
        toggle.setHomeAsUpIndicator(AppCompatResources.getDrawable(this, ...))
        drawer!!.addDrawerListener(toggle)
        toggle.setToolbarNavigationClickListener {
            setDrawerOpened(!isDrawerOpened())
        }
        toggle.syncState()

fun setDrawerOpened(open: Boolean) {
    if (open == drawerLayout.isDrawerOpen(GravityCompat.START))
        return
    if (open)
        drawerLayout.openDrawer(GravityCompat.START)
    else drawerLayout.closeDrawer(GravityCompat.START)
}