Programs & Examples On #Online store

Multi value Dictionary

If you are trying to group values together this may be a great opportunity to create a simple struct or class and use that as the value in a dictionary.

public struct MyValue
{
    public object Value1;
    public double Value2;
}

then you could have your dictionary

var dict = new Dictionary<int, MyValue>();

you could even go a step further and implement your own dictionary class that will handle any special operations that you would need. for example if you wanted to have an Add method that accepted an int, object, and double

public class MyDictionary : Dictionary<int, MyValue>
{
    public void Add(int key, object value1, double value2)
    {
        MyValue val;
        val.Value1 = value1;
        val.Value2 = value2;
        this.Add(key, val);
    }
}

then you could simply instantiate and add to the dictionary like so and you wouldn't have to worry about creating 'MyValue' structs:

var dict = new MyDictionary();
dict.Add(1, new Object(), 2.22);

Converting an int into a 4 byte char array (C)

The problem is arising as unsigned char is a 4 byte number not a 1 byte number as many think, so change it to

union {
unsigned int integer;
char byte[4];
} temp32bitint;

and cast while printing, to prevent promoting to 'int' (which C does by default)

printf("%u, %u \n", (unsigned char)Buffer[0], (unsigned char)Buffer[1]);

How to spawn a process and capture its STDOUT in .NET?

Here's code that I've verified to work. I use it for spawning MSBuild and listening to its output:

process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data);
process.Start();
process.BeginOutputReadLine();

How add unique key to existing table (with non uniques rows)

The proper syntax would be - ALTER TABLE Table_Name ADD UNIQUE (column_name)

Example

ALTER TABLE  0_value_addition_setup ADD UNIQUE (`value_code`)

How do I get the object if it exists, or None if it does not exist?

From django docs

get() raises a DoesNotExist exception if an object is not found for the given parameters. This exception is also an attribute of the model class. The DoesNotExist exception inherits from django.core.exceptions.ObjectDoesNotExist

You can catch the exception and assign None to go.

from django.core.exceptions import ObjectDoesNotExist
try:
    go  = Content.objects.get(name="baby")
except ObjectDoesNotExist:
    go = None

Exit single-user mode

I tried this is working

ALTER DATABASE dbName SET MULTI_USER WITH ROLLBACK IMMEDIATE

How do I fix a "Performance counter registry hive consistency" when installing SQL Server R2 Express?

open Command line and type lodctr /r The p. counter will be resotred\recreated.

There is no need to skip it. http://technet.microsoft.com/en-us/library/cc774958.aspx

Length of the String without using length() method

Just to complete this with the most stupid method I can come up with: Generate all possible strings of length 1, use equals to compare them to the original string; if they are equal, the string length is 1. If no string matches, generate all possible strings of length 2, compare them, for string length 2. Etc. Continue until you find the string length or the universe ends, whatever happens first.

Create intermediate folders if one doesn't exist

A nice Java 7+ answer from Benoit Blanchon can be found here:

With Java 7, you can use Files.createDirectories().

For instance:

Files.createDirectories(Paths.get("/path/to/directory"));

How to merge 2 List<T> and removing duplicate values from it in C#

Have you had a look at Enumerable.Union

This method excludes duplicates from the return set. This is different behavior to the Concat method, which returns all the elements in the input sequences including duplicates.

List<int> list1 = new List<int> { 1, 12, 12, 5};
List<int> list2 = new List<int> { 12, 5, 7, 9, 1 };
List<int> ulist = list1.Union(list2).ToList();

// ulist output : 1, 12, 5, 7, 9

pandas dataframe convert column type to string or categorical

Prior answers focused on nominal data (e.g. unordered). If there is a reason to impose order for an ordinal variable, then one would use:

# Transform to category
df['zipcode_category'] = df['zipcode_category'].astype('category')

# Add ordered category
df['zipcode_ordered'] = df['zipcode_category']

# Setup the ordering
df.zipcode_ordered.cat.set_categories(
    new_categories = [90211, 90210], ordered = True, inplace = True
)

# Output IDs
df['zipcode_ordered_id'] = df.zipcode_ordered.cat.codes
print(df)
#  zipcode_category zipcode_ordered  zipcode_ordered_id
#            90210           90210                   1
#            90211           90211                   0

More details on setting ordered categories can be found at the pandas website:

https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#sorting-and-order

When does Java's Thread.sleep throw InterruptedException?

A solid and easy way to handle it in single threaded code would be to catch it and retrow it in a RuntimeException, to avoid the need to declare it for every method.

Preprocessing in scikit learn - single sample - Depreciation warning

Just listen to what the warning is telling you:

Reshape your data either X.reshape(-1, 1) if your data has a single feature/column and X.reshape(1, -1) if it contains a single sample.

For your example type(if you have more than one feature/column):

temp = temp.reshape(1,-1) 

For one feature/column:

temp = temp.reshape(-1,1)

Post to another page within a PHP script

CURL method is very popular so yes it is good to use it. You could also explain more those codes with some extra comments because starters could understand them.

Determining the current foreground application from a background task or service

Do something like this:

int showLimit = 20;

/* Get all Tasks available (with limit set). */
ActivityManager mgr = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> allTasks = mgr.getRunningTasks(showLimit);
/* Loop through all tasks returned. */
for (ActivityManager.RunningTaskInfo aTask : allTasks) 
{                  
    Log.i("MyApp", "Task: " + aTask.baseActivity.getClassName()); 
    if (aTask.baseActivity.getClassName().equals("com.android.email.activity.MessageList")) 
        running=true;
}

Business logic in MVC

Model = code for CRUD database operations.

Controller = responds to user actions, and passes the user requests for data retrieval or delete/update to the model, subject to the business rules specific to an organization. These business rules could be implemented in helper classes, or if they are not too complex, just directly in the controller actions. The controller finally asks the view to update itself so as to give feedback to the user in the form of a new display, or a message like 'updated, thanks', etc.,

View = UI that is generated based on a query on the model.

There are no hard and fast rules regarding where business rules should go. In some designs they go into model, whereas in others they are included with the controller. But I think it is better to keep them with the controller. Let the model worry only about database connectivity.

SQL update query using joins

MySQL: In general, make necessary changes par your requirement:

UPDATE
    shopping_cart sc
    LEFT JOIN
    package pc ON sc. package_id = pc.id    
SET
    sc. amount = pc.amount

LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

If you have a "Win32 project" + defined a WinMain and your SubSystem linker setting is set to WINDOWS you can still get this linker error in case somebody set the "Additional Options" in the linker settings to "/SUBSYSTEM:CONSOLE" (looks like this additional setting is preferred over the actual SubSystem setting.

Test if registry value exists

My version:

Function Test-RegistryValue($Key, $Name)
{
    (Get-ChildItem (Split-Path -Parent -Path $Key) | Where-Object {$_.PSChildName -eq (Split-Path -Leaf $Key)}).Property -contains $Name
}

Change size of axes title and labels in ggplot2

To change the size of (almost) all text elements, in one place, and synchronously, rel() is quite efficient:
g+theme(text = element_text(size=rel(3.5))

You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)), strip.text.x = element_text(size=rel(3.5)), strip.text.y = element_text(size=rel(3.5)))

How to flatten only some dimensions of a numpy array

Take a look at numpy.reshape .

>>> arr = numpy.zeros((50,100,25))
>>> arr.shape
# (50, 100, 25)

>>> new_arr = arr.reshape(5000,25)
>>> new_arr.shape   
# (5000, 25)

# One shape dimension can be -1. 
# In this case, the value is inferred from 
# the length of the array and remaining dimensions.
>>> another_arr = arr.reshape(-1, arr.shape[-1])
>>> another_arr.shape
# (5000, 25)

How to perform a real time search and filter on a HTML table

If you can separate html and data, you can use external libraries like datatables or the one i created. https://github.com/thehitechpanky/js-bootstrap-tables

This library uses keyup function to reload tabledata and hence it appears to work like search.

function _addTableDataRows(paramObjectTDR) {
    let { filterNode, limitNode, bodyNode, countNode, paramObject } = paramObjectTDR;
    let { dataRows, functionArray } = paramObject;
    _clearNode(bodyNode);
    if (typeof dataRows === `string`) {
        bodyNode.insertAdjacentHTML(`beforeend`, dataRows);
    } else {
        let filterTerm;
        if (filterNode) {
            filterTerm = filterNode.value.toLowerCase();
        }
        let serialNumber = 0;
        let limitNumber = 0;
        let rowNode;
        dataRows.forEach(currentRow => {
            if (!filterNode || _filterData(filterTerm, currentRow)) {
                serialNumber++;
                if (!limitNode || limitNode.value === `all` || limitNode.value >= serialNumber) {
                    limitNumber++;
                    rowNode = _getNode(`tr`);
                    bodyNode.appendChild(rowNode);
                    _addData(rowNode, serialNumber, currentRow, `td`);
                }
            }
        });
        _clearNode(countNode);
        countNode.insertAdjacentText(`beforeend`, `Showing 1 to ${limitNumber} of ${serialNumber} entries`);
    }
    if (functionArray) {
        functionArray.forEach(currentObject => {
            let { className, eventName, functionName } = currentObject;
            _attachFunctionToClassNodes(className, eventName, functionName);
        });
    }
}

Java unsupported major minor version 52.0

You have to compile with Java 1.7. But if you have *.jsp files, you should also completely remove Java 1.8 from the system. If you use Mac, here is how you can do it.

Spring 3 MVC resources and tag <mvc:resources />

@Nanocom's answer works for me. It may be that lines have to be at the end, or could be because has to be after of some the bean class like this:

<bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping" />
<bean class="org.springframework.web.servlet.resource.ResourceHttpRequestHandler" />    

<mvc:resources mapping="/resources/**" 
               location="/resources/" 
               cache-period="10000" />

How to prevent favicon.ico requests?

You can use .htaccess or server directives to deny access to favicon.ico, but the server will send an access denied reply to the browser and this still slows page access.

You can stop the browser requesting favicon.ico when a user returns to your site, by getting it to stay in the browser cache.

First, provide a small favicon.ico image, could be blank, but as small as possible. I made a black and white one under 200 bytes. Then, using .htaccess or server directives, set the file Expires header a month or two in the future. When the same user comes back to your site it will be loaded from the browser cache and no request will go to your site. No more 404's in the server logs too.

If you have control over a complete Apache server or maybe a virtual server you can do this:-

If the server document root is say /var/www/html then add this to /etc/httpd/conf/httpd.conf:-

Alias /favicon.ico "/var/www/html/favicon.ico"
<Directory "/var/www/html">
    <Files favicon.ico>
       ExpiresActive On
       ExpiresDefault "access plus 1 month"
    </Files>
</Directory>

Then a single favicon.ico will work for all the virtual hosted sites since you are aliasing it. It will be drawn from the browser cache for a month after the users visit.

For .htaccess this is reported to work (not checked by me):-

AddType image/x-icon .ico
ExpiresActive On
ExpiresByType image/x-icon "access plus 1 month"

Unable to begin a distributed transaction

If your Destination server is on another cloud or data-center then need to add host-entry of MSDTC service(Destination Server) in your source server.

Try this one if problem doesn't resolved, After enable the MSDTC settings.

from list of integers, get number closest to a given value

>>> takeClosest = lambda num,collection:min(collection,key=lambda x:abs(x-num))
>>> takeClosest(5,[4,1,88,44,3])
4

A lambda is a special way of writing an "anonymous" function (a function that doesn't have a name). You can assign it any name you want because a lambda is an expression.

The "long" way of writing the the above would be:

def takeClosest(num,collection):
   return min(collection,key=lambda x:abs(x-num))

Using Python's list index() method on a list of tuples or objects?

No body suggest lambdas?

Y try this and works. I come to this post searching answer. I don't found that I like, but I feel a insingth :P

    l #[['rana', 1, 1], ['pato', 1, 1], ['perro', 1, 1]]

    map(lambda x:x[0], l).index("pato") #1 

Edit to add examples:

   l=[['rana', 1, 1], ['pato', 2, 1], ['perro', 1, 1], ['pato', 2, 2], ['pato', 2, 2]]

extract all items by condition: filter(lambda x:x[0]=="pato", l) #[['pato', 2, 1], ['pato', 2, 2], ['pato', 2, 2]]

extract all items by condition with index:

    >>> filter(lambda x:x[1][0]=="pato", enumerate(l))
    [(1, ['pato', 2, 1]), (3, ['pato', 2, 2]), (4, ['pato', 2, 2])]
    >>> map(lambda x:x[1],_)
    [['pato', 2, 1], ['pato', 2, 2], ['pato', 2, 2]]

Note:_ variable only works in interactive interpreter y normal text file _ need explicti assign, ie _=filter(lambda x:x[1][0]=="pato", enumerate(l))

How to stop event bubbling on checkbox click

Don't forget IE:

if (event.stopPropagation) {    // standard
        event.stopPropagation();
    } else {    // IE6-8
        event.cancelBubble = true;
}

How to properly URL encode a string in PHP?

Based on what type of RFC standard encoding you want to perform or if you need to customize your encoding you might want to create your own class.

/**
 * UrlEncoder make it easy to encode your URL
 */
class UrlEncoder{
    public const STANDARD_RFC1738 = 1;
    public const STANDARD_RFC3986 = 2;
    public const STANDARD_CUSTOM_RFC3986_ISH = 3;
    // add more here

    static function encode($string, $rfc){
        switch ($rfc) {
            case self::STANDARD_RFC1738:
                return  urlencode($string);
                break;
            case self::STANDARD_RFC3986:
                return rawurlencode($string);
                break;
            case self::STANDARD_CUSTOM_RFC3986_ISH:
                // Add your custom encoding
                $entities = ['%21', '%2A', '%27', '%28', '%29', '%3B', '%3A', '%40', '%26', '%3D', '%2B', '%24', '%2C', '%2F', '%3F', '%25', '%23', '%5B', '%5D'];
                $replacements = ['!', '*', "'", "(", ")", ";", ":", "@", "&", "=", "+", "$", ",", "/", "?", "%", "#", "[", "]"];
                return str_replace($entities, $replacements, urlencode($string));
                break;
            default:
                throw new Exception("Invalid RFC encoder - See class const for reference");
                break;
        }
    }
}

Use example:

$dataString = "https://www.google.pl/search?q=PHP is **great**!&id=123&css=#kolo&[email protected])";

$dataStringUrlEncodedRFC1738 = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_RFC1738);
$dataStringUrlEncodedRFC3986 = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_RFC3986);
$dataStringUrlEncodedCutom = UrlEncoder::encode($dataString, UrlEncoder::STANDARD_CUSTOM_RFC3986_ISH);

Will output:

string(126) "https%3A%2F%2Fwww.google.pl%2Fsearch%3Fq%3DPHP+is+%2A%2Agreat%2A%2A%21%26id%3D123%26css%3D%23kolo%26email%3Dme%40liszka.com%29"
string(130) "https%3A%2F%2Fwww.google.pl%2Fsearch%3Fq%3DPHP%20is%20%2A%2Agreat%2A%2A%21%26id%3D123%26css%3D%23kolo%26email%3Dme%40liszka.com%29"
string(86)  "https://www.google.pl/search?q=PHP+is+**great**!&id=123&css=#kolo&[email protected])"

* Find out more about RFC standards: https://datatracker.ietf.org/doc/rfc3986/ and urlencode vs rawurlencode?

What is the best way to modify a list in a 'foreach' loop?

Make a copy of the enumeration, using an IEnumerable extension method in this case, and enumerate over it. This would add a copy of every element in every inner enumerable to that enumeration.

foreach(var item in Enumerable)
{
    foreach(var item2 in item.Enumerable.ToList())
    {
        item.Add(item2)
    }
}

Validate form field only on submit or user input

Invoking of validation on form element could be handled by triggering change event on this element:

a) exemple: trigger change on separated element in form

$scope.formName.elementName.$$element.change();

b) exemple: trigger change event for each of form elements for example on ng-submit, ng-click, ng-blur ...

vm.triggerChangeForFormElements = function() {
    // trigger change event for each of form elements
    angular.forEach($scope.formName, function (element, name) {
        if (!name.startsWith('$')) {
            element.$$element.change();
        }
    });
};

c) and one more way for that

    var handdleChange = function(form){
        var formFields = angular.element(form)[0].$$controls;
        angular.forEach(formFields, function(field){
            field.$$element.change();
        });
    };

Calculating the distance between 2 points

measure the square distance from one point to the other:

((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) < d*d

where d is the distance, (x1,y1) are the coordinates of the 'base point' and (x2,y2) the coordinates of the point you want to check.

or if you prefer:

(Math.Pow(x1-x2,2)+Math.Pow(y1-y2,2)) < (d*d);

Noticed that the preferred one does not call Pow at all for speed reasons, and the second one, probably slower, as well does not call Math.Sqrt, always for performance reasons. Maybe such optimization are premature in your case, but they are useful if that code has to be executed a lot of times.

Of course you are talking in meters and I supposed point coordinates are expressed in meters too.

Remove values from select list based on condition

if(frm.product.value=="F"){
    var select = document.getElementsByName('val')[0];
    select.remove(0);
    select.remove(1);
}

jQuery / Javascript code check, if not undefined

I like this:

if (wlocation !== undefined)

But if you prefer the second way wouldn't be as you posted. It would be:

if (typeof wlocation  !== "undefined")

jQuery select option elements by value

options = $("#span_id>select>option[value='"+i+"']");
option = options.text();
alert(option); 

here is the fiddle http://jsfiddle.net/hRFYF/

Join between tables in two different databases?

SELECT <...> 
FROM A.tableA JOIN B.tableB 

Object of class mysqli_result could not be converted to string in

The query() function returns an object, you'll want fetch a record from what's returned from that function. Look at the examples on this page to learn how to print data from mysql

Converting <br /> into a new line for use in a text area

EDIT: previous answer was backwards of what you wanted. Use str_replace. replace <br> with \n

echo str_replace('<br>', "\n", $var1);

Update a column value, replacing part of a string

You need the WHERE clause to replace ONLY the records that complies with the condition in the WHERE clause (as opposed to all records). You use % sign to indicate partial string: I.E.

LIKE ('...//domain1.com/images/%');

means all records that BEGIN with "...//domain1.com/images/" and have anything AFTER (that's the % for...)

Another example:

LIKE ('%http://domain1.com/images/%')

which means all records that contains "http://domain1.com/images/"

in any part of the string...

Validation error: "No validator could be found for type: java.lang.Integer"

You can add hibernate validator dependency, to provide a Validator

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>6.0.12.Final</version>
</dependency>

"Gradle Version 2.10 is required." Error

Important:

If you are getting this when you run:
gradle build
from command line you have to use:
gradlew build
instead so that you will use gradle wrapper to downloaded the appropriate gradle version needed by the app.

When you execute gradle build you are using the global gradle installed on your system.

Save child objects automatically using JPA Hibernate

Use org.hibernate.annotations for doing Cascade , if the hibernate and JPA are used together , its somehow complaining on saving the child objects.

How does JPA orphanRemoval=true differ from the ON DELETE CASCADE DML clause

orphan removal has the same effect as ON DELETE CASCADE in the following scenario:- Lets say we have a simple many to one relationship between student entity and a guide entity, where many students can be mapped to the same guide and in database we have a foreign key relation between Student and Guide table such that student table has id_guide as FK.

    @Entity
    @Table(name = "student", catalog = "helloworld")
    public class Student implements java.io.Serializable {
     @Id
     @GeneratedValue(strategy = IDENTITY)
     @Column(name = "id")
     private Integer id;

    @ManyToOne(cascade={CascadeType.PERSIST,CascadeType.REMOVE})
    @JoinColumn(name = "id_guide")
    private Guide guide;

// The parent entity

    @Entity
    @Table(name = "guide", catalog = "helloworld")
    public class Guide implements java.io.Serializable {

/**
 * 
 */
private static final long serialVersionUID = 9017118664546491038L;

@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Integer id;

@Column(name = "name", length = 45)
private String name;

@Column(name = "salary", length = 45)
private String salary;


 @OneToMany(mappedBy = "guide", orphanRemoval=true) 
 private Set<Student> students = new  HashSet<Student>(0);

In this scenario, the relationship is such that student entity is the owner of the relationship and as such we need to save the student entity in order to persist the whole object graph e.g.

    Guide guide = new Guide("John", "$1500");
    Student s1 = new Student(guide, "Roy","ECE");
    Student s2 = new Student(guide, "Nick", "ECE");
    em.persist(s1);
    em.persist(s2);

Here we are mapping the same guide with two different student objects and since the CASCADE.PERSIST is used , the object graph will be saved as below in the database table(MySql in my case)

STUDENT table:-

ID Name Dept Id_Guide

1     Roy     ECE    1

2    Nick    ECE    1

GUIDE Table:-

ID NAME Salary

1    John     $1500

and Now if I want to remove one of the students, using

      Student student1 = em.find(Student.class,1);
      em.remove(student1);

and when a student record is removed the corresponding guide record should also be removed, that's where CASCADE.REMOVE attribute in the Student entity comes into picture and what it does is ;it removes the student with identifier 1 as well the corresponding guide object(identifier 1). But in this example, there is one more student object which is mapped to the same guide record and unless we use the orphanRemoval=true attribute in the Guide Entity , the remove code above will not work.

How to set a single, main title above all the subplots with Pyplot?

A few points I find useful when applying this to my own plots:

  • I prefer the consistency of using fig.suptitle(title) rather than plt.suptitle(title)
  • When using fig.tight_layout() the title must be shifted with fig.subplots_adjust(top=0.88)
  • See answer below about fontsizes

Example code taken from subplots demo in matplotlib docs and adjusted with a master title.

A nice 4x4 plot

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, axarr = plt.subplots(2, 2)
fig.suptitle("This Main Title is Nicely Formatted", fontsize=16)

axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0] Subtitle')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1] Subtitle')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0] Subtitle')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1] Subtitle')

# # Fine-tune figure; hide x ticks for top plots and y ticks for right plots
plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)

# Tight layout often produces nice results
# but requires the title to be spaced accordingly
fig.tight_layout()
fig.subplots_adjust(top=0.88)

plt.show()

Iterating through a List Object in JSP

change the code to the following

<%! List eList = (ArrayList)session.getAttribute("empList");%>
....
<table>
    <%
    for(int i=0; i<eList.length;i++){%>
        <tr>
            <td><%= ((Employee)eList[i]).getEid() %></td>
            <td><%= ((Employee)eList[i]).getEname() %></td>  
        </tr>
      <%}%>
</table>

Not equal string

Try this:

if(myString != "-1")

The opperand is != and not =!

You can also use Equals

if(!myString.Equals("-1"))

Note the ! before myString

Invariant Violation: Objects are not valid as a React child

For anybody using Firebase with Android, this only breaks Android. My iOS emulation ignores it.

And as posted by Apoorv Bankey above.

Anything above Firebase V5.0.3, for Android, atm is a bust. Fix:

npm i --save [email protected]

Confirmed numerous times here https://github.com/firebase/firebase-js-sdk/issues/871

Insert multiple values using INSERT INTO (SQL Server 2005)

You can also use the following syntax:-

INSERT INTO MyTable (FirstCol, SecondCol)
SELECT 'First' ,1
UNION ALL
SELECT 'Second' ,2
UNION ALL
SELECT 'Third' ,3
UNION ALL
SELECT 'Fourth' ,4
UNION ALL
SELECT 'Fifth' ,5
GO

From here

How to urlencode data for curl command?

Having php installed I use this way:

URL_ENCODED_DATA=`php -r "echo urlencode('$DATA');"`

Replace multiple characters in a C# string

A .NET Core version for replacing a defined set of string chars to a specific char. It leverages the recently introduced Span type and string.Create method.

The idea is to prepare a replacement array, so no actual comparison operations would be required for the each string char. Thus, the replacement process reminds the way a state machine works. In order to avoid initialization of all items of the replacement array, let's store oldChar ^ newChar (XOR'ed) values there, what gives the following benefits:

  • If a char is not changing: ch ^ ch = 0 - no need to initialize non-changing items
  • The final char can be found by XOR'ing: ch ^ repl[ch]:
    • ch ^ 0 = ch - not changed chars case
    • ch ^ (ch ^ newChar) = newChar - replaced char

So the only requirement would be to ensure that the replacement array is zero-ed when initialized. We'll be using ArrayPool<char> to avoid allocations each time the ReplaceAll method is called. And, in order to ensure that the arrays are zero-ed without expensive call to Array.Clear method, we'll be maintaining a pool dedicated for the ReplaceAll method. We'll be clearing the replacement array (exact items only) before returning it to the pool.

public static class StringExtensions
{
    private static readonly ArrayPool<char> _replacementPool = ArrayPool<char>.Create();

    public static string ReplaceAll(this string str, char newChar, params char[] oldChars)
    {
        // If nothing to do, return the original string.
        if (string.IsNullOrEmpty(str) ||
            oldChars is null ||
            oldChars.Length == 0)
        {
            return str;
        }

        // If only one character needs to be replaced,
        // use the more efficient `string.Replace`.
        if (oldChars.Length == 1)
        {
            return str.Replace(oldChars[0], newChar);
        }

        // Get a replacement array from the pool.
        var replacements = _replacementPool.Rent(char.MaxValue + 1);

        try
        {
            // Intialize the replacement array in the way that
            // all elements represent `oldChar ^ newChar`.
            foreach (var oldCh in oldChars)
            {
                replacements[oldCh] = (char)(newChar ^ oldCh);
            }

            // Create a string with replaced characters.
            return string.Create(str.Length, (str, replacements), (dst, args) =>
            {
                var repl = args.replacements;

                foreach (var ch in args.str)
                {
                    dst[0] = (char)(repl[ch] ^ ch);
                    dst = dst.Slice(1);
                }
            });
        }
        finally
        {
            // Clear the replacement array.
            foreach (var oldCh in oldChars)
            {
                replacements[oldCh] = char.MinValue;
            }

            // Return the replacement array back to the pool.
            _replacementPool.Return(replacements);
        }
    }
}

Convert Date format into DD/MMM/YYYY format in SQL Server

Try this :

select replace ( convert(varchar,getdate(),106),' ','/')

ImageMagick security policy 'PDF' blocking conversion

Adding to Stefan Seidel's answer.

Well, at least in Ubuntu 20.04.2 LTS or maybe in other versions you can't really edit the policy.xml file directly in a GUI way. Here is a terminal way to edit it.

  1. Open the policy.xml file in terminal by entering this command -

    sudo nano /etc/ImageMagick-6/policy.xml

  2. Now, directly edit the file in terminal, find <policy domain="coder" rights="none" pattern="PDF" /> and replace none with read|write as shown in the picture. Then press Ctrl+X to exit.

Edit in terminal

the best way to make codeigniter website multi-language. calling from lang arrays depends on lang session?

Have you seen CodeIgniter's Language library?

The Language Class provides functions to retrieve language files and lines of text for purposes of internationalization.

In your CodeIgniter system folder you'll find one called language containing sets of language files. You can create your own language files as needed in order to display error and other messages in other languages.

Language files are typically stored in your system/language directory. Alternately you can create a folder called language inside your application folder and store them there. CodeIgniter will look first in your application/language directory. If the directory does not exist or the specified language is not located there CI will instead look in your global system/language folder.

In your case...

  • you need to create a polish_lang.php and english_lang.php inside application/language/polish
  • then create your keys inside that file (e.g. $lang['hello'] = "Witaj";
  • then load it in your controller like $this->lang->load('polish_lang', 'polish');
  • then fetch the line like $this->lang->line('hello'); Just store the return value of this function in a variable so you can use it in your view.

Repeat the steps for the english language and all other languages you need.

Ansible: Set variable to file content

You can use the slurp module to fetch a file from the remote host: (Thanks to @mlissner for suggesting it)

vars:
  amazon_linux_ami: "ami-fb8e9292"
  user_data_file: "base-ami-userdata.sh"
tasks:
- name: Load data
  slurp:
    src: "{{ user_data_file }}"
  register: slurped_user_data
- name: Decode data and store as fact # You can skip this if you want to use the right hand side directly...
  set_fact:
    user_data: "{{ slurped_user_data.content | b64decode }}"

std::string formatting like sprintf

Update of some answer around, difference is - function will properly accept std::string for %s

namespace format_helper
{

    template <class Src>
    inline Src cast(Src v)
    {
        return v;
    }

    inline const char *cast(const std::string& v)
    {
        return v.c_str();
    }
};

template <typename... Ts>
inline std::string stringfmt (const std::string &fmt, Ts&&... vs)
{
    using namespace format_helper;
    char b;
    size_t required = std::snprintf(&b, 0, fmt.c_str(), cast(std::forward<Ts>(vs))...);//not counting the terminating null character.
    std::string result;
    //because we use string as container, it adds extra 0 automatically
    result.resize(required , 0);
    //and snprintf will use n-1 bytes supplied
    std::snprintf(const_cast<char*>(result.data()), required + 1, fmt.c_str(), cast(std::forward<Ts>(vs))...);

    return result;
}

Live: http://cpp.sh/5ajsv

Python: How exactly can you take a string, split it, reverse it and join it back together again?

Do you mean like this?

import string
astr='a(b[c])d'

deleter=string.maketrans('()[]','    ')
print(astr.translate(deleter))
# a b c  d
print(astr.translate(deleter).split())
# ['a', 'b', 'c', 'd']
print(list(reversed(astr.translate(deleter).split())))
# ['d', 'c', 'b', 'a']
print(' '.join(reversed(astr.translate(deleter).split())))
# d c b a

How to run a command in the background on Windows?

I'm assuming what you want to do is run a command without an interface (possibly automatically?). On windows there are a number of options for what you are looking for:

  • Best: write your program as a windows service. These will start when no one logs into the server. They let you select the user account (which can be different than your own) and they will restart if they fail. These run all the time so you can automate tasks at specific times or on a regular schedule from within them. For more information on how to write a windows service you can read a tutorial online such as (http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx).

  • Better: Start the command and hide the window. Assuming the command is a DOS command you can use a VB or C# script for this. See here for more information. An example is:

    Set objShell = WScript.CreateObject("WScript.Shell")
    objShell.Run("C:\yourbatch.bat"), 0, True
    

    You are still going to have to start the command manually or write a task to start the command. This is one of the biggest down falls of this strategy.

  • Worst: Start the command using the startup folder. This runs when a user logs into the computer

Hope that helps some!

how do I change text in a label with swift?

use a simple formula: WHO.WHAT = VALUE

where,

WHO is the element in the storyboard you want to make changes to for eg. label

WHAT is the property of that element you wish to change for eg. text

VALUE is the change that you wish to be displayed

for eg. if I want to change the text from story text to You see a fork in the road in the label as shown in screenshot 1

In this case, our WHO is the label (element in the storyboard), WHAT is the text (property of element) and VALUE will be You see a fork in the road

so our final code will be as follows: Final code

screenshot 1 changes to screenshot 2 once the above code is executed.

I hope this solution helps you solve your issue. Thank you!

git status (nothing to commit, working directory clean), however with changes commited

git status output tells you three things by default:

  1. which branch you are on
  2. What is the status of your local branch in relation to the remote branch
  3. If you have any uncommitted files

When you did git commit , it committed to your local repository, thus #3 shows nothing to commit, however, #2 should show that you need to push or pull if you have setup the tracking branch.

If you find the output of git status verbose and difficult to comprehend, try using git status -sb this is less verbose and will show you clearly if you need to push or pull. In your case, the output would be something like:

master...origin/master [ahead 1]

git status is pretty useful, in the workflow you described do a git status -sb: after touching the file, after adding the file and after committing the file, see the difference in the output, it will give you more clarity on untracked, tracked and committed files.

Update #1
This answer is applicable if there was a misunderstanding in reading the git status output. However, as it was pointed out, in the OPs case, the upstream was not set correctly. For that, Chris Mae's answer is correct.

What does "control reaches end of non-void function" mean?

Make sure that your code is returning a value of given return-type irrespective of conditional statements

This code snippet was showing the same error

int search(char arr[], int start, int end, char value)
{
    int i;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            return i;
    }
}

This is the working code after little changes

int search(char arr[], int start, int end, char value)
{
    int i;
    int index=-1;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            index=i;
    }
    return index;
}

Comparing floating point number to zero

No.

Equality is equality.

The function you wrote will not test two doubles for equality, as its name promises. It will only test if two doubles are "close enough" to each other.

If you really want to test two doubles for equality, use this one:

inline bool isEqual(double x, double y)
{
   return x == y;
}

Coding standards usually recommend against comparing two doubles for exact equality. But that is a different subject. If you actually want to compare two doubles for exact equality, x == y is the code you want.

10.000000000000001 is not equal to 10.0, no matter what they tell you.

An example of using exact equality is when a particular value of a double is used as a synonym of some special state, such as "pending calulation" or "no data available". This is possible only if the actual numeric values after that pending calculation are only a subset of the possible values of a double. The most typical particular case is when that value is nonnegative, and you use -1.0 as an (exact) representation of a "pending calculation" or "no data available". You could represent that with a constant:

const double NO_DATA = -1.0;

double myData = getSomeDataWhichIsAlwaysNonNegative(someParameters);

if (myData != NO_DATA)
{
    ...
}

How to print something to the console in Xcode?

@Logan said it perfectly. but i would like to add an alternative here,

if you want to view logs from just your application then you can make a custom method that keeps saving the log to a file in documents directory & then you can view that log file from your application.

There is one good advantage for developers of the app after the app has been released & users are downloading it. Because your app will be able to send logs & crash reports to the developers (of course with the permissions of the device user !!!) & it'll be the way to improve your application.

Let me know (To other SO users), if there is another way of doing the same thing. (Like default Apple feature or something)

Let me know if it helps or you want some more idea.

How to run a cronjob every X minutes?

Your CRON should look like this:

*/5 * * * *

CronWTF is really usefull when you need to test out your CRON settings.

Might be a good idea to pipe the output into a log file so you can see if your script is throwing any errors too - since you wont see them in your terminal.

Also try using a shebang at the top of your PHP file, so the system knows where to find PHP. Such as:

#!/usr/bin/php

that way you can call the whole thing like this

*/5 * * * * php /path/to/script.php > /path/to/logfile.log

SQL query with avg and group by

If I understand what you need, try this:

SELECT id, pass, AVG(val) AS val_1 
FROM data_r1 
GROUP BY id, pass;

Or, if you want just one row for every id, this:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id

How can I determine browser window size on server side C#

There is a solution to solve page_onload problem (can't get size until page load complete) : Create a userControl :

<%@ Control Language="VB" AutoEventWireup="false" CodeFile="ClientSizeDetector.ascx.vb"    Inherits="Project_UserControls_ClientSizeDetector" %>
<%If (IsFirstTime) Then%>
<script type="text/javascript">
var pageURL = window.location.href.search(/\?/) > 0 ? "&" : "?";
window.location.href = window.location.href + pageURL + "clientHeight=" + window.innerHeight + "&clientWidth=" + window.innerWidth;
</script>
<%End If%>

Code behind :

 Private _isFirstTime As Boolean = False
 Private _clientWidth As Integer = 0
 Private _clientHeight As Integer = 0

 Public Property ClientWidth() As Integer
    Get
        Return _clientWidth
    End Get
    Set(value As Integer)
        _clientWidth = value
    End Set
End Property

Public Property ClientHeight() As Integer
    Get
        Return _clientHeight
    End Get
    Set(value As Integer)
        _clientHeight = value
    End Set
End Property

public Property IsFirstTime() As Boolean 
    Get
        Return _isFirstTime
    End Get
    Set(value As Boolean)
        _isFirstTime = value
    End Set
End Property



Protected Overrides Sub OnInit(e As EventArgs)

    If (String.IsNullOrEmpty(Request.QueryString("clientHeight")) Or String.IsNullOrEmpty(Request.QueryString("clientWidth"))) Then
        Me._isFirstTime = True
    Else
        Integer.TryParse(Request.QueryString("clientHeight").ToString(), ClientHeight)
        Integer.TryParse(Request.QueryString("clientWidth").ToString(), ClientWidth)
        Me._isFirstTime = False
    End If
End Sub

So after, you can call your control properties

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

it works for me Swift 3:

    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        return true
    }

and in ViewDidLoad:

    self.navigationController?.interactivePopGestureRecognizer?.delegate = self
    self.navigationController?.interactivePopGestureRecognizer?.isEnabled = true

Excluding files/directories from Gulp task

Quick answer

On src, you can always specify files to ignore using "!".

Example (you want to exclude all *.min.js files on your js folder and subfolder:

gulp.src(['js/**/*.js', '!js/**/*.min.js'])

You can do it as well for individual files.

Expanded answer:

Extracted from gulp documentation:

gulp.src(globs[, options])

Emits files matching provided glob or an array of globs. Returns a stream of Vinyl files that can be piped to plugins.

glob refers to node-glob syntax or it can be a direct file path.

So, looking to node-glob documentation we can see that it uses the minimatch library to do its matching.

On minimatch documentation, they point out the following:

if the pattern starts with a ! character, then it is negated.

And that is why using ! symbol will exclude files / directories from a gulp task

How to add a vertical Separator?

This is not exactly what author asked, but still, it is very simple and works exactly as expected.

Rectangle does the job:

<StackPanel Grid.Column="2" Orientation="Horizontal">
    <Button >Next</Button>
    <Button >Prev</Button>
    <Rectangle VerticalAlignment="Stretch" Width="1" Margin="2" Stroke="Black" />
    <Button>Filter all</Button>
</StackPanel>

HTTP Status 405 - Method Not Allowed Error for Rest API

@Produces({"text/plain","application/xml","application/json"}) change this to @Produces("text/plain") and try,

Value of type 'T' cannot be converted to

Even though it's inside of an if block, the compiler doesn't know that T is string.
Therefore, it doesn't let you cast. (For the same reason that you cannot cast DateTime to string)

You need to cast to object, (which any T can cast to), and from there to string (since object can be cast to string).
For example:

T newT1 = (T)(object)"some text";
string newT2 = (string)(object)t;

Javascript geocoding from address to latitude and longitude numbers not working

The script tag to the api has changed recently. Use something like this to query the Geocoding API and get the JSON object back

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/geocode/json?address=THE_ADDRESS_YOU_WANT_TO_GEOCODE&key=YOUR_API_KEY"></script>

The address could be something like

1600+Amphitheatre+Parkway,+Mountain+View,+CA (URI Encoded; you should Google it. Very useful)

or simply

1600 Amphitheatre Parkway, Mountain View, CA

By entering this address https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY inside the browser, along with my API Key, I get back a JSON object which contains the Latitude & Longitude for the city of Moutain view, CA.

{"results" : [
  {
     "address_components" : [
        {
           "long_name" : "1600",
           "short_name" : "1600",
           "types" : [ "street_number" ]
        },
        {
           "long_name" : "Amphitheatre Parkway",
           "short_name" : "Amphitheatre Pkwy",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Mountain View",
           "short_name" : "Mountain View",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Santa Clara County",
           "short_name" : "Santa Clara County",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "California",
           "short_name" : "CA",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "United States",
           "short_name" : "US",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "94043",
           "short_name" : "94043",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA",
     "geometry" : {
        "location" : {
           "lat" : 37.4222556,
           "lng" : -122.0838589
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 37.4236045802915,
              "lng" : -122.0825099197085
           },
           "southwest" : {
              "lat" : 37.4209066197085,
              "lng" : -122.0852078802915
           }
        }
     },
     "place_id" : "ChIJ2eUgeAK6j4ARbn5u_wAGqWA",
     "types" : [ "street_address" ]
  }],"status" : "OK"}

Web Frameworks such like AngularJS allow us to perform these queries with ease.

An error occurred while signing: SignTool.exe not found

Windows 10 users can find signtool.exe in C:\Program Files (x86)\Windows Kits\10\bin\10.0.18362.0\x64 folder (10.0.18362.0 in my case, or other version).


But first, make sure you've installed Windows 10 SDK

Then, check Windows SDK Signing Tools for Desktop Apps is installed by going to Control Panel > Programs > Programs and Features, choose Windows Software Development Kit - Windows 10.0.18362.1 (in my case, you version may be different), right-click, choose Change, choose options Change then click Next.

How to use in jQuery :not and hasClass() to get a specific element without a class

jQuery's hasClass() method returns a boolean (true/false) and not an element. Also, the parameter to be given to it is a class name and not a selector as such.

For ex: x.hasClass('error');

How to comment and uncomment blocks of code in the Office VBA Editor

Or just click View, ToolBars, Edit. Then you can select a block of code and then click the Comment or Uncomment toolbar button to do everything in one click.

As an aside, you can Tab/Shift+Tab a block of selected text also. When I was a noobie, I didn't know that for a long time and would do them one line at a time.

Good Luck!

Moment.js - how do I get the number of years since a date, not rounded up?

Try this:

 moment("02/26/1978", "MM/DD/YYYY").fromNow().split(" ")[0];

Explanation:

We receive string something like this: '23 days ago'. Split it to array: ['23', 'days', 'ago'] and then take first item '23'.

How to get GET (query string) variables in Express.js on Node.js?

There are 2 ways to pass parameters via GET method

Method 1 : The MVC approach where you pass the parameters like /routename/:paramname
In this case you can use req.params.paramname to get the parameter value For Example refer below code where I am expecting Id as a param
link could be like : http://myhost.com/items/23

var express = require('express');
var app = express();
app.get("items/:id", function(req, res) {
    var id = req.params.id;
    //further operations to perform
});
app.listen(3000);

Method 2 : General Approach : Passing variables as query string using '?' operator
For Example refer below code where I am expecting Id as a query parameter
link could be like : http://myhost.com/items?id=23

var express = require('express');
var app = express();
app.get("/items", function(req, res) {
    var id = req.query.id;
    //further operations to perform
});
app.listen(3000);

Create array of regex matches

        Set<String> keyList = new HashSet();
        Pattern regex = Pattern.compile("#\\{(.*?)\\}");
        Matcher matcher = regex.matcher("Content goes here");
        while(matcher.find()) {
            keyList.add(matcher.group(1)); 
        }
        return keyList;

How to get ELMAH to work with ASP.NET MVC [HandleError] attribute?

There is now an ELMAH.MVC package in NuGet that includes an improved solution by Atif and also a controller that handles the elmah interface within MVC routing (no need to use that axd anymore)
The problem with that solution (and with all the ones here) is that one way or another the elmah error handler is actually handling the error, ignoring what you might want to set up as a customError tag or through ErrorHandler or your own error handler
The best solution IMHO is to create a filter that will act at the end of all the other filters and log the events that have been handled already. The elmah module should take care of loging the other errors that are unhandled by the application. This will also allow you to use the health monitor and all the other modules that can be added to asp.net to look at error events

I wrote this looking with reflector at the ErrorHandler inside elmah.mvc

public class ElmahMVCErrorFilter : IExceptionFilter
{
   private static ErrorFilterConfiguration _config;

   public void OnException(ExceptionContext context)
   {
       if (context.ExceptionHandled) //The unhandled ones will be picked by the elmah module
       {
           var e = context.Exception;
           var context2 = context.HttpContext.ApplicationInstance.Context;
           //TODO: Add additional variables to context.HttpContext.Request.ServerVariables for both handled and unhandled exceptions
           if ((context2 == null) || (!_RaiseErrorSignal(e, context2) && !_IsFiltered(e, context2)))
           {
            _LogException(e, context2);
           }
       }
   }

   private static bool _IsFiltered(System.Exception e, System.Web.HttpContext context)
   {
       if (_config == null)
       {
           _config = (context.GetSection("elmah/errorFilter") as ErrorFilterConfiguration) ?? new ErrorFilterConfiguration();
       }
       var context2 = new ErrorFilterModule.AssertionHelperContext((System.Exception)e, context);
       return _config.Assertion.Test(context2);
   }

   private static void _LogException(System.Exception e, System.Web.HttpContext context)
   {
       ErrorLog.GetDefault((System.Web.HttpContext)context).Log(new Elmah.Error((System.Exception)e, (System.Web.HttpContext)context));
   }


   private static bool _RaiseErrorSignal(System.Exception e, System.Web.HttpContext context)
   {
       var signal = ErrorSignal.FromContext((System.Web.HttpContext)context);
       if (signal == null)
       {
           return false;
       }
       signal.Raise((System.Exception)e, (System.Web.HttpContext)context);
       return true;
   }
}

Now, in your filter config you want to do something like this:

    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        //These filters should go at the end of the pipeline, add all error handlers before
        filters.Add(new ElmahMVCErrorFilter());
    }

Notice that I left a comment there to remind people that if they want to add a global filter that will actually handle the exception it should go BEFORE this last filter, otherwise you run into the case where the unhandled exception will be ignored by the ElmahMVCErrorFilter because it hasn't been handled and it should be loged by the Elmah module but then the next filter marks the exception as handled and the module ignores it, resulting on the exception never making it into elmah.

Now, make sure the appsettings for elmah in your webconfig look something like this:

<add key="elmah.mvc.disableHandler" value="false" /> <!-- This handles elmah controller pages, if disabled elmah pages will not work -->
<add key="elmah.mvc.disableHandleErrorFilter" value="true" /> <!-- This uses the default filter for elmah, set to disabled to use our own -->
<add key="elmah.mvc.requiresAuthentication" value="false" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.allowedRoles" value="*" /> <!-- Manages authentication for elmah pages -->
<add key="elmah.mvc.route" value="errortracking" /> <!-- Base route for elmah pages -->

The important one here is "elmah.mvc.disableHandleErrorFilter", if this is false it will use the handler inside elmah.mvc that will actually handle the exception by using the default HandleErrorHandler that will ignore your customError settings

This setup allows you to set your own ErrorHandler tags in classes and views, while still loging those errors through the ElmahMVCErrorFilter, adding a customError configuration to your web.config through the elmah module, even writing your own Error Handlers. The only thing you need to do is remember to not add any filters that will actually handle the error before the elmah filter we've written. And I forgot to mention: no duplicates in elmah.

CSS force image resize and keep aspect ratio

To maintain a responsive image while still enforcing the image to have a certain aspect ratio you can do the following:

HTML:

<div class="ratio2-1">
   <img src="../image.png" alt="image">
</div>

And SCSS:

.ratio2-1 {
  overflow: hidden;
  position: relative;

  &:before {
    content: '';
    display: block;
    padding-top: 50%; // ratio 2:1
  }

  img {
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
  }
}

This can be used to enforce a certain aspect ratio, regardless of the size of the image that authors upload.

Thanks to @Kseso at http://codepen.io/Kseso/pen/bfdhg. Check this URL for more ratios and a working example.

How to find EOF through fscanf?

fscanf - "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure. In the case of an input failure before any data could be successfully read, EOF is returned."

So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF.

You should check for EOF when you call fscanf, not check the array slot for EOF.

Direct download from Google Drive using Google Drive API

If you just want to programmatically (as oppossed to giving the user a link to open in a browser) download a file through the Google Drive API, I would suggest using the downloadUrl of the file instead of the webContentLink, as documented here: https://developers.google.com/drive/web/manage-downloads

curl usage to get header

curl --head https://www.example.net

I was pointed to this by curl itself; when I issued the command with -X HEAD, it printed:

Warning: Setting custom HTTP method to HEAD with -X/--request may not work the 
Warning: way you want. Consider using -I/--head instead.

Failed to resolve: com.google.firebase:firebase-core:16.0.1

if you are using

compileSdkVersion 23

in app-level gradle, and

classpath 'com.android.tools.build:gradle:2.1.0'

in project-level gradle and you have added the google-services.json file to your project.

you need to add just below code

maven {
   url "https://maven.google.com"
}

at below of jcenter() in repositories blocks in project-level gradle file here are my gradle files:

project-level gradle file:

buildscript {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
        classpath 'com.google.gms:google-services:4.0.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

and app-level gradle file:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.moslem.amazonlikeapp"
        minSdkVersion 21
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.google.firebase:firebase-core:16.0.1'
}
apply plugin: 'com.google.gms.google-services'

CodeIgniter activerecord, retrieve last insert id?

Try this.

public function insert_data_function($your_data)
{
    $this->db->insert("your_table",$your_data);
    $last_id = $this->db->insert_id();
    return $last_id;
}

Truncate Two decimal places without rounding

Apart from the above solutions,there is another way we can achieve .

    decimal val=23.5678m,finalValue;

    //take the decimal part    
     int decimalPos = val.ToString().IndexOf('.');
     string decimalPart = val.ToString().Substring(decimalPosition+1,val.ToString().Length);
    //will result.56
   string wholePart=val.ToString().Substring(0,decimalPos-1);
   //concantinate and parse for decimal.
  string truncatedValue=wholePart+decimalPart;//"23.56"
  bool isDecimal=Decimal.tryParse(truncatedValue,out finalValue);//finalValue=23.56

cursor.fetchall() vs list(cursor) in Python

cursor.fetchall() and list(cursor) are essentially the same. The different option is to not retrieve a list, and instead just loop over the bare cursor object:

for result in cursor:

This can be more efficient if the result set is large, as it doesn't have to fetch the entire result set and keep it all in memory; it can just incrementally get each item (or batch them in smaller batches).

Maintain aspect ratio of div but fill screen width and height in CSS?

Use the new CSS viewport units vw and vh (viewport width / viewport height)

FIDDLE

Resize vertically and horizontally and you'll see that the element will always fill the maximum viewport size without breaking the ratio and without scrollbars!

(PURE) CSS

div
{
    width: 100vw; 
    height: 56.25vw; /* height:width ratio = 9/16 = .5625  */
    background: pink;
    max-height: 100vh;
    max-width: 177.78vh; /* 16/9 = 1.778 */
    margin: auto;
    position: absolute;
    top:0;bottom:0; /* vertical center */
    left:0;right:0; /* horizontal center */
}

_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
div {_x000D_
  width: 100vw;_x000D_
  height: 56.25vw;_x000D_
  /* 100/56.25 = 1.778 */_x000D_
  background: pink;_x000D_
  max-height: 100vh;_x000D_
  max-width: 177.78vh;_x000D_
  /* 16/9 = 1.778 */_x000D_
  margin: auto;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  /* vertical center */_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  /* horizontal center */_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

If you want to use a maximum of say 90% width and height of the viewport: FIDDLE

_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
div {_x000D_
  width: 90vw;_x000D_
  /* 90% of viewport vidth */_x000D_
  height: 50.625vw;_x000D_
  /* ratio = 9/16 * 90 = 50.625 */_x000D_
  background: pink;_x000D_
  max-height: 90vh;_x000D_
  max-width: 160vh;_x000D_
  /* 16/9 * 90 = 160 */_x000D_
  margin: auto;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Also, browser support is pretty good too: IE9+, FF, Chrome, Safari- caniuse

Bootstrap css hides portion of container below navbar navbar-fixed-top

It happens because with navbar-fixed-top class the navbar gets the position:fixed. This in turns take the navbar out of the document flow leaving the body to take up the space behind the navbar.

You need to apply padding-top or margin-top to your container, based on your requirements with values >= 50px. (or play around with different values)

The basic bootstrap navbar takes height around 40px. So if you give a padding-top or margin-top of 50px or more, you will always have that breathing space between your container and the navbar.

Vertical and horizontal align (middle and center) with CSS

This isn't as easy to do as one might expect -- you can really only do vertical alignment if you know the height of your container. IF this is the case, you can do it with absolute positioning.

The concept is to set the top / left positions at 50%, and then use negative margins (set to half the height / width) to pull the container back to being centered.

Example: http://jsbin.com/ipawe/edit

Basic CSS:

#mydiv { 
    position: absolute;
    top: 50%;
    left: 50%;
    height: 400px;
    width: 700px;
    margin-top: -200px; /* -(1/2 height) */
    margin-left: -350px; /* -(1/2 width) */
  }

Jquery: how to sleep or delay?

How about .delay() ?

http://api.jquery.com/delay/

$("#test").animate({"top":"-=80px"},1500)
          .delay(1000)
          .animate({"opacity":"0"},500);

Creating SolidColorBrush from hex color value

Try this instead:

(SolidColorBrush)(new BrushConverter().ConvertFrom("#ffaacc"));

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

CSS Input Type Selectors - Possible to have an "or" or "not" syntax?

CSS3 has a pseudo-class called :not()

_x000D_
_x000D_
input:not([type='checkbox']) {    
    visibility: hidden;
}
_x000D_
<p>If <code>:not()</code> is supported, you'll only see the checkbox.</p>
                                      
<ul>
  <li>text: (<input type="text">)</li>  
  <li>password (<input type="password">)</li>       
  <li>checkbox (<input type="checkbox">)</li> 
 </ul>
_x000D_
_x000D_
_x000D_


Multiple selectors

As Vincent mentioned, it's possible to string multiple :not()s together:

input:not([type='checkbox']):not([type='submit'])

CSS4, which is supported in many of the latest browser releases, allows multiple selectors in a :not()

input:not([type='checkbox'],[type='submit'])

Legacy support

All modern browsers support the CSS3 syntax. At the time this question was asked, we needed a fall-back for IE7 and IE8. One option was to use a polyfill like IE9.js. Another was to exploit the cascade in CSS:

input {
   // styles for most inputs
}   

input[type=checkbox] {
  // revert back to the original style
} 

input.checkbox {
  // for completeness, this would have worked even in IE3!
} 

Double free or corruption after queue::push

You can also try to check null before delete such that

if(myArray) { delete[] myArray; myArray = NULL; }

or you can define all delete operations ina safe manner like this:

#ifndef SAFE_DELETE
#define SAFE_DELETE(p) { if(p) { delete (p); (p) = NULL; } }
#endif

#ifndef SAFE_DELETE_ARRAY
#define SAFE_DELETE_ARRAY(p) { if(p) { delete[] (p); (p) = NULL; } }
#endif

and then use

SAFE_DELETE_ARRAY(myArray);

Difference between try-catch and throw in java

try - Add sensitive code catch - to handle exception finally - always executed whether exception caught or not. Associated with try -catch. Used to close the resource which we opened in try block throw - To handover our created exception to JVM manually. Used to throw customized exception throws - To delegate the responsibility of exception handling to caller method or main method.

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

This is how it worked for me:

  1. Kill Xcode and launch again
  2. Open project again
  3. Clean Project
  4. Go to project settings > general > uncheck 'automatically managed profiles' and than 'check' again it will prompt for enable.
  5. Now try archiving the source code

P.S Killing Xcode and launch again is the best thing to do if facing any random issue

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

How do I put a variable inside a string?

In general, you can create strings using:

stringExample = "someString " + str(someNumber)
print(stringExample)
plot.savefig(stringExample)

Android: Pass data(extras) to a fragment

There is a simple why that I prefered to the bundle due to the no duplicate data in memory. It consists of a init public method for the fragment

private ArrayList<Music> listMusics = new ArrayList<Music>();
private ListView listMusic;


public static ListMusicFragment createInstance(List<Music> music) {
    ListMusicFragment fragment = new ListMusicFragment();
    fragment.init(music);
    return fragment;
}

public void init(List<Music> music){
    this.listMusic = music;
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, 
    Bundle savedInstanceState)
{

    View view = inflater.inflate(R.layout.musiclistview, container, false);
    listMusic = (ListView) view.findViewById(R.id.musicListView);
    listMusic.setAdapter(new MusicBaseAdapter(getActivity(), listMusics));

    return view;
}
}

In two words, you create an instance of the fragment an by the init method (u can call it as u want) you pass the reference of your list without create a copy by serialization to the instance of the fragment. This is very usefull because if you change something in the list u will get it in the other parts of the app and ofcourse, you use less memory.

C# Checking if button was clicked

These helped me a lot: I wanted to save values from my gridview, and it was reloading my gridview /overriding my new values, as i have IsPostBack inside my PageLoad.

if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{
   //Do not reload the gridview.

}
else
{
   reload my gridview.
}

SOURCE: http://bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked

How do I set a path in Visual Studio?

None of the answers solved exactly my problem (the solution file I was running was trying to find xcopy to copy a dll after generation).

What solved it for me was going into menu "Project -> Properties"

Then in the window that opens choosing on the left pane: "Configuration Properties -> VC++ Directories

On the right pane under "General" choosing "Executable Directories "

And then adding:

$(SystemRoot)\system32;$(SystemRoot);$(SystemRoot)\System32\Wbem;$(SystemRoot)\System32\WindowsPowerShell\v1.0\;$(ExecutablePath)

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

This issue is because you didn't register the data access component with the interface written for it. Try using as follows

services.AddTransient<IMyDataProvider, MyDataAccess>();`

How to prevent "The play() request was interrupted by a call to pause()" error?

removed all errors: (typescript)

audio.addEventListener('canplay', () => {
    audio.play();
    audio.pause();
    audio.removeEventListener('canplay');
}); 

How to initialize all the elements of an array to any specific value in java

Using Java 8, you can simply use ncopies of Collections class:

Object[] arrays = Collections.nCopies(size, object).stream().toArray();

In your case it will be:

Integer[] arrays = Collections.nCopies(10, Integer.valueOf(1)).stream().toArray(Integer[]::new);
.

Here is a detailed answer of a similar case of yours.

How do you create a dictionary in Java?

You'll want a Map<String, String>. Classes that implement the Map interface include (but are not limited to):

Each is designed/optimized for certain situations (go to their respective docs for more info). HashMap is probably the most common; the go-to default.

For example (using a HashMap):

Map<String, String> map = new HashMap<String, String>();
map.put("dog", "type of animal");
System.out.println(map.get("dog"));
type of animal

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

Adding an answer that's completely based on and indebted to divestoclimb with a hint from Shaun Stone. Just wanted to spell it out in detail since it's a common problem and the solution is a bit confusing.

This is using Hibernate 4.1.4.Final, though I suspect anything after 3.6 will work.

First, create divestoclimb's UtcTimestampTypeDescriptor

public class UtcTimestampTypeDescriptor extends TimestampTypeDescriptor {
    public static final UtcTimestampTypeDescriptor INSTANCE = new UtcTimestampTypeDescriptor();

    private static final TimeZone UTC = TimeZone.getTimeZone("UTC");

    public <X> ValueBinder<X> getBinder(final JavaTypeDescriptor<X> javaTypeDescriptor) {
        return new BasicBinder<X>( javaTypeDescriptor, this ) {
            @Override
            protected void doBind(PreparedStatement st, X value, int index, WrapperOptions options) throws SQLException {
                st.setTimestamp( index, javaTypeDescriptor.unwrap( value, Timestamp.class, options ), Calendar.getInstance(UTC) );
            }
        };
    }

    public <X> ValueExtractor<X> getExtractor(final JavaTypeDescriptor<X> javaTypeDescriptor) {
        return new BasicExtractor<X>( javaTypeDescriptor, this ) {
            @Override
            protected X doExtract(ResultSet rs, String name, WrapperOptions options) throws SQLException {
                return javaTypeDescriptor.wrap( rs.getTimestamp( name, Calendar.getInstance(UTC) ), options );
            }
        };
    }
}

Then create UtcTimestampType, which uses UtcTimestampTypeDescriptor instead of TimestampTypeDescriptor as the SqlTypeDescriptor in the super constructor call but otherwise delegates everything to TimestampType:

public class UtcTimestampType
        extends AbstractSingleColumnStandardBasicType<Date>
        implements VersionType<Date>, LiteralType<Date> {
    public static final UtcTimestampType INSTANCE = new UtcTimestampType();

    public UtcTimestampType() {
        super( UtcTimestampTypeDescriptor.INSTANCE, JdbcTimestampTypeDescriptor.INSTANCE );
    }

    public String getName() {
        return TimestampType.INSTANCE.getName();
    }

    @Override
    public String[] getRegistrationKeys() {
        return TimestampType.INSTANCE.getRegistrationKeys();
    }

    public Date next(Date current, SessionImplementor session) {
        return TimestampType.INSTANCE.next(current, session);
    }

    public Date seed(SessionImplementor session) {
        return TimestampType.INSTANCE.seed(session);
    }

    public Comparator<Date> getComparator() {
        return TimestampType.INSTANCE.getComparator();        
    }

    public String objectToSQLString(Date value, Dialect dialect) throws Exception {
        return TimestampType.INSTANCE.objectToSQLString(value, dialect);
    }

    public Date fromStringValue(String xml) throws HibernateException {
        return TimestampType.INSTANCE.fromStringValue(xml);
    }
}

Finally, when you initialize your Hibernate configuration, register UtcTimestampType as a type override:

configuration.registerTypeOverride(new UtcTimestampType());

Now timestamps shouldn't be concerned with the JVM's time zone on their way to and from the database. HTH.

How to dockerize maven project? and how many ways to accomplish it?

Create a Dockerfile
#
# Build stage
#

FROM maven:3.6.3-jdk-11-slim AS build

WORKDIR usr/src/app

COPY . ./

RUN mvn clean package

#
# Package stage
#

FROM openjdk:11-jre-slim

ARG JAR_NAME="project-name"

WORKDIR /usr/src/app

EXPOSE ${HTTP_PORT}

COPY --from=build /usr/src/app/target/${JAR_NAME}.jar ./app.jar

CMD ["java","-jar", "./app.jar"]

Regex: matching up to the first occurrence of a character

"/^([^\/]*)\/$/" worked for me, to get only top "folders" from an array like:

a/   <- this
a/b/
c/   <- this
c/d/
/d/e/
f/   <- this

Strip last two characters of a column in MySQL

To select all characters except the last n from a string (or put another way, remove last n characters from a string); use the SUBSTRING and CHAR_LENGTH functions together:

SELECT col
     , /* ANSI Syntax  */ SUBSTRING(col FROM 1 FOR CHAR_LENGTH(col) - 2) AS col_trimmed
     , /* MySQL Syntax */ SUBSTRING(col,     1,    CHAR_LENGTH(col) - 2) AS col_trimmed
FROM tbl

To remove a specific substring from the end of string, use the TRIM function:

SELECT col
     , TRIM(TRAILING '.php' FROM col)
-- index.php becomes index
-- index.txt remains index.txt

GROUP BY + CASE statement

Aliases can be used only if they were introduced in the preceding step. So aliases in the SELECT clause can be used in the ORDER BY but not the GROUP BY clause.

Reference: Microsoft T-SQL Documentation for further reading.

FROM
ON
JOIN
WHERE
GROUP BY
WITH CUBE or WITH ROLLUP
HAVING
SELECT
DISTINCT
ORDER BY
TOP

Hope this helps.

How to determine device screen size category (small, normal, large, xlarge) using code?

private String getDeviceDensity() {
    int density = mContext.getResources().getDisplayMetrics().densityDpi;
    switch (density)
    {
        case DisplayMetrics.DENSITY_MEDIUM:
            return "MDPI";
        case DisplayMetrics.DENSITY_HIGH:
            return "HDPI";
        case DisplayMetrics.DENSITY_LOW:
            return "LDPI";
        case DisplayMetrics.DENSITY_XHIGH:
            return "XHDPI";
        case DisplayMetrics.DENSITY_TV:
            return "TV";
        case DisplayMetrics.DENSITY_XXHIGH:
            return "XXHDPI";
        case DisplayMetrics.DENSITY_XXXHIGH:
            return "XXXHDPI";
        default:
            return "Unknown";
    }
}

How to center an element horizontally and vertically

This should works

_x000D_
_x000D_
.center-div {_x000D_
    display: flex;_x000D_
    flex-direction: column;_x000D_
    justify-content: center;_x000D_
    align-items: center;_x000D_
    text-align: center;_x000D_
    min-height: 100vh;_x000D_
}
_x000D_
<div class="center-div">Center Div</div>
_x000D_
_x000D_
_x000D_

How do I fix PyDev "Undefined variable from import" errors?

My answer doesn't contribute anything new, just a concrete example I encountered.

import gtk.gdk

w = gtk.gdk.get_default_root_window()

PyDev showed the error message "Undefined variable from import: get_default_root_window()"

In the python shell you can see that this is a 'built-in' module as mentioned in a answer above:

>>> import gtk.gdk
>>> gtk.gdk
<module 'gtk.gdk' (built-in)>

Now under Window->Preferences->PyDev->Interpreters->Python Interpreter, I selected the tab 'Forced Builtins' and added 'gtk.gdk' to the list.

Now the error message didn't show anymore.

SQL Server: IF EXISTS ; ELSE

I know its been a while since the original post but I like using CTE's and this worked for me:

WITH cte_table_a
AS
(
    SELECT [id] [id]
    , MAX([value]) [value]
    FROM table_a
    GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN  cte_table_a
ON table_b.id = cte_table_a.id

What's the most efficient way to erase duplicates and sort a vector?

std::set<int> s;
std::for_each(v.cbegin(), v.cend(), [&s](int val){s.insert(val);});
v.clear();
std::copy(s.cbegin(), s.cend(), v.cbegin());

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

Great solution, thank you! I took the AndyDBell's question and Cuong Le's answer to build an example with two diferent interface's implementation:

public interface ISample
{
    int SampleId { get; set; }
}

public class Sample1 : ISample
{
    public int SampleId { get; set; }
    public Sample1() { }
}


public class Sample2 : ISample
{
    public int SampleId { get; set; }
    public String SampleName { get; set; }
    public Sample2() { }
}

public class SampleGroup
{
    public int GroupId { get; set; }
    public IEnumerable<ISample> Samples { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        //Sample1 instance
        var sz = "{\"GroupId\":1,\"Samples\":[{\"SampleId\":1},{\"SampleId\":2}]}";
        var j = JsonConvert.DeserializeObject<SampleGroup>(sz, new SampleConverter<Sample1>());
        foreach (var item in j.Samples)
        {
            Console.WriteLine("id:{0}", item.SampleId);
        }
        //Sample2 instance
        var sz2 = "{\"GroupId\":1,\"Samples\":[{\"SampleId\":1, \"SampleName\":\"Test1\"},{\"SampleId\":2, \"SampleName\":\"Test2\"}]}";
        var j2 = JsonConvert.DeserializeObject<SampleGroup>(sz2, new SampleConverter<Sample2>());
        //Print to show that the unboxing to Sample2 preserved the SampleName's values
        foreach (var item in j2.Samples)
        {
            Console.WriteLine("id:{0} name:{1}", item.SampleId, (item as Sample2).SampleName);
        }
        Console.ReadKey();
    }
}

And a generic version to the SampleConverter:

public class SampleConverter<T> : CustomCreationConverter<ISample> where T: new ()
{
    public override ISample Create(Type objectType)
    {
        return ((ISample)new T());
    }
}

Best way to get hostname with php

For PHP >= 5.3.0 use this:

$hostname = gethostname();

For PHP < 5.3.0 but >= 4.2.0 use this:

$hostname = php_uname('n');

For PHP < 4.2.0 use this:

$hostname = getenv('HOSTNAME'); 
if(!$hostname) $hostname = trim(`hostname`); 
if(!$hostname) $hostname = exec('echo $HOSTNAME');
if(!$hostname) $hostname = preg_replace('#^\w+\s+(\w+).*$#', '$1', exec('uname -a')); 

How to run cron once, daily at 10pm

Here is what I look at everytime I am writing a new crontab entry:

To start editing from terminal -type:

 zee$ crontab -e

what you will add to crontab file:

0 22 * * 0  some-user /opt/somescript/to/run.sh

What it means:

[ 
+ user => 'some-user',      
+ minute => ‘0’,             <<= on top of the hour.
+ hour => '22',              <<= at 10 PM. Military time.
+ monthday => '*',           <<= Every day of the month*
+ month => '*',              <<= Every month*
+ weekday => ‘0’,            <<= Everyday (0 thru 6) = sunday thru saturday
] 

Also, check what shell your machine is running and name the the file accordingly OR it wont execute.

Check the shell with either echo $SHELL or echo $0

It can be "Bourne shell (sh) , Bourne again shell (bash),Korn shell (ksh)..etc"

Is there an equivalent to the SUBSTRING function in MS Access SQL?

You can use the VBA string functions (as @onedaywhen points out in the comments, they are not really the VBA functions, but their equivalents from the MS Jet libraries. As far as function signatures go, they are called and work the same, even though the actual presence of MS Access is not required for them to be available.):

SELECT DISTINCT Left(LastName, 1)
FROM Authors;

SELECT DISTINCT Mid(LastName, 1, 1)
FROM Authors;

How to import module when module name has a '-' dash or hyphen in it?

If you can't rename the original file, you could also use a symlink:

ln -s foo-bar.py foo_bar.py

Then you can just:

from foo_bar import *

Add a dependency in Maven

I'll assume that you're asking how to push a dependency out to a "well-known repository," and not simply asking how to update your POM.

If yes, then this is what you want to read.

And for anyone looking to set up an internal repository server, look here (half of the problem with using Maven 2 is finding the docs)

Add Facebook Share button to static HTML page

This should solve your problem: FB Share button/dialog documentation Genereally speaking you can use either normal HTML code and style it with CSS, or you can use Javascript.

Here is an example:

<a href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fparse.com" target="_blank" rel="noopener">
    <img class="YOUR_FB_CSS_STYLING_CLASS" src="img/YOUR_FB_ICON_IMAGE.png" width="22px" height="22px" alt="Share on Facebook">
</a>

Replace https%3A%2F%2Fparse.com, YOUR_FB_CSS_STYLING_CLASS and YOUR_FB_ICON_IMAGE.png with your own choices and you should be ok.

Note: For the sake of your users' security use the HTTPS link to FB, like in the a's href attribute.

How can I install Apache Ant on Mac OS X?

To get Ant running on your Mac in 5 minutes, follow these steps.

Open up your terminal.

Perform these commands in order:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

brew install ant

If you don't have Java installed yet, you will get the following error: "Error: An unsatisfied requirement failed this build." Run this command next: brew cask install java to fix this.

The installation will resume.

Check your version of by running this command:

ant -version

And you're ready to go!

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

Solution: Edit and save the file!

From VisualStudio go to the View and expand to see it's resx file

Right-click menu select OpenWith... XML (Text) Editor.

Just add a space at the end and save.

How to use setArguments() and getArguments() methods in Fragments?

Eg: Add data:-

   Bundle bundle = new Bundle();
   bundle.putString("latitude", latitude);
   bundle.putString("longitude", longitude);
   bundle.putString("board_id", board_id);
   MapFragment mapFragment = new MapFragment();
   mapFragment.setArguments(bundle);

Eg: Get data :-

String latitude =  getArguments().getString("latitude")

SET NOCOUNT ON usage

Regarding the triggers breaking NHibernate, I had that experience first-hand. Basically, when NH does an UPDATE it expects certain number of rows affected. By adding SET NOCOUNT ON to the triggers you get the number of rows back to what NH expected thereby fixing the issue. So yeah, I would definitely recommend turning it off for triggers if you use NH.

Regarding the usage in SPs, it's a matter of personal preference. I had always turned the row count off, but then again, there are no real strong arguments either way.

On a different note, you should really consider moving away from SP-based architecture, then you won't even have this question.

Hide scroll bar, but while still being able to scroll

This will be at the body:

<div id="maincontainer" >
<div id="child">this is the 1st step</div>
<div id="child">this is the 2nd step</div>
<div id="child">this is the 3rd step</div>

And this is the CSS:

#maincontainer
{
    background: grey;
    width: 101%;
    height: 101%;
    overflow: auto;
    position: fixed;
}

#child
{
    background: white;
    height:500px;
}

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

How do I change the figure size with subplots?

If you already have the figure object use:

f.set_figheight(15)
f.set_figwidth(15)

But if you use the .subplots() command (as in the examples you're showing) to create a new figure you can also use:

f, axs = plt.subplots(2,2,figsize=(15,15))

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

While both reducebykey and groupbykey will produce the same answer, the reduceByKey example works much better on a large dataset. That's because Spark knows it can combine output with a common key on each partition before shuffling the data.

On the other hand, when calling groupByKey - all the key-value pairs are shuffled around. This is a lot of unnessary data to being transferred over the network.

for more detailed check this below link

https://databricks.gitbooks.io/databricks-spark-knowledge-base/content/best_practices/prefer_reducebykey_over_groupbykey.html

What is the different between RESTful and RESTless

Here are summarized the key differences between RESTful and RESTless web services:

1. Protocol

  • RESTful services use REST architectural style,
  • RESTless services use SOAP protocol.

2. Business logic / Functionality

  • RESTful services use URL to expose business logic,
  • RESTless services use the service interface to expose business logic.

3. Security

  • RESTful inherits security from the underlying transport protocols,
  • RESTless defines its own security layer, thus it is considered as more secure.

4. Data format

  • RESTful supports various data formats such as HTML, JSON, text, etc,
  • RESTless supports XML format.

5. Flexibility

  • RESTful is easier and flexible,
  • RESTless is not as easy and flexible.

6. Bandwidth

  • RESTful services consume less bandwidth and resource,
  • RESTless services consume more bandwidth and resources.

Time complexity of nested for-loop

Yes, the time complexity of this is O(n^2).

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

Actually python will reclaim the memory which is not in use anymore.This is called garbage collection which is automatic process in python. But still if you want to do it then you can delete it by del variable_name. You can also do it by assigning the variable to None

a = 10
print a 

del a       
print a      ## throws an error here because it's been deleted already.

The only way to truly reclaim memory from unreferenced Python objects is via the garbage collector. The del keyword simply unbinds a name from an object, but the object still needs to be garbage collected. You can force garbage collector to run using the gc module, but this is almost certainly a premature optimization but it has its own risks. Using del has no real effect, since those names would have been deleted as they went out of scope anyway.

Laravel requires the Mcrypt PHP extension

In Ubuntu (PHP-FPM,Nginx)

sudo apt-get install php5-mcrypt

After installing php5-mcrypt

you have to make a symlink to ini files in mods-available:

sudo ln -s /etc/php5/conf.d/mcrypt.ini /etc/php5/mods-available/mcrypt.ini

enable:

sudo php5enmod mcrypt

restart php5-fpm:

sudo service php5-fpm restart

More detail

Multiline for WPF TextBox

Also, if, like me, you add controls directly in XAML (not using the editor), you might get frustrated that it won't stretch to the available height, even after setting those two properties.

To make the TextBox stretch, set the Height="Auto".

UPDATE:

In retrospect, I think this must have been necessary thanks to a default style for TextBoxes specifying the height to some standard for the application somewhere in the App resources. It may be worthwhile checking this if this helped you.

How to create a template function within a class? (C++)

Yes, template member functions are perfectly legal and useful on numerous occasions.

The only caveat is that template member functions cannot be virtual.

Simple Android RecyclerView example

The following is a minimal example that will look like the following image.

RecyclerView with a list of animal names

Start with an empty activity. You will perform the following tasks to add the RecyclerView. All you need to do is copy and paste the code in each section. Later you can customize it to fit your needs.

  • Add dependencies to gradle
  • Add the xml layout files for the activity and for the RecyclerView row
  • Make the RecyclerView adapter
  • Initialize the RecyclerView in your activity

Update Gradle dependencies

Make sure the following dependencies are in your app gradle.build file:

implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:recyclerview-v7:28.0.0'

You can update the version numbers to whatever is the most current. Use compile rather than implementation if you are still using Android Studio 2.x.

Create activity layout

Add the RecyclerView to your xml layout.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rvAnimals"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</RelativeLayout>

Create row layout

Each row in our RecyclerView is only going to have a single TextView. Create a new layout resource file.

recyclerview_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:padding="10dp">

    <TextView
        android:id="@+id/tvAnimalName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp"/>

</LinearLayout>

Create the adapter

The RecyclerView needs an adapter to populate the views in each row with your data. Create a new java file.

MyRecyclerViewAdapter.java

public class MyRecyclerViewAdapter extends RecyclerView.Adapter<MyRecyclerViewAdapter.ViewHolder> {

    private List<String> mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    // data is passed into the constructor
    MyRecyclerViewAdapter(Context context, List<String> data) {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }

    // inflates the row layout from xml when needed
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.recyclerview_row, parent, false);
        return new ViewHolder(view);
    }

    // binds the data to the TextView in each row
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String animal = mData.get(position);
        holder.myTextView.setText(animal);
    }

    // total number of rows
    @Override
    public int getItemCount() {
        return mData.size();
    }


    // stores and recycles views as they are scrolled off screen
    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.tvAnimalName);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    // convenience method for getting data at click position
    String getItem(int id) {
        return mData.get(id);
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }
}

Notes

  • Although not strictly necessary, I included the functionality for listening for click events on the rows. This was available in the old ListViews and is a common need. You can remove this code if you don't need it.

Initialize RecyclerView in Activity

Add the following code to your main activity.

MainActivity.java

public class MainActivity extends AppCompatActivity implements MyRecyclerViewAdapter.ItemClickListener {

    MyRecyclerViewAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // data to populate the RecyclerView with
        ArrayList<String> animalNames = new ArrayList<>();
        animalNames.add("Horse");
        animalNames.add("Cow");
        animalNames.add("Camel");
        animalNames.add("Sheep");
        animalNames.add("Goat");

        // set up the RecyclerView
        RecyclerView recyclerView = findViewById(R.id.rvAnimals);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new MyRecyclerViewAdapter(this, animalNames);
        adapter.setClickListener(this);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
    }
}

Notes

  • Notice that the activity implements the ItemClickListener that we defined in our adapter. This allows us to handle row click events in onItemClick.

Finished

That's it. You should be able to run your project now and get something similar to the image at the top.

Going on

Adding a divider between rows

You can add a simple divider like this

DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(recyclerView.getContext(),
    layoutManager.getOrientation());
recyclerView.addItemDecoration(dividerItemDecoration);

If you want something a little more complex, see the following answers:

Changing row color on click

See this answer for how to change the background color and add the Ripple Effect when a row is clicked.

Insert single item

Updating rows

See this answer for how to add, remove, and update rows.

Insert single item

Further reading

Drop Down Menu/Text Field in one

The modern solution is an input field of type "search"!

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/search https://www.w3schools.com/tags/tag_datalist.asp

Somewhere in your HTML you define a datalist for later reference:

<datalist id="mylist">
   <option value="Option 1">
   <option value="Option 2">
   <option value="Option 3">
</datalist>

Then you can define your search input like this:

<input type="search" list="mylist">

Voilà. Very nice and easy.

Calling a method inside another method in same class

Recursion is a method that call itself. In this case it is a recursion. However it will be overloading until you put a restriction inside the method to stop the loop (if-condition).

Python - Get path of root project structure

Below Code Returns the path until your project root

import sys
print(sys.path[1])

Http post and get request in angular 6

For reading full response in Angular you should add the observe option:

{ observe: 'response' }
    return this.http.get(`${environment.serverUrl}/api/posts/${postId}/comments/?page=${page}&size=${size}`, { observe: 'response' });

Parallel foreach with asynchronous lambda

With SemaphoreSlim you can achieve parallelism control.

var bag = new ConcurrentBag<object>();
var maxParallel = 20;
var throttler = new SemaphoreSlim(initialCount: maxParallel);
var tasks = myCollection.Select(async item =>
{
  try
  {
     await throttler.WaitAsync();
     var response = await GetData(item);
     bag.Add(response);
  }
  finally
  {
     throttler.Release();
  }
});
await Task.WhenAll(tasks);
var count = bag.Count;

How to add image for button in android?

you can use ImageView as Button. Create an ImageView and set clickable true after in write imageView.setOnClickListener for ImageView.

  <ImageView
android:clickable="true"
android:focusable="true"`
android:id="@+id/imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

and in Activity's oncreate:

imageView.setOnClickListener(...

What is the difference between @Inject and @Autowired in Spring Framework? Which one to use under what condition?

Here is a blog post that compares @Resource, @Inject, and @Autowired, and appears to do a pretty comprehensive job.

From the link:

With the exception of test 2 & 7 the configuration and outcomes were identical. When I looked under the hood I determined that the ‘@Autowired’ and ‘@Inject’ annotation behave identically. Both of these annotations use the ‘AutowiredAnnotationBeanPostProcessor’ to inject dependencies. ‘@Autowired’ and ‘@Inject’ can be used interchangeable to inject Spring beans. However the ‘@Resource’ annotation uses the ‘CommonAnnotationBeanPostProcessor’ to inject dependencies. Even though they use different post processor classes they all behave nearly identically. Below is a summary of their execution paths.

Tests 2 and 7 that the author references are 'injection by field name' and 'an attempt at resolving a bean using a bad qualifier', respectively.

The Conclusion should give you all the information you need.

How do I create and store md5 passwords in mysql

just get the hash by following line and store it into the database:

$encryptedValue = md5("YOUR STRING");

How to set session timeout dynamically in Java web applications?

As another anwsers told, you can change in a Session Listener. But you can change it directly in your servlet, for example.

getRequest().getSession().setMaxInactiveInterval(123);

Spring Boot default H2 jdbc connection (and H2 console)

If you use Spring Boot's developer tools, it comes with H2 Console enabled by default. It can be accessed from /h2-console/. On the login interface, for input JDBC URL use value jdbc:h2:mem:testdb. Pay attention to mem string.

If you don't use Spring Boot's developer tools, you can enable the console in application.properties using spring.h2.console.enabled=true. This will enable console under /h2-console. If you want to change the URL then you can add another entry with spring.h2.console.path=my_console_path.

The default schema name is testdb.

More details in Spring Boot Documentation.

String.Format like functionality in T-SQL?

take a look at xp_sprintf. example below.

DECLARE @ret_string varchar (255)
EXEC xp_sprintf @ret_string OUTPUT, 
    'INSERT INTO %s VALUES (%s, %s)', 'table1', '1', '2'
PRINT @ret_string

Result looks like this:

INSERT INTO table1 VALUES (1, 2)

Just found an issue with the max size (255 char limit) of the string with this so there is an alternative function you can use:

create function dbo.fnSprintf (@s varchar(MAX), 
                @params varchar(MAX), @separator char(1) = ',')
returns varchar(MAX)
as
begin
declare @p varchar(MAX)
declare @paramlen int

set @params = @params + @separator
set @paramlen = len(@params)
while not @params = ''
begin
    set @p = left(@params+@separator, charindex(@separator, @params)-1)
    set @s = STUFF(@s, charindex('%s', @s), 2, @p)
    set @params = substring(@params, len(@p)+2, @paramlen)
end
return @s
end

To get the same result as above you call the function as follows:

print dbo.fnSprintf('INSERT INTO %s VALUES (%s, %s)', 'table1,1,2', default)

Php, wait 5 seconds before executing an action

i use this

    $i = 1;
    $last_time = $_SERVER['REQUEST_TIME'];
    while($i > 0){
        $total = $_SERVER['REQUEST_TIME'] - $last_time;
        if($total >= 2){
            // Code Here
            $i = -1;
        }
    }

you can use

function WaitForSec($sec){
    $i = 1;
    $last_time = $_SERVER['REQUEST_TIME'];
    while($i > 0){
        $total = $_SERVER['REQUEST_TIME'] - $last_time;
        if($total >= 2){
            return 1;
            $i = -1;
        }
    }
}

and run code =>

WaitForSec(your_sec);

Example :

WaitForSec(5);

OR you can use sleep

Example :

sleep(5);

The server encountered an internal error or misconfiguration and was unable to complete your request

You should look for the error in the file error_log in the log directory. Maybe there are differences between your local and server configuration (db user/password etc.etc.)

usually the log file is in

/var/log/apache2/error.log

or

/var/log/httpd/error.log

How to detect my browser version and operating system using JavaScript?

For Firefox, Chrome, Opera, Internet Explorer and Safari

var ua="Mozilla/1.22 (compatible; MSIE 10.0; Windows 3.1)";
//ua = navigator.userAgent;
var b;
var browser;
if(ua.indexOf("Opera")!=-1) {

    b=browser="Opera";
}
if(ua.indexOf("Firefox")!=-1 && ua.indexOf("Opera")==-1) {
    b=browser="Firefox";
    // Opera may also contains Firefox
}
if(ua.indexOf("Chrome")!=-1) {
    b=browser="Chrome";
}
if(ua.indexOf("Safari")!=-1 && ua.indexOf("Chrome")==-1) {
    b=browser="Safari";
    // Chrome always contains Safari
}

if(ua.indexOf("MSIE")!=-1 && (ua.indexOf("Opera")==-1 && ua.indexOf("Trident")==-1)) {
    b="MSIE";
    browser="Internet Explorer";
    //user agent with MSIE and Opera or MSIE and Trident may exist.
}

if(ua.indexOf("Trident")!=-1) {
    b="Trident";
    browser="Internet Explorer";
}

// now for version


var version=ua.match(b+"[ /]+[0-9]+(.[0-9]+)*")[0];

console.log("broswer",browser);
console.log("version",version);

Sending Multipart File as POST parameters with RestTemplate requests

MultiValueMap<String, Object> parts = new LinkedMultiValueMap<String, Object>();
parts.add("name 1", "value 1");
parts.add("name 2", "value 2+1");
parts.add("name 2", "value 2+2");
Resource logo = new ClassPathResource("/org/springframework/http/converter/logo.jpg");
parts.add("logo", logo);
Source xml = new StreamSource(new StringReader("<root><child/></root>"));
parts.add("xml", xml);

template.postForLocation("http://example.com/multipart", parts);

How to get .pem file from .key and .crt files?

Additionally, if you don't want it to ask for a passphrase, then need to run the following command:

openssl rsa -in server.key -out server.key

Basic example of using .ajax() with JSONP?

<!DOCTYPE html>
<html>
<head>
<style>img{ height: 100px; float: left; }</style>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<title>An JSONP example </title>
</head>
<body>
<!-- DIV FOR SHOWING IMAGES -->
<div id="images">
</div>
<!-- SCRIPT FOR GETTING IMAGES FROM FLICKER.COM USING JSONP -->
<script>
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?",
{
  format: "json"
},
//RETURNED RESPONSE DATA IS LOOPED AND ONLY IMAGE IS APPENDED TO IMAGE DIV
function(data) {
  $.each(data.items, function(i,item){
  $("<img/>").attr("src", item.media.m).appendTo("#images");

 });
});</script>
</body>
</html> 

The above code helps in getting images from the Flicker API. This uses the GET method for getting images using JSONP. It can be found in detail in here

Why do you use typedef when declaring an enum in C++?

It's a C heritage, in C, if you do :

enum TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
};

you'll have to use it doing something like :

enum TokenType foo;

But if you do this :

typedef enum e_TokenType
{
    blah1   = 0x00000000,
    blah2   = 0X01000000,
    blah3   = 0X02000000
} TokenType;

You'll be able to declare :

TokenType foo;

But in C++, you can use only the former definition and use it as if it were in a C typedef.

What does "Object reference not set to an instance of an object" mean?

If I have the class:

public class MyClass
{
   public void MyMethod()
   {

   }
}

and I then do:

MyClass myClass = null;
myClass.MyMethod();

The second line throws this exception becuase I'm calling a method on a reference type object that is null (I.e. has not been instantiated by calling myClass = new MyClass())

How can I stage and commit all files, including newly added files, using a single command?

Not sure why these answers all dance around what I believe to be the right solution but for what it's worth here is what I use:

1. Create an alias:

git config --global alias.coa "!git add -A && git commit -m"

2. Add all files & commit with a message:

git coa "A bunch of horrible changes"

NOTE: coa is short for commit all and can be replaced with anything your heart desires

How to print a linebreak in a python function?

The newline character is actually '\n'.

write multiple lines in a file in python

Assuming you don't want a space at each new line use:

print("I'm going to write these to the file")
target.write("%s\n%s\n%s\n" % (line1, line2, line3))

This works for version 3.6

Adding backslashes without escaping [Python]

printing a list can also cause this problem (im new in python, so it confused me a bit too):

>>>myList = ['\\']
>>>print myList
['\\']
>>>print ''.join(myList)
\ 

similarly:

>>>myList = ['\&']
>>>print myList
['\\&']
>>>print ''.join(myList)
\&

Converting String to Int with Swift

Basic Idea, note that this only works in Swift 1.x (check out ParaSara's answer to see how it works in Swift 2.x):

    // toInt returns optional that's why we used a:Int?
    let a:Int? = firstText.text.toInt() // firstText is UITextField
    let b:Int? = secondText.text.toInt() // secondText is UITextField

    // check a and b before unwrapping using !
    if a && b {
        var ans = a! + b!
        answerLabel.text = "Answer is \(ans)" // answerLabel ie UILabel
    } else {
        answerLabel.text = "Input values are not numeric"
    }

Update for Swift 4

...
let a:Int? = Int(firstText.text) // firstText is UITextField
let b:Int? = Int(secondText.text) // secondText is UITextField
...

Converting HTML string into DOM elements?

You can use a DOMParser, like so:

_x000D_
_x000D_
var xmlString = "<div id='foo'><a href='#'>Link</a><span></span></div>";_x000D_
var doc = new DOMParser().parseFromString(xmlString, "text/xml");_x000D_
console.log(doc.firstChild.innerHTML); // => <a href="#">Link..._x000D_
console.log(doc.firstChild.firstChild.innerHTML); // => Link
_x000D_
_x000D_
_x000D_

How to put a jpg or png image into a button in HTML

You can style the button using CSS or use an image-input. Additionally you might use the button element which supports inline content.

<button type="submit"><img src="/path/to/image" alt="Submit"></button>

How to load all modules in a folder?

Just import them by importlib and add them to __all__ (add action is optional) in recurse in the __init__.py of package.

/Foo
    bar.py
    spam.py
    eggs.py
    __init__.py

# __init__.py
import os
import importlib
pyfile_extes = ['py', ]
__all__ = [importlib.import_module('.%s' % filename, __package__) for filename in [os.path.splitext(i)[0] for i in os.listdir(os.path.dirname(__file__)) if os.path.splitext(i)[1] in pyfile_extes] if not filename.startswith('__')]
del os, importlib, pyfile_extes

Get absolute path of initially run script

__DIR__

From the manual:

The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FILE__ always contains an absolute path with symlinks resolved whereas in older versions (than 4.0.2) it contained relative path under some circumstances.

Note: __DIR__ was added in PHP 5.3.0.

Where's my JSON data in my incoming Django request?

request.raw_response is now deprecated. Use request.body instead to process non-conventional form data such as XML payloads, binary images, etc.

Django documentation on the issue.

How to register ASP.NET 2.0 to web server(IIS7)?

I got it resolved by doing Repir on .NET framework Extended, in Add/Remove program ;

Using win2008R2, .NET framework 4.0

In C#, why is String a reference type that behaves like a value type?

The distinction between reference types and value types are basically a performance tradeoff in the design of the language. Reference types have some overhead on construction and destruction and garbage collection, because they are created on the heap. Value types on the other hand have overhead on method calls (if the data size is larger than a pointer), because the whole object is copied rather than just a pointer. Because strings can be (and typically are) much larger than the size of a pointer, they are designed as reference types. Also, as Servy pointed out, the size of a value type must be known at compile time, which is not always the case for strings.

The question of mutability is a separate issue. Both reference types and value types can be either mutable or immutable. Value types are typically immutable though, since the semantics for mutable value types can be confusing.

Reference types are generally mutable, but can be designed as immutable if it makes sense. Strings are defined as immutable because it makes certain optimizations possible. For example, if the same string literal occurs multiple times in the same program (which is quite common), the compiler can reuse the same object.

So why is "==" overloaded to compare strings by text? Because it is the most useful semantics. If two strings are equal by text, they may or may not be the same object reference due to the optimizations. So comparing references are pretty useless, while comparing text are almost always what you want.

Speaking more generally, Strings has what is termed value semantics. This is a more general concept than value types, which is a C# specific implementation detail. Value types have value semantics, but reference types may also have value semantics. When a type have value semantics, you can't really tell if the underlying implementation is a reference type or value type, so you can consider that an implementation detail.

How to disable text selection highlighting

A JavaScript solution for Internet Explorer is:

onselectstart="return false;"

pandas get column average/mean

You can easily follow the following code

import pandas as pd 
import numpy as np 
        
classxii = {'Name':['Karan','Ishan','Aditya','Anant','Ronit'],
            'Subject':['Accounts','Economics','Accounts','Economics','Accounts'],
            'Score':[87,64,58,74,87],
            'Grade':['A1','B2','C1','B1','A2']}

df = pd.DataFrame(classxii,index = ['a','b','c','d','e'],columns=['Name','Subject','Score','Grade'])
print(df)

#use the below for mean if you already have a dataframe
print('mean of score is:')
print(df[['Score']].mean())

Object Library Not Registered When Adding Windows Common Controls 6.0

To overcome the issue of Win7 32bit VB6, try copying from Windows Server 2003 C:\Windows\system32\ the files mscomctl.ocx and mscomcctl.oba.

How to center cards in bootstrap 4?

Update 2018

There is no need for extra CSS, and there are multiple centering methods in Bootstrap 4:

  • text-center for center display:inline elements
  • mx-auto for centering display:block elements inside display:flex (d-flex)
  • offset-* or mx-auto can be used to center grid columns
  • or justify-content-center on row to center grid columns

mx-auto (auto x-axis margins) will center inside display:flex elements that have a defined width, (%, vw, px, etc..). Flexbox is used by default on grid columns, so there are also various centering methods.

In your case, you can simply mx-auto to the cards.

How to get href value using jQuery?

It's worth mentioning that

$('a').attr('href'); // gets the actual value
$('a').prop('href'); // gets the full URL always

Update span tag value with JQuery

Tag ids must be unique. You are updating the span with ID 'ItemCostSpan' of which there are two. Give the span a class and get it using find.

    $("legend").each(function() {
        var SoftwareItem = $(this).text();
        itemCost = GetItemCost(SoftwareItem);
        $("input:checked").each(function() {               
            var Component = $(this).next("label").text();
            itemCost += GetItemCost(Component);
        });            
        $(this).find(".ItemCostSpan").text("Item Cost = $ " + itemCost);
    });

jQuery animate backgroundColor

For anyone finding this. Your better off using the jQuery UI version because it works on all browsers. The color plugin has issues with Safari and Chrome. It only works sometimes.

How do you split and unsplit a window/view in Eclipse IDE?

This is possible with the menu items Window>Editor>Toggle Split Editor.

Current shortcut for splitting is:

Azerty keyboard:

  • Ctrl + _ for split horizontally, and
  • Ctrl + { for split vertically.

Qwerty US keyboard:

  • Ctrl + Shift + - (accessing _) for split horizontally, and
  • Ctrl + Shift + [ (accessing {) for split vertically.

MacOS - Qwerty US keyboard:

  • + Shift + - (accessing _) for split horizontally, and
  • + Shift + [ (accessing {) for split vertically.

On any other keyboard if a required key is unavailable (like { on a german Qwertz keyboard), the following generic approach may work:

  • Alt + ASCII code + Ctrl then release Alt

Example: ASCII for '{' = 123, so press 'Alt', '1', '2', '3', 'Ctrl' and release 'Alt', effectively typing '{' while 'Ctrl' is pressed, to split vertically.

Example of vertical split:

https://bugs.eclipse.org/bugs/attachment.cgi?id=238285

PS:

  • The menu items Window>Editor>Toggle Split Editor were added with Eclipse Luna 4.4 M4, as mentioned by Lars Vogel in "Split editor implemented in Eclipse M4 Luna"
  • The split editor is one of the oldest and most upvoted Eclipse bug! Bug 8009
  • The split editor functionality has been developed in Bug 378298, and will be available as of Eclipse Luna M4. The Note & Newsworthy of Eclipse Luna M4 will contain the announcement.

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

Little bit late answering that but there we go.

I could solve this using Environment.CurrentDirectory

Where is web.xml in Eclipse Dynamic Web Project

The web.xml file should be listed right below the last line in your screenshot and resides in WebContent/WEB-INF. If it is missing you might have missed to check the "Generate web.xml deployment descriptor" option on the third page of the Dynamic web project wizard.

MessageBox Buttons?

This way to check the condition while pressing 'YES' or 'NO' buttons in MessageBox window.

DialogResult d = MessageBox.Show("Are you sure ?", "Remove Panel", MessageBoxButtons.YesNo);
            if (d == DialogResult.Yes)
            {
                //Contents
            }
            else if (d == DialogResult.No)
            {
                //Contents
            }

How to delete specific columns with VBA?

You were just missing the second half of the column statement telling it to remove the entire column, since most normal Ranges start with a Column Letter, it was looking for a number and didn't get one. The ":" gets the whole column, or row.

I think what you were looking for in your Range was this:

Range("C:C,F:F,I:I,L:L,O:O,R:R").Delete

Just change the column letters to match your needs.

Python module for converting PDF to text

Found that solution today. Works great for me. Even rendering PDF pages to PNG images. http://www.swftools.org/gfx_tutorial.html

WSDL vs REST Pros and Cons

The previous answers contain a lot of information, but I think there is a philosophical difference that hasn't been pointed out. SOAP was the answer to "how to we create a modern, object-oriented, platform and protocol independent successor to RPC?". REST developed from the question, "how to we take the insights that made HTTP so successful for the web, and use them for distributed computing?"

SOAP is a about giving you tools to make distributed programming look like ... programming. REST tries to impose a style to simplify distributed interfaces, so that distributed resources can refer to each other like distributed html pages can refer to each other. One way it does that is attempt to (mostly) restrict operations to "CRUD" on resources (create, read, update, delete).

REST is still young -- although it is oriented towards "human readable" services, it doesn't rule out introspection services, etc. or automatic creation of proxies. However, these have not been standardized (as I write). SOAP gives you these things, but (IMHO) gives you "only" these things, whereas the style imposed by REST is already encouraging the spread of web services because of its simplicity. I would myself encourage newbie service providers to choose REST unless there are specific SOAP-provided features they need to use.

In my opinion, then, if you are implementing a "greenfield" API, and don't know that much about possible clients, I would choose REST as the style it encourages tends to help make interfaces comprehensible, and easy to develop to. If you know a lot about client and server, and there are specific SOAP tools that will make life easy for both, then I wouldn't be religious about REST, though.

Find size and free space of the filesystem containing a given file

As of Python 3.3, there an easy and direct way to do this with the standard library:

$ cat free_space.py 
#!/usr/bin/env python3

import shutil

total, used, free = shutil.disk_usage(__file__)
print(total, used, free)

$ ./free_space.py 
1007870246912 460794834944 495854989312

These numbers are in bytes. See the documentation for more info.

How can I remove non-ASCII characters but leave periods and spaces using Python?

If you want printable ascii characters you probably should correct your code to:

if ord(char) < 32 or ord(char) > 126: return ''

this is equivalent, to string.printable (answer from @jterrace), except for the absence of returns and tabs ('\t','\n','\x0b','\x0c' and '\r') but doesnt correspond to the range on your question

How to stop tracking and ignore changes to a file in Git?

To prevent monitoring a file by git

git update-index --assume-unchanged [file-path]

And to revert it back use

git update-index --no-assume-unchanged [file-path]

A repo to refer for similar use cases https://github.com/awslabs/git-secrets

How do I test for an empty JavaScript object?

This is what I came up with, to tell if there are any non-null values in the object.

function isEmpty(obj: Object): Boolean {
    for (const prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (obj[prop] instanceof Object) {
                const rtn = this.isEmpty(obj[prop]);
                if (rtn === false) {
                  return false;
                }
            } else if (obj[prop] || obj[prop] === false) {
                return false;
            }
        }
    }
    return true;
}

ExpressionChangedAfterItHasBeenCheckedError Explained

Update

I highly recommend starting with the OP's self response first: properly think about what can be done in the constructor vs what should be done in ngOnChanges().

Original

This is more a side note than an answer, but it might help someone. I stumbled upon this problem when trying to make the presence of a button depend on the state of the form:

<button *ngIf="form.pristine">Yo</button>

As far as I know, this syntax leads to the button being added and removed from the DOM based on the condition. Which in turn leads to the ExpressionChangedAfterItHasBeenCheckedError.

The fix in my case (although I don't claim to grasp the full implications of the difference), was to use display: none instead:

<button [style.display]="form.pristine ? 'inline' : 'none'">Yo</button>

Uninstalling Android ADT

If running on windows vista or later,
remember to run eclipse under a user with proper file permissions.
try to use the 'Run as Administrator' option.

What can I use for good quality code coverage for C#/.NET?

TestCocoon is also pretty nice. It is in active development and has a user community:

  • Open source (GPL 3)
  • Supports C/C++/C# cross platform (Linux, Windows, and Mac)
  • CoverageScanner - Instrumentation during the Generation
  • CoverageBrowser - View, Analysis and Management of Code Coverage Result

However, TestCocoon is no longer developed and its creators are now producing a commercial software for C/C++.

Trim a string based on the string length

s = s.substring(0, Math.min(s.length(), 10));

Using Math.min like this avoids an exception in the case where the string is already shorter than 10.


Notes:

  1. The above does real trimming. If you actually want to replace the last three (!) characters with dots if it truncates, then use Apache Commons StringUtils.abbreviate.

  2. For typical implementations of String, s.substring(0, s.length()) will return s rather than allocating a new String.

  3. This may behave incorrectly1 if your String contains Unicode codepoints outside of the BMP; e.g. Emojis. For a (more complicated) solution that works correctly for all Unicode code-points, see @sibnick's solution.


1 - A Unicode codepoint that is not on plane 0 (the BMP) is represented as a "surrogate pair" (i.e. two char values) in the String. By ignoring this, we might trim to fewer than 10 code points, or (worse) truncate in the middle of a surrogate pair. On the other hand, String.length() is no longer an ideal measure of Unicode text length, so trimming based on it may be the wrong thing to do.

How can I open an Excel file in Python?

Edit:
In the newer version of pandas, you can pass the sheet name as a parameter.

file_name =  # path to file + file name
sheet =  # sheet name or sheet number or list of sheet numbers and names

import pandas as pd
df = pd.read_excel(io=file_name, sheet_name=sheet)
print(df.head(5))  # print first 5 rows of the dataframe

Check the docs for examples on how to pass sheet_name:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_excel.html

Old version:
you can use pandas package as well....

When you are working with an excel file with multiple sheets, you can use:

import pandas as pd
xl = pd.ExcelFile(path + filename)
xl.sheet_names

>>> [u'Sheet1', u'Sheet2', u'Sheet3']

df = xl.parse("Sheet1")
df.head()

df.head() will print first 5 rows of your Excel file

If you're working with an Excel file with a single sheet, you can simply use:

import pandas as pd
df = pd.read_excel(path + filename)
print df.head()

Read Variable from Web.Config

If you want the basics, you can access the keys via:

string myKey = System.Configuration.ConfigurationManager.AppSettings["myKey"].ToString();
string imageFolder = System.Configuration.ConfigurationManager.AppSettings["imageFolder"].ToString();

To access my web config keys I always make a static class in my application. It means I can access them wherever I require and I'm not using the strings all over my application (if it changes in the web config I'd have to go through all the occurrences changing them). Here's a sample:

using System.Configuration;

public static class AppSettingsGet
{    
    public static string myKey
    {
        get { return ConfigurationManager.AppSettings["myKey"].ToString(); }
    }

    public static string imageFolder
    {
        get { return ConfigurationManager.AppSettings["imageFolder"].ToString(); }
    }

    // I also get my connection string from here
    public static string ConnectionString
    {
       get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
    }
}

Difference between Static methods and Instance methods

In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.

This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.

class A {
    int a;
    int b;

    public void setParameters(int a, int b){
        this.a = a;
        this.b = b;
    }
    public int add(){
        return this.a + this.b;
   }

    public static returnSum(int s1, int s2){
        return (s1 + s2);
    }
}

In the above example, when you call add() as:

A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3 

B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5

//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10

class B{
    int s=8;
    int t = 8;
    public addition(int s,int t){
       A.returnSum(s,t);//returns 16
    }
}

In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.

How to execute function in SQL Server 2008

you may be create function before so, update your function again using.

Alter FUNCTION dbo.Afisho_rankimin(@emri_rest int)
RETURNS int
AS
  BEGIN
     Declare @rankimi int
     Select @rankimi=dbo.RESTORANTET.Rankimi
     From RESTORANTET
     Where  dbo.RESTORANTET.ID_Rest=@emri_rest
     RETURN @rankimi
END
GO

SELECT dbo.Afisho_rankimin(5) AS Rankimi
GO