Programs & Examples On #Websphere 6.1

Use this tag for questions related to version 6.1 of IBM's WebSphere Application Server.

Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.

The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.


EDIT 2019:

The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:

CREATE TABLE Source
(
  EmployeeID int,
  DateStarted date,
  DepartmentID int
)

INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)


SELECT *, 
  ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
  newid() as GroupKey,
  CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;

UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 GroupKey
    FROM #RankedData sub 
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID = sup.DepartmentID AND
      NOT EXISTS 
        (
          SELECT * 
          FROM #RankedData bot 
          WHERE bot.EmployeeID = sup.EmployeeID AND
            bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
            bot.DepartmentID <> sup.DepartmentID
        )
      ORDER BY DateStarted ASC
    ) beginDate (GroupKey);

UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
  CROSS APPLY 
  (
    SELECT TOP 1 DateStarted
    FROM #RankedData sub
    WHERE sub.EmployeeID = sup.EmployeeID AND
      sub.DepartmentID <> sup.DepartmentID AND
      sub.EntryRank > sup.EntryRank
    ORDER BY EntryRank ASC
  ) nextGroup (DateStarted);

SELECT * FROM 
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;

DROP TABLE #RankedData
DROP TABLE Source

Copying files into the application folder at compile time

You can use a MSBuild task on your csproj, like that.

Edit your csproj file

  <Target Name="AfterBuild">
    <Copy SourceFiles="$(OutputPath)yourfiles" DestinationFolder="$(YourVariable)" ContinueOnError="true" />
  </Target>

Insert new column into table in sqlite?

You have two options. First, you could simply add a new column with the following:

ALTER TABLE {tableName} ADD COLUMN COLNew {type};

Second, and more complicatedly, but would actually put the column where you want it, would be to rename the table:

ALTER TABLE {tableName} RENAME TO TempOldTable;

Then create the new table with the missing column:

CREATE TABLE {tableName} (name TEXT, COLNew {type} DEFAULT {defaultValue}, qty INTEGER, rate REAL);

And populate it with the old data:

INSERT INTO {tableName} (name, qty, rate) SELECT name, qty, rate FROM TempOldTable;

Then delete the old table:

DROP TABLE TempOldTable;

I'd much prefer the second option, as it will allow you to completely rename everything if need be.

CSS "and" and "or"

AND (&&):

.registration_form_right input:not([type="radio"]):not([type="checkbox"])

OR (||):

.registration_form_right input:not([type="radio"]), 
   .registration_form_right input:not([type="checkbox"])

How to push both key and value into an Array in Jquery

arr[title] = link;

You're not pushing into the array, you're setting the element with the key title to the value link. As such your array should be an object.

How to convert SQL Server's timestamp column to datetime format

Why not try FROM_UNIXTIME(unix_timestamp, format)?

SQL Server® 2016, 2017 and 2019 Express full download

Download the developer edition. There you can choose Express as license when installing.

enter image description here

Notepad++ incrementally replace


Solutions suggested above will work only if data is aligned..
See solution in the link using PythonScript Notepad++ plugin, It Works great!

stackoverflow Find/Replace but Increment Value

how to implement a pop up dialog box in iOS

Since the release of iOS 8, UIAlertView is now deprecated; UIAlertController is the replacement.

Here is a sample of how it looks in Swift:

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: UIAlertControllerStyle.alert)
let alertAction = UIAlertAction(title: "OK!", style: UIAlertActionStyle.default)
{
    (UIAlertAction) -> Void in
}
alert.addAction(alertAction)
present(alert, animated: true)
{
    () -> Void in
}

As you can see, the API allows us to implement callbacks for both the action and when we are presenting the alert, which is quite handy!

Updated for Swift 4.2

let alert = UIAlertController(title: "Hello!", message: "Message", preferredStyle: .alert)
let alertAction = UIAlertAction(title: "OK!", style: .default)
        {
            (UIAlertAction) -> Void in
        }
        alert.addAction(alertAction)
        present(alert, animated: true)
        {
            () -> Void in
        }

Simplest way to do grouped barplot

There are several ways to do plots in R; lattice is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:

Reasonstats <- read.table(text="Category         Reason  Species
                                 Decline        Genuine       24
                                Improved        Genuine       16
                                Improved  Misclassified       85
                                 Decline  Misclassified       41
                                 Decline      Taxonomic        2
                                Improved      Taxonomic        7
                                 Decline        Unclear       41
                                Improved        Unclear      117", header=T)

ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3   <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason

windows()
  barplot(t(Reasonstats3), beside=TRUE, ylab="number of species", 
          cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
  box(bty="l")

enter image description here

Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline and for Improved. Then I made those categories the column names. I also made the Reasons the row names. The barplot() function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot() function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot() wants for your intended output.

Get the last 4 characters of a string

Like this:

>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>>mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.

Find the maximum value in a list of tuples in Python

Use max():

 
Using itemgetter():

In [53]: lis=[(101, 153), (255, 827), (361, 961)]

In [81]: from operator import itemgetter

In [82]: max(lis,key=itemgetter(1))[0]    #faster solution
Out[82]: 361

using lambda:

In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)

In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361

timeit comparison:

In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop

In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop

What is the difference between .*? and .* regular expressions?

It is the difference between greedy and non-greedy quantifiers.

Consider the input 101000000000100.

Using 1.*1, * is greedy - it will match all the way to the end, and then backtrack until it can match 1, leaving you with 1010000000001.
.*? is non-greedy. * will match nothing, but then will try to match extra characters until it matches 1, eventually matching 101.

All quantifiers have a non-greedy mode: .*?, .+?, .{2,6}?, and even .??.

In your case, a similar pattern could be <([^>]*)> - matching anything but a greater-than sign (strictly speaking, it matches zero or more characters other than > in-between < and >).

See Quantifier Cheat Sheet.

Given a class, see if instance has method (Ruby)

Actually this doesn't work for both Objects and Classes.

This does:

class TestClass
  def methodName
  end
end

So with the given answer, this works:

TestClass.method_defined? :methodName # => TRUE

But this does NOT work:

t = TestClass.new
t.method_defined? : methodName  # => ERROR!

So I use this for both classes and objects:

Classes:

TestClass.methods.include? 'methodName'  # => TRUE

Objects:

t = TestClass.new
t.methods.include? 'methodName'  # => TRUE

Calling a parent window function from an iframe

<a onclick="parent.abc();" href="#" >Call Me </a>

See window.parent

Returns a reference to the parent of the current window or subframe.

If a window does not have a parent, its parent property is a reference to itself.

When a window is loaded in an <iframe>, <object>, or <frame>, its parent is the window with the element embedding the window.

dropzone.js - how to do something after ALL files are uploaded

The accepted answer is not necessarily correct. queuecomplete will be called even when the selected file is larger than the max file size.

The proper event to use is successmultiple or completemultiple.

Reference: http://www.dropzonejs.com/#event-successmultiple

Conversion between UTF-8 ArrayBuffer and String

This should work:

// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

/* utf.js - UTF-8 <=> UTF-16 convertion
 *
 * Copyright (C) 1999 Masanao Izumo <[email protected]>
 * Version: 1.0
 * LastModified: Dec 25 1999
 * This library is free.  You can redistribute it and/or modify it.
 */

function Utf8ArrayToStr(array) {
  var out, i, len, c;
  var char2, char3;

  out = "";
  len = array.length;
  i = 0;
  while (i < len) {
    c = array[i++];
    switch (c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                                   ((char2 & 0x3F) << 6) |
                                   ((char3 & 0x3F) << 0));
        break;
    }
  }    
  return out;
}

It's somewhat cleaner as the other solutions because it doesn't use any hacks nor depends on Browser JS functions, e.g. works also in other JS environments.

Check out the JSFiddle demo.

Also see the related questions: here, here

Primary key or Unique index?

There is no such thing as a primary key in relational data theory, so your question has to be answered on the practical level.

Unique indexes are not part of the SQL standard. The particular implementation of a DBMS will determine what are the consequences of declaring a unique index.

In Oracle, declaring a primary key will result in a unique index being created on your behalf, so the question is almost moot. I can't tell you about other DBMS products.

I favor declaring a primary key. This has the effect of forbidding NULLs in the key column(s) as well as forbidding duplicates. I also favor declaring REFERENCES constraints to enforce entity integrity. In many cases, declaring an index on the coulmn(s) of a foreign key will speed up joins. This kind of index should in general not be unique.

MySQL join with where clause

Try this

  SELECT *
    FROM categories
    LEFT JOIN user_category_subscriptions 
         ON user_category_subscriptions.category_id = categories.category_id 
   WHERE user_category_subscriptions.user_id = 1 
          or user_category_subscriptions.user_id is null

'Framework not found' in Xcode

delete all frameworks from Embedded Binaries and re-add it

Android Service Stops When App Is Closed

<service android:name=".Service2"
            android:process="@string/app_name"
            android:exported="true"
            android:isolatedProcess="true"
            />

Declare this in your manifest. Give a custom name to your process and make that process isolated and exported .

Composer require runs out of memory. PHP Fatal error: Allowed memory size of 1610612736 bytes exhausted

In my case I was trying to require this package, and I was getting the PHP Fatal error: Allowed memory size of.

I found it easy to run like this and you don't have to update the PHP INI file.

example: COMPOSER_MEMORY_LIMIT=-1 composer require huddledigital/zendesk-laravel

Hope this help someone.

How can I include css files using node, express, and ejs?

Use this in your server.js file

app.use(express.static(__dirname + '/public'));

and add css like

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

dont need / before css like

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

How to increase heap size of an android application?

You can use android:largeHeap="true" to request a larger heap size, but this will not work on any pre Honeycomb devices. On pre 2.3 devices, you can use the VMRuntime class, but this will not work on Gingerbread and above.

The only way to have as large a limit as possible is to do memory intensive tasks via the NDK, as the NDK does not impose memory limits like the SDK.

Alternatively, you could only load the part of the model that is currently in view, and load the rest as you need it, while removing the unused parts from memory. However, this may not be possible, depending on your app.

MySQL - sum column value(s) based on row from the same table

SUM CASE using example:

    SELECT 
  DISTINCT(p.`ProductID`) AS ProductID,
  SUM(IF(p.`PaymentMethod`='Cash',Amount,0)) AS Cash_,
  SUM(IF(p.`PaymentMethod`='Check',Amount,0)) AS Check_,
  SUM(IF(p.`PaymentMethod`='Credit Card',Amount,0)) AS Credit_Card_,
  SUM( CASE PaymentMethod 
      WHEN 'Cash' THEN Amount
      WHEN 'Check' THEN Amount
      WHEN 'Credit Card' THEN Amount
     END) AS Total
FROM
  `payments` AS p 
GROUP BY p.`ProductID`;

SQL FIDDLE: http://www.sqlfiddle.com/#!9/23d07d/18

Result and Table view

What is move semantics?

You know what a copy semantics means right? it means you have types which are copyable, for user-defined types you define this either buy explicitly writing a copy constructor & assignment operator or the compiler generates them implicitly. This will do a copy.

Move semantics is basically a user-defined type with constructor that takes an r-value reference (new type of reference using && (yes two ampersands)) which is non-const, this is called a move constructor, same goes for assignment operator. So what does a move constructor do, well instead of copying memory from it's source argument it 'moves' memory from the source to the destination.

When would you want to do that? well std::vector is an example, say you created a temporary std::vector and you return it from a function say:

std::vector<foo> get_foos();

You're going to have overhead from the copy constructor when the function returns, if (and it will in C++0x) std::vector has a move constructor instead of copying it can just set it's pointers and 'move' dynamically allocated memory to the new instance. It's kind of like transfer-of-ownership semantics with std::auto_ptr.

Getting Raw XML From SOAPMessage in Java

If you need formatting the xml string to xml, try this:

String xmlStr = "your-xml-string";
Source xmlInput = new StreamSource(new StringReader(xmlStr));
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput,
        new StreamResult(new FileOutputStream("response.xml")));

Converting XML to JSON using Python?

To anyone that may still need this. Here's a newer, simple code to do this conversion.

from xml.etree import ElementTree as ET

xml    = ET.parse('FILE_NAME.xml')
parsed = parseXmlToJson(xml)


def parseXmlToJson(xml):
  response = {}

  for child in list(xml):
    if len(list(child)) > 0:
      response[child.tag] = parseXmlToJson(child)
    else:
      response[child.tag] = child.text or ''

    # one-liner equivalent
    # response[child.tag] = parseXmlToJson(child) if len(list(child)) > 0 else child.text or ''

  return response

Can I set a TTL for @Cacheable

Spring 3.1 and Guava 1.13.1:

@EnableCaching
@Configuration
public class CacheConfiguration implements CachingConfigurer {

    @Override
    public CacheManager cacheManager() {
        ConcurrentMapCacheManager cacheManager = new ConcurrentMapCacheManager() {

            @Override
            protected Cache createConcurrentMapCache(final String name) {
                return new ConcurrentMapCache(name,
                    CacheBuilder.newBuilder().expireAfterWrite(30, TimeUnit.MINUTES).maximumSize(100).build().asMap(), false);
            }
        };

        return cacheManager;
    }

    @Override
    public KeyGenerator keyGenerator() {
        return new DefaultKeyGenerator();
    }

}

Changing the Git remote 'push to' default

Another technique I just found for solving this (even if I deleted origin first, what appears to be a mistake) is manipulating git config directly:

git config remote.origin.url url-to-my-other-remote

BeautifulSoup: extract text from anchor tag

I would suggest going the lxml route and using xpath.

from lxml import etree
# data is the variable containing the html
data = etree.HTML(data)
anchor = data.xpath('//a[@class="title"]/text()')

Bootstrap modal - close modal when "call to action" button is clicked

Make as shown.

_x000D_
_x000D_
  $(document).ready(function(){_x000D_
    $('#myModal').modal('show');_x000D_
_x000D_
    $('#myBtn').on('click', function(){_x000D_
      $('#myModal').modal('show');_x000D_
    });_x000D_
    _x000D_
  });_x000D_
<br/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <title>Bootstrap Example</title>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container">_x000D_
  <h2>Activate Modal with JavaScript</h2>_x000D_
  <!-- Trigger the modal with a button -->_x000D_
  <button type="button" class="btn btn-info btn-lg" id="myBtn">Open Modal</button>_x000D_
_x000D_
  <!-- Modal -->_x000D_
  <div class="modal fade" id="myModal" role="dialog">_x000D_
    <div class="modal-dialog">_x000D_
    _x000D_
      <!-- Modal content-->_x000D_
      <div class="modal-content">_x000D_
        <div class="modal-header">_x000D_
          <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
          <h4 class="modal-title">Modal Header</h4>_x000D_
        </div>_x000D_
        <div class="modal-body">_x000D_
          <p>Some text in the modal.</p>_x000D_
        </div>_x000D_
_x000D_
      </div>_x000D_
      _x000D_
    </div>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

node.js http 'get' request with query string parameters

No need for a 3rd party library. Use the nodejs url module to build a URL with query parameters:

const requestUrl = url.parse(url.format({
    protocol: 'https',
    hostname: 'yoursite.com',
    pathname: '/the/path',
    query: {
        key: value
    }
}));

Then make the request with the formatted url. requestUrl.path will include the query parameters.

const req = https.get({
    hostname: requestUrl.hostname,
    path: requestUrl.path,
}, (res) => {
   // ...
})

How to print out the method name and line number and conditionally disable NSLog?

It's easy to change your existing NSLogs to display line number and class from which they are called. Add one line of code to your prefix file:

#define NSLog(__FORMAT__, ...) NSLog((@"%s [Line %d] " __FORMAT__), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)

How can I search Git branches for a file or directory?

You could use gitk --all and search for commits "touching paths" and the pathname you are interested in.

getting error while updating Composer

for php7 you can do that:

sudo apt-get install php-gd php-xml php7.0-mbstring

Center Align on a Absolutely Positioned Div

Yes:

div#thing { text-align:center; }

How do I iterate over a range of numbers defined by variables in Bash?

I know this question is about bash, but - just for the record - ksh93 is smarter and implements it as expected:

$ ksh -c 'i=5; for x in {1..$i}; do echo "$x"; done'
1
2
3
4
5
$ ksh -c 'echo $KSH_VERSION'
Version JM 93u+ 2012-02-29

$ bash -c 'i=5; for x in {1..$i}; do echo "$x"; done'
{1..5}

Save PHP variables to a text file

Personally, I'd use file_put_contents and file_get_contents (these are wrappers for fopen, fputs, etc).

Also, if you are going to write any structured data, such as arrays, I suggest you serialize and unserialize the files contents.

$file = '/tmp/file';
$content = serialize($my_variable);
file_put_contents($file, $content);
$content = unserialize(file_get_contents($file));

Permanently Set Postgresql Schema Path

(And if you have no admin access to the server)

ALTER ROLE <your_login_role> SET search_path TO a,b,c;

Two important things to know about:

  1. When a schema name is not simple, it needs to be wrapped in double quotes.
  2. The order in which you set default schemas a, b, c matters, as it is also the order in which the schemas will be looked up for tables. So if you have the same table name in more than one schema among the defaults, there will be no ambiguity, the server will always use the table from the first schema you specified for your search_path.

Execution sequence of Group By, Having and Where clause in SQL Server?

In below Order

  1. FROM & JOIN
  2. WHERE
  3. GROUP BY
  4. HAVING
  5. SELECT
  6. ORDER BY
  7. LIMIT

How I can delete in VIM all text from current line to end of file?

:.,$d

This will delete all content from current line to end of the file. This is very useful when you're dealing with test vector generation or stripping.

How to get cumulative sum

Late answer but showing one more possibility...

Cumulative Sum generation can be more optimized with the CROSS APPLY logic.

Works better than the INNER JOIN & OVER Clause when analyzed the actual query plan ...

/* Create table & populate data */
IF OBJECT_ID('tempdb..#TMP') IS NOT NULL
DROP TABLE #TMP 

SELECT * INTO #TMP 
FROM (
SELECT 1 AS id
UNION 
SELECT 2 AS id
UNION 
SELECT 3 AS id
UNION 
SELECT 4 AS id
UNION 
SELECT 5 AS id
) Tab


/* Using CROSS APPLY 
Query cost relative to the batch 17%
*/    
SELECT   T1.id, 
         T2.CumSum 
FROM     #TMP T1 
         CROSS APPLY ( 
         SELECT   SUM(T2.id) AS CumSum 
         FROM     #TMP T2 
         WHERE    T1.id >= T2.id
         ) T2

/* Using INNER JOIN 
Query cost relative to the batch 46%
*/
SELECT   T1.id, 
         SUM(T2.id) CumSum
FROM     #TMP T1
         INNER JOIN #TMP T2
                 ON T1.id > = T2.id
GROUP BY T1.id

/* Using OVER clause
Query cost relative to the batch 37%
*/
SELECT   T1.id, 
         SUM(T1.id) OVER( PARTITION BY id)
FROM     #TMP T1

Output:-
  id       CumSum
-------   ------- 
   1         1
   2         3
   3         6
   4         10
   5         15

Is there any difference between GROUP BY and DISTINCT

MusiGenesis' response is functionally the correct one with regard to your question as stated; the SQL Server is smart enough to realize that if you are using "Group By" and not using any aggregate functions, then what you actually mean is "Distinct" - and therefore it generates an execution plan as if you'd simply used "Distinct."

However, I think it's important to note Hank's response as well - cavalier treatment of "Group By" and "Distinct" could lead to some pernicious gotchas down the line if you're not careful. It's not entirely correct to say that this is "not a question about aggregates" because you're asking about the functional difference between two SQL query keywords, one of which is meant to be used with aggregates and one of which is not.

A hammer can work to drive in a screw sometimes, but if you've got a screwdriver handy, why bother?

(for the purposes of this analogy, Hammer : Screwdriver :: GroupBy : Distinct and screw => get list of unique values in a table column)

Change column type in pandas

pandas >= 1.0

Here's a chart that summarises some of the most important conversions in pandas.

enter image description here

Conversions to string are trivial .astype(str) and are not shown in the figure.

"Hard" versus "Soft" conversions

Note that "conversions" in this context could either refer to converting text data into their actual data type (hard conversion), or inferring more appropriate data types for data in object columns (soft conversion). To illustrate the difference, take a look at

df = pd.DataFrame({'a': ['1', '2', '3'], 'b': [4, 5, 6]}, dtype=object)
df.dtypes                                                                  

a    object
b    object
dtype: object

# Actually converts string to numeric - hard conversion
df.apply(pd.to_numeric).dtypes                                             

a    int64
b    int64
dtype: object

# Infers better data types for object data - soft conversion
df.infer_objects().dtypes                                                  

a    object  # no change
b     int64
dtype: object

# Same as infer_objects, but converts to equivalent ExtensionType
df.convert_dtypes().dtypes                                                     

Failed to load resource: the server responded with a status of 404 (Not Found)

Add this to your Configuration file. Then put all your resources(eg. img,css,js etc) into the src > main > webapp > resources directory.

public class Config extends WebMvcConfigurerAdapter{
   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {  
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
   }
}

After this, you can access your resources like this.

<link href="${pageContext.request.contextPath}/resources/assets/css/demo.css" rel="stylesheet" />

List<Object> and List<?>

To answer your second question, yes, you can cast the List<?> as a List<Object> or a List<T> of any type, since the ? (Wildcard) parameter indicates that the list contains a homogenous collection of an any Object. However, there's no way to know at compile what the type is since it's part of the exported API only - meaning you can't see what's being inserted into the List<?>.

Here's how you would make the cast:

List<?> wildcardList = methodThatReturnsWildcardList();
// generates Unchecked cast compiler warning
List<Object> objectReference = (List<Object>)wildcardList;

In this case you can ignore the warning because in order for an object to be used in a generic class it must be a subtype of Object. Let's pretend that we're trying to cast this as a List<Integer> when it actually contains a collection of Strings.

// this code will compile safely
List<?> wildcardList = methodThatReturnsWildcardList();
List<Integer> integerReference = (List<Integer>)wildcardList;

// this line will throw an invalid cast exception for any type other than Integer
Integer myInteger = integerRefence.get(0);

Remember: generic types are erased at runtime. You won't know what the collection contains, but you can get an element and call .getClass() on it to determine its type.

Class objectClass = wildcardList.get(0).getClass();

Splitting a Java String by the pipe symbol using split("|")

You need

test.split("\\|");

split uses regular expression and in regex | is a metacharacter representing the OR operator. You need to escape that character using \ (written in String as "\\" since \ is also a metacharacter in String literals and require another \ to escape it).

You can also use

test.split(Pattern.quote("|"));

and let Pattern.quote create the escaped version of the regex representing |.

How to specify the default error page in web.xml?

You can also do something like that:

<error-page>
    <error-code>403</error-code>
    <location>/403.html</location>
</error-page>

<error-page>
    <location>/error.html</location>
</error-page>

For error code 403 it will return the page 403.html, and for any other error code it will return the page error.html.

Android eclipse DDMS - Can't access data/data/ on phone to pull files

To set permission on the data folder and all it's subfolders and files:
Open command prompt from the ADB folder:

>> adb shell
>> su
>> find /data -type d -exec chmod 777 {} \;

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

This is an old question, but one that is frequently visited and clear recommendations are now available from RFC 7303 which obsoletes RFC3023. In a nutshell (section 9.2):

The registration information for text/xml is in all respects the same
as that given for application/xml above (Section 9.1), except that
the "Type name" is "text".

Read values into a shell variable from a pipe

if you want to read in lots of data and work on each line separately you could use something like this:

cat myFile | while read x ; do echo $x ; done

if you want to split the lines up into multiple words you can use multiple variables in place of x like this:

cat myFile | while read x y ; do echo $y $x ; done

alternatively:

while read x y ; do echo $y $x ; done < myFile

But as soon as you start to want to do anything really clever with this sort of thing you're better going for some scripting language like perl where you could try something like this:

perl -ane 'print "$F[0]\n"' < myFile

There's a fairly steep learning curve with perl (or I guess any of these languages) but you'll find it a lot easier in the long run if you want to do anything but the simplest of scripts. I'd recommend the Perl Cookbook and, of course, The Perl Programming Language by Larry Wall et al.

Replace missing values with column mean

There is also quick solution using the imputeTS package:

library(imputeTS)
na_mean(yourDataFrame)

SOAP Action WSDL

I have solved this problem, in Java Code, adding:

 MimeHeaders headers = message.getMimeHeaders();
 headers.addHeader("SOAPAction", endpointURL);

Daemon not running. Starting it now on port 5037

This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.

How to change already compiled .class file without decompile?

You can change the code when you decompiled it, but it has to be recompiled to a class file, the decompiler outputs java code, this has to be recompiled with the same classpath as the original jar/class file

How do you rename a Git tag?

This answer solves the problem by creating a duplicate annotated tag — including all tag info such as tagger, message, and tag date — by using the tag info from the existing tag.

SOURCE_TAG=old NEW_TAG=new; deref() { git for-each-ref \
"refs/tags/$SOURCE_TAG" --format="%($1)" ; }; \
GIT_COMMITTER_NAME="$(deref taggername)" \
GIT_COMMITTER_EMAIL="$(deref taggeremail)" \
GIT_COMMITTER_DATE="$(deref taggerdate)" git tag "$NEW_TAG" \
"$(deref "*objectname")" -a -m "$(deref contents)"

git tag -d old

git push origin new :old

Update the SOURCE_TAG and NEW_TAG values to match your old and new tag names.

Motivation

From what I can tell, all the other answers have subtle gotchas, or don't fully duplicate everything about the tag (e.g. they use a new tag date, or the current user's info as the tagger). Many of them call out the re-tagging warning, despite that not applying to this scenario (it's for moving a tag name to a different commit, not for renaming to a differently named tag). I've done some digging, and I believe I've pieced together a solution that addresses these concerns.

Goal

The git-tag documentation specifies the parts of an annotated tag. To truly be an indistinguishable rename, these elements should be the same in the new tag.

Tag objects (created with -a, -s, or -u) are called "annotated" tags; they contain a creation date, the tagger name and e-mail, a tagging message, and an optional GnuPG signature.

I'm only addressing unsigned tags in this answer, though it should be a simple matter to extend this solution to signed tags.

Procedure

An annotated tag named old is used in the example, and will be renamed to new.

Step 1: Get existing tag information

First, we need to get the information for the existing tag. This can be achieved using for-each-ref:

Command:

git for-each-ref refs/tags --format="\
Tag name: %(refname:short)
Tag commit: %(objectname:short)
Tagger date: %(taggerdate)
Tagger name: %(taggername)
Tagger email: %(taggeremail)
Tagged commit: %(*objectname:short)
Tag message: %(contents)"

Output:

Tag commit: 88a6169
Tagger date: Mon Dec 14 12:44:52 2020 -0600
Tagger name: John Doe
Tagger email: <[email protected]>
Tagged commit: cda5b4d
Tag name: old
Tag message: Initial tag

Body line 1.
Body line 2.
Body line 3.

Step 2: Create a duplicate tag locally

A duplicate tag with the new name can be created using the info gathered in step 1 from the existing tag.

The commit ID & commit message can be passed directly to git tag.

The tagger information (name, email, and date) can be set using the git environment variables GIT_COMMITTER_NAME, GIT_COMMITTER_EMAIL, GIT_COMMITTER_DATE. The date usage in this context is described in the On Backdating Tags documentation for git tag; the other two I figured out through experimentation.

GIT_COMMITTER_NAME="John Doe" GIT_COMMITTER_EMAIL="[email protected]" \
GIT_COMMITTER_DATE="Mon Dec 14 12:44:52 2020 -0600" git tag new cda5b4d -a -m "Initial tag

Body line 1.
Body line 2.
Body line 3."

A side-by-side comparison of the two tags shows they're identical in all the ways that matter. The only thing that's differing here is the commit reference of the tag itself, which is expected since they're two different tags.

Command:

git for-each-ref refs/tags --format="\
Tag commit: %(objectname:short)
Tagger date: %(taggerdate)
Tagger name: %(taggername)
Tagger email: %(taggeremail)
Tagged commit: %(*objectname:short)
Tag name: %(refname:short)
Tag message: %(contents)"

Output:

Tag commit: 580f817
Tagger date: Mon Dec 14 12:44:52 2020 -0600
Tagger name: John Doe
Tagger email: <[email protected]>
Tagged commit: cda5b4d
Tag name: new
Tag message: Initial tag

Body line 1.
Body line 2.
Body line 3.

Tag commit: 30ddd25
Tagger date: Mon Dec 14 12:44:52 2020 -0600
Tagger name: John Doe
Tagger email: <[email protected]>
Tagged commit: cda5b4d
Tag name: old
Tag message: Initial tag

Body line 1.
Body line 2.
Body line 3.

As a single command, including retrieving the current tag data:

SOURCE_TAG=old NEW_TAG=new; deref() { git for-each-ref "refs/tags/$SOURCE_TAG" --format="%($1)" ; }; GIT_COMMITTER_NAME="$(deref taggername)" GIT_COMMITTER_EMAIL="$(deref taggeremail)" GIT_COMMITTER_DATE="$(deref taggerdate)" git tag "$NEW_TAG" "$(deref "*objectname")" -a -m "$(deref contents)"

Step 3: Delete the existing tag locally

Next, the existing tag should be deleted locally. This step can be skipped if you wish to keep the old tag along with the new one (i.e. duplicate the tag rather than rename it).

git tag -d old

Step 4: Push changes to remote repository

Assuming you're working from a remote repository, the changes can now be pushed using git push:

git push origin new :old

This pushes the new tag, and deletes the old tag.

What does the "no version information available" error from linux dynamic linker mean?

How are you compiling your app? What compiler flags?

In my experience, when targeting the vast realm of Linux systems out there, build your packages on the oldest version you are willing to support, and because more systems tend to be backwards compatible, your app will continue to work. Actually this is the whole reason for library versioning - ensuring backward compatibility.

specifying goal in pom.xml

I ran into this when trying to run spring boot from the command line...

mvn spring-boot:run

I accidentally mis-typed the command as...

mvn spring-boot run

So it was looking for the commands... run, build etc...

Carousel with Thumbnails in Bootstrap 3.0

Bootstrap 4 (update 2019)

A multi-item carousel can be accomplished in several ways as explained here. Another option is to use separate thumbnails to navigate the carousel slides.

Bootstrap 3 (original answer)

This can be done using the grid inside each carousel item.

       <div id="myCarousel" class="carousel slide">
                <div class="carousel-inner">
                    <div class="item active">
                        <div class="row">
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                            <div class="col-sm-3">..
                            </div>
                        </div>
                        <!--/row-->
                    </div>
                    ...add more item(s)
                 </div>
        </div>

Demo example thumbnail slider using the carousel:
http://www.bootply.com/81478

Another example with carousel indicators as thumbnails: http://www.bootply.com/79859

Ajax passing data to php script

You can also use bellow code for pass data using ajax.

var dataString = "album" + title;
$.ajax({  
    type: 'POST',  
    url: 'test.php', 
    data: dataString,
    success: function(response) {
        content.html(response);
    }
});

Eclipse Java Missing required source folder: 'src'

Eclipse wouldn't let me point to an existing (or add a new) source directory. Eclipse's configuration files can be wonky. In my case I should have started simple. Right click the project and click Refresh.

Correct way to use Modernizr to detect IE?

I needed to detect IE vs most everything else and I didn't want to depend on the UA string. I found that using es6number with Modernizr did exactly what I wanted. I don't have much concern with this changing as I don't expect IE to ever support ES6 Number. So now I know the difference between any version of IE vs Edge/Chrome/Firefox/Opera/Safari.

More details here: http://caniuse.com/#feat=es6-number

Note that I'm not really concerned about Opera Mini false negatives. You might be.

500 Internal Server Error for php file not for html

It was changing the line endings (from Windows CRLF to Unix LF) in the .htaccess file that fixed it for me.

Get current time in hours and minutes

date +%H:%M

Would be easier, I think :). If you really wanted to chop off the seconds, you could have done

date | sed 's/.* \([0-9]*:[0-9]*\):[0-9]*.*/\1/'

How to swap String characters in Java?

StringBuilder sb = new StringBuilder("abcde");
sb.setCharAt(0, 'b');
sb.setCharAt(1, 'a');
String newString = sb.toString();

Why use a READ UNCOMMITTED isolation level?

It can be used for a simple table, for example in an insert-only audit table, where there is no update to existing row, and no fk to other table. The insert is a simple insert, which has no or little chance of rollback.

UNC path to a folder on my local computer

If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:

\\localhost\c$\my_dir

... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.

Copy multiple files in Python

def recursive_copy_files(source_path, destination_path, override=False):
    """
    Recursive copies files from source  to destination directory.
    :param source_path: source directory
    :param destination_path: destination directory
    :param override if True all files will be overridden otherwise skip if file exist
    :return: count of copied files
    """
    files_count = 0
    if not os.path.exists(destination_path):
        os.mkdir(destination_path)
    items = glob.glob(source_path + '/*')
    for item in items:
        if os.path.isdir(item):
            path = os.path.join(destination_path, item.split('/')[-1])
            files_count += recursive_copy_files(source_path=item, destination_path=path, override=override)
        else:
            file = os.path.join(destination_path, item.split('/')[-1])
            if not os.path.exists(file) or override:
                shutil.copyfile(item, file)
                files_count += 1
    return files_count

jQuery UI Sortable Position

You can use the ui object provided to the events, specifically you want the stop event, the ui.item property and .index(), like this:

$("#sortable").sortable({
    stop: function(event, ui) {
        alert("New position: " + ui.item.index());
    }
});

You can see a working demo here, remember the .index() value is zero-based, so you may want to +1 for display purposes.

Clone Object without reference javascript

A and B reference the same object, so A.a and B.a reference the same property of the same object.

Edit

Here's a "copy" function that may do the job, it can do both shallow and deep clones. Note the caveats. It copies all enumerable properties of an object (not inherited properties), including those with falsey values (I don't understand why other approaches ignore them), it also doesn't copy non–existent properties of sparse arrays.

There is no general copy or clone function because there are many different ideas on what a copy or clone should do in every case. Most rule out host objects, or anything other than Objects or Arrays. This one also copies primitives. What should happen with functions?

So have a look at the following, it's a slightly different approach to others.

/* Only works for native objects, host objects are not
** included. Copies Objects, Arrays, Functions and primitives.
** Any other type of object (Number, String, etc.) will likely give 
** unexpected results, e.g. copy(new Number(5)) ==> 0 since the value
** is stored in a non-enumerable property.
**
** Expects that objects have a properly set *constructor* property.
*/
function copy(source, deep) {
   var o, prop, type;

  if (typeof source != 'object' || source === null) {
    // What do to with functions, throw an error?
    o = source;
    return o;
  }

  o = new source.constructor();

  for (prop in source) {

    if (source.hasOwnProperty(prop)) {
      type = typeof source[prop];

      if (deep && type == 'object' && source[prop] !== null) {
        o[prop] = copy(source[prop]);

      } else {
        o[prop] = source[prop];
      }
    }
  }
  return o;
}

PHP replacing special characters like à->a, è->e

CodeIgniter way:

$this->load->helper('text');

$string = convert_accented_characters($string);

This function uses a companion config file application/config/foreign_chars.php to define the to and from array for transliteration.

https://www.codeigniter.com/user_guide/helpers/text_helper.html#ascii_to_entities

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

To Select all

 $('select[name=eventsFilter]').find('option').attr('selected', true);
$('select[name=eventsFilter]').select2();

To UnSellect all

$('select[name=eventsFilter]').find('option').attr('selected', false);
  $('select[name=eventsFilter]').select2("");

Saving response from Requests to file

As Peter already pointed out:

In [1]: import requests

In [2]: r = requests.get('https://api.github.com/events')

In [3]: type(r)
Out[3]: requests.models.Response

In [4]: type(r.content)
Out[4]: str

You may also want to check r.text.

Also: https://2.python-requests.org/en/latest/user/quickstart/

Max parallel http connections in a browser?

 BrowserVersion | ConnectionsPerHostname | MaxConnections
----------------------------------------------------------
 Chrome34/32    | 6                      | 10
 IE9            | 6                      | 35
 IE10           | 8                      | 17
 IE11           | 13                     | 17
 Firefox27/26   | 6                      | 17
 Safari7.0.1    | 6                      | 17
 Android4       | 6                      | 17
 ChromeMobile18 | 6                      | 16
 IE Mobile9     | 6                      | 60

The first value is ConnectionsPerHostname and the second value is MaxConnections.

Source: http://www.browserscope.org/?category=network&v=top

Note: ConnectionsPerHostname is the maximum number of concurrent http requests that browsers will make to the same domain. To increase the number of concurrent connections, one can host resources (e.g. images) in different domains. However, you cannot exceed MaxConnections, the maximum number of connections a browser will open in total - across all domains.

2020 Update

Number of parallel connections per browser

| Browser              | Connections per Domain         | Max Connections                |
| -------------------- | ------------------------------ | ------------------------------ |
| Chrome 81            | 6 [^note1]                     | 256[^note2]                    |
| Edge 18              | *same as Internet Explorer 11* | *same as Internet Explorer 11* |
| Firefox 68           | 9 [^note1] or 6 [^note3]       | 1000+[^note2]                  |
| Internet Explorer 11 | 12 [^note4]                    | 1000+[^note2]                  |
| Safari 13            | 6 [^note1]                     | 1000+[^note2]                  |
  • [^note1]: tested with 72 requests , 1 domain(127.0.0.1)
  • [^note2]: tested with 1002 requests, 6 requests per domain * 167 domains (127.0.0.*)
  • [^note3]: when called in async context, e.g. in callback of setTimeout, + requestAnimationFrame, then...
  • [^note4]: of which the last 6 are follow-ups (2,4,6 available at 0.5s,1s,1.5s respectively)

How do I open workbook programmatically as read-only?

Check out the language reference:

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

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

Differences between Emacs and Vim

VI is always available and will run on the most crippled, single user mode, broken graphics, no keymap, slow link machine - so it's worth knowing how to edit simple files in it just for sysadmin tasks.

Emacs is a complete user interface in an editor. The idea is that you fire up Emacs when you start the machine and never leave it. It's possible to have thousands of sessions present.

Whether learning the capabilities of Emacs are worth it compared to using a GUI editor/IDE and using something like python/awk/etc for extra tasks is up to you.

How to add a linked source folder in Android Studio?

While sourceSets allows you to include entire directory structures, there's no way to exclude parts of it in Android Studio (as of version 1.2), as described here: Android Studio Exclude Class from build?

Until Android Studio gets updated to support include/exclude directives for Android sources, Symlinks work quite well. If you're using Windows, native tools such as junction or mklink can accomplish the equivalent of Un*x symlinks. CygWin can also create these with a little coersion. See: Git Symlinks in Windows and How to make symbolic link with cygwin in Windows 7

jQuery 1.9 .live() is not a function

jQuery .live() has been removed in version 1.9 onwards.

That means if you are upgrading from version 1.8 and earlier, you will notice things breaking if you do not follow the migration guide below. You must not simply replace .live() with .on()!


Read before you start doing a search and replace:

For quick/hot fixes on a live site, do not just replace the keyword live with on,
as the parameters are different!

.live(events, function)

should map to:

.on(eventType, selector, function)

The (child) selector is very important! If you do not need to use this for any reason, set it to null.


Migration Example 1:

before:

$('#mainmenu a').live('click', function)

after, you move the child element (a) to the .on() selector:

$('#mainmenu').on('click', 'a', function)

Migration Example 2:

before:

$('.myButton').live('click', function)

after, you move the element (.myButton) to the .on() selector, and find the nearest parent element (preferably with an ID):

$('#parentElement').on('click', '.myButton', function)

If you do not know what to put as the parent, body always works:

$('body').on('click', '.myButton', function)

See also:

Convert IEnumerable to DataTable

There is nothing built in afaik, but building it yourself should be easy. I would do as you suggest and use reflection to obtain the properties and use them to create the columns of the table. Then I would step through each item in the IEnumerable and create a row for each. The only caveat is if your collection contains items of several types (say Person and Animal) then they may not have the same properties. But if you need to check for it depends on your use.

How to create an empty file with Ansible?

Changed if file not exists. Create empty file.

- name: create fake 'nologin' shell
  file:
    path: /etc/nologin
    state: touch
  register: p
  changed_when: p.diff.before.state == "absent"

jQuery click function doesn't work after ajax call?

Here's the FIDDLE

Same code as yours but it will work on dynamically created elements.

$(document).on('click', '.deletelanguage', function () {
    alert("success");
    $('#LangTable').append(' <br>------------<br> <a class="deletelanguage">Now my class is deletelanguage. click me to test it is not working.</a>');
});

How can I get the MAC and the IP address of a connected client in PHP?

// Turn on output buffering  
ob_start();  

//Get the ipconfig details using system commond  
system('ipconfig /all');  

// Capture the output into a variable  
$mycomsys=ob_get_contents();  

// Clean (erase) the output buffer  
ob_clean();  

$find_mac = "Physical"; 
//find the "Physical" & Find the position of Physical text  

$pmac = strpos($mycomsys, $find_mac);  
// Get Physical Address  

$macaddress=substr($mycomsys,($pmac+36),17);  
//Display Mac Address  

echo $macaddress;  

This works for me on Windows, as ipconfig /all is Windows system command.

Is it possible to get an Excel document's row count without loading the entire document into memory?

The solution suggested in this answer has been deprecated, and might no longer work.


Taking a look at the source code of OpenPyXL (IterableWorksheet) I've figured out how to get the column and row count from an iterator worksheet:

wb = load_workbook(path, use_iterators=True)
sheet = wb.worksheets[0]

row_count = sheet.get_highest_row() - 1
column_count = letter_to_index(sheet.get_highest_column()) + 1

IterableWorksheet.get_highest_column returns a string with the column letter that you can see in Excel, e.g. "A", "B", "C" etc. Therefore I've also written a function to translate the column letter to a zero based index:

def letter_to_index(letter):
    """Converts a column letter, e.g. "A", "B", "AA", "BC" etc. to a zero based
    column index.

    A becomes 0, B becomes 1, Z becomes 25, AA becomes 26 etc.

    Args:
        letter (str): The column index letter.
    Returns:
        The column index as an integer.
    """
    letter = letter.upper()
    result = 0

    for index, char in enumerate(reversed(letter)):
        # Get the ASCII number of the letter and subtract 64 so that A
        # corresponds to 1.
        num = ord(char) - 64

        # Multiply the number with 26 to the power of `index` to get the correct
        # value of the letter based on it's index in the string.
        final_num = (26 ** index) * num

        result += final_num

    # Subtract 1 from the result to make it zero-based before returning.
    return result - 1

I still haven't figured out how to get the column sizes though, so I've decided to use a fixed-width font and automatically scaled columns in my application.

Oracle SQL Developer - tables cannot be seen

3.1 didn't matter for me.

It took me a while, but I managed to find the 2.1 release to try that out here: http://www.oracle.com/technetwork/testcontent/index21-ea1-095147.html

1.2 http://www.oracle.com/technetwork/testcontent/index-archive12-101280.html

That doesn't work either though, still no tables so it looks like something with permission.

Checking if a variable exists in javascript

I'm writing an answer only because I do not have enough reputations to comment the accepted answer from apsillers. I agree with his answer, but

If you really want to test if a variable is undeclared, you'll need to catch the ReferenceError ...

is not the only way. One can do just:

this.hasOwnProperty("bar")

to check if there is a variable bar declared in the current context. (I'm not sure, but calling the hasOwnProperty could also be more fast/effective than raising an exception) This works only for the current context (not for the whole current scope).

Getting the parameters of a running JVM

This technique applies for any java application running local or remote.

  1. Start your java application.
  2. Run JVisualVM found in you JDK (such as C:\Program Files\Java\jdk1.8.0_05\bin\jvisualvm.exe).
  3. When this useful tool starts look at the list of running java application under the "Local" tree node.
  4. Double click [your application] (pid [n]).
  5. On the right side there will be inspection contents in tab for the application. In the middle of the Overview tab you will see the JVM arguments for the application.

jvisualvm can be found in any JDK since JDK 6 Update 7. Video tutorial on jvisualvm is here.

Regex to replace everything except numbers and a decimal point

Use this:

document.getElementById(target).value = newVal.replace(/[^0-9.]/g, '');

CSS: how to position element in lower right?

Lets say your HTML looks something like this:

<div class="box">
    <!-- stuff -->
    <p class="bet_time">Bet 5 days ago</p>
</div>

Then, with CSS, you can make that text appear in the bottom right like so:

.box {
    position:relative;
}
.bet_time {
    position:absolute;
    bottom:0;
    right:0;
}

The way this works is that absolutely positioned elements are always positioned with respect to the first relatively positioned parent element, or the window. Because we set the box's position to relative, .bet_time positions its right edge to the right edge of .box and its bottom edge to the bottom edge of .box

What does numpy.random.seed(0) do?

numpy.random.seed(0)
numpy.random.randint(10, size=5)

This produces the following output: array([5, 0, 3, 3, 7]) Again,if we run the same code we will get the same result.

Now if we change the seed value 0 to 1 or others:

numpy.random.seed(1)
numpy.random.randint(10, size=5)

This produces the following output: array([5 8 9 5 0]) but now the output not the same like above.

How do I bind Twitter Bootstrap tooltips to dynamically created elements?

Rather than search it in full Body. One could just use dynamic title option already available in such scenarios I think:

$btn.tooltip({
  title: function(){
    return $(this).attr('title');
  }
});

Using Java to pull data from a webpage?

The simplest solution (without depending on any third-party library or platform) is to create a URL instance pointing to the web page / link you want to download, and read the content using streams.

For example:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;


public class DownloadPage {

    public static void main(String[] args) throws IOException {

        // Make a URL to the web page
        URL url = new URL("http://stackoverflow.com/questions/6159118/using-java-to-pull-data-from-a-webpage");

        // Get the input stream through URL Connection
        URLConnection con = url.openConnection();
        InputStream is =con.getInputStream();

        // Once you have the Input Stream, it's just plain old Java IO stuff.

        // For this case, since you are interested in getting plain-text web page
        // I'll use a reader and output the text content to System.out.

        // For binary content, it's better to directly read the bytes from stream and write
        // to the target file.


        BufferedReader br = new BufferedReader(new InputStreamReader(is));

        String line = null;

        // read each line and write to System.out
        while ((line = br.readLine()) != null) {
            System.out.println(line);
        }
    }
}

Hope this helps.

How can I create a product key for my C# application?

You can check LicenseSpot. It provides:

  • Free Licensing Component
  • Online Activation
  • API to integrate your app and online store
  • Serial number generation
  • Revoke licenses
  • Subscription Management

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

You just have to change the structure of the if...else..endif somewhat:

if exists(select * from Table where FieldValue='') then begin
  select TableID from Table where FieldValue=''
end else begin
  insert into Table (FieldValue) values ('')
  select TableID from Table where TableID = scope_identity()
end

You could also do:

if not exists(select * from Table where FieldValue='') then begin
  insert into Table (FieldValue) values ('')
end
select TableID from Table where FieldValue=''

Or:

if exists(select * from Table where FieldValue='') then begin
  select TableID from Table where FieldValue=''
end else begin
  insert into Table (FieldValue) values ('')
  select scope_identity() as TableID
end

Show row number in row header of a DataGridView

row.HeaderCell.Value = row.Index + 1;

when applied on datagridview with a very large number of rows creates a memory leak and eventually will result in an out of memory issue. Any ideas how to reclaim the memory?

Here is sample code to apply to an empty grid with some columns. it simply adds rows and numbers the index. Repeat button click a few times.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        dataGridView1.SuspendLayout();
        for (int i = 1; i < 10000; i++)
        {
            dataGridView1.Rows.Add(i);                
        }
        dataGridView1.ResumeLayout();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in dataGridView1.Rows)
            row.HeaderCell.Value = (row.Index + 1).ToString();
    }
}

How to use UIScrollView in Storyboard

I'm answering my own question because I just spent 2 hours to find the solution and StackOverflow allows this QA style.

Start to finish here is how to make it work in storyboard.

1: go to you view controller and click on Attribute Inspector.

2: change Size to Freeform instead of Inferred.

3: Go to the main view on that storyboard, not your scrollview but rather the top level view.

4: Click Size Inspector and set this view to your desired size. I changed my height to 1000.

Now you will see that you storyboard has your view setup so you can see the entire height of your scroll for easy design.

5: Drop on a scrollview and stretch it so it takes up the whole view. You should now have a scrollview with size of 320,1000 sitting on a view in your view controller.

Now we need to make it scroll and need to make it show content correctly.

6: Click on your scrollview and click on Identity Inspector.

7: Add a User Defined runtime attribute with KeyPath of contentSize then type of SIZE and put in your content size. For me it is (320, 1000).

Since we want to see our whole scroll view on the storyboard we stretched it and it has a frame of 320,1000 but in order for this to work in our app we need to change the frame down to what the visible scrollview will be.

8: Add a runtime attribute with KeyPath frame with Type RECT and 0,0,320,416.

Now when we run our app we will have a visible scrollview has a frame of 0,0,320, 416 and can scroll down to 1000. We are able to layout our subviews and images and whatnot in Storyboard just the way we want them to appear. Then our runtime attributes make sure to display it properly. All of this without 1 line of code.

Can I prevent text in a div block from overflowing?

Simply use this:

white-space: pre-wrap;      /* CSS3 */   
white-space: -moz-pre-wrap; /* Firefox */    
white-space: -pre-wrap;     /* Opera <7 */   
white-space: -o-pre-wrap;   /* Opera 7 */    
word-wrap: break-word;      /* IE */

Getting All Variables In Scope

How much time do you have?

If you hate your cpu you can bruteforce through every valid variable name, and eval each one to see if it results in a value!

The following snippet tries the first 1000 bruteforce strings, which is enough to find the contrived variable names in scope:

_x000D_
_x000D_
let alpha = 'abcdefghijklmnopqrstuvwxyz';
let everyPossibleString = function*() {
  yield '';
  for (let prefix of everyPossibleString()) for (let char of alpha) yield `${prefix}${char}`;
};
let allVarsInScope = (iterations=1000) => {  
  let results = {};
  let count = 0;
  for (let bruteforceString of everyPossibleString()) {
    if (!bruteforceString) continue; // Skip the first empty string
    try { results[bruteforceString] = eval(bruteforceString); } catch(err) {}
    if (count++ > iterations) break;
  }
  return results;
};

let myScope = (() => {
    
  let dd = 'ddd';
  let ee = 'eee';
  let ff = 'fff';
  
  ((gg, hh) => {
    
    // We can't call a separate function, since that function would be outside our
    // scope and wouldn't be able to see any variables - but we can define the
    // function in place (using `eval(allVarsInScope.toString())`), and then call
    // that defined-in-place function
    console.log(eval(allVarsInScope.toString())());
    
  })('ggg', 'hhh');
  
})();
_x000D_
_x000D_
_x000D_

This script will eventually (after a very long time) find all scoped variable names, as well as abc nifty and swell, some example variables I created. Note it will only find variable names consisting of alpha characters.

_x000D_
_x000D_
let preElem = document.getElementsByClassName('display')[0];
let statusElem = document.getElementsByClassName('status')[0];
let alpha = 'abcdefghijklmnopqrstuvwxyz';
alpha += alpha.toUpperCase();
let everyPossibleString = function*() {
  yield '';
  for (let prefix of everyPossibleString()) for (let char of alpha) yield `${prefix}${char}`;
};

(async () => {
  
  let abc = 'This is the ABC variable :-|';
  let neato = 'This is the NEATO variable :-)';
  let swell = 'This is the SWELL variable :-D';
  
  let results = {};
  let batch = 25000;
  let waitMs = 25;
  let count = 0;
  let startStr = null;

  for (let bruteStr of everyPossibleString()) {
    
    try {

      if (bruteStr === '') continue;
      if (startStr === null) startStr = bruteStr;

      try { results[bruteStr] = eval(bruteStr); } catch(err) {}

      if (count++ >= batch) {
        
        statusElem.innerHTML = `Did batch of ${batch} from ${startStr} -> ${bruteStr}`;
        preElem.innerHTML = JSON.stringify(results, null, 2);
        
        count = 0;
        startStr = null;
        await new Promise(r => setTimeout(r, waitMs));

      }
      
    } catch(err) {
      
      // It turns out some global variables are protected by stackoverflow's snippet
      // system (these include "top", "self", and "this"). If these values are touched
      // they result in a weird iframe error, captured in this `catch` statement. The
      // program can recover by replacing the most recent `result` value (this will be
      // the value which causes the error).
      let lastEntry = Object.entries(results).slice(-1)[0];
      results[lastEntry[0]] = '<a protected value>';
            
    }

  }
  
  console.log('Done...'); // Will literally never happen

})();
_x000D_
html, body { position: fixed; left: 0; top: 0; right: 0; bottom: 0; margin: 0; padding: 0; overflow: hidden }
.display {
  position: fixed;
  box-sizing: border-box;
  left: 0; top: 0;
  bottom: 30px; right: 0;
  overflow-y: scroll;
  white-space: pre;
  font-family: monospace;
  padding: 10px;
  box-shadow: inset 0 0 10px 1px rgba(0, 0, 0, 0.3);
}
.status {
  position: fixed;
  box-sizing: border-box;
  left: 0; bottom: 0px; right: 0; height: 30px; line-height: 30px;
  padding: 0 10px;
  background-color: rgba(0, 0, 0, 1);
  color: rgba(255, 255, 255, 1);
  font-family: monospace;
}
_x000D_
<div class="display"></div>
<div class="status"></div>
_x000D_
_x000D_
_x000D_

I am all too aware there is virtually no situation where this is practical

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Get day of week using NSDate

extension Date {

var weekdayName: String {
    let formatter = DateFormatter(); formatter.dateFormat = "E"
    return formatter.string(from: self as Date)
}

var weekdayNameFull: String {
    let formatter = DateFormatter(); formatter.dateFormat = "EEEE"
    return formatter.string(from: self as Date)
}
var monthName: String {
    let formatter = DateFormatter(); formatter.dateFormat = "MMM"
    return formatter.string(from: self as Date)
}
var OnlyYear: String {
    let formatter = DateFormatter(); formatter.dateFormat = "YYYY"
    return formatter.string(from: self as Date)
}
var period: String {
    let formatter = DateFormatter(); formatter.dateFormat = "a"
    return formatter.string(from: self as Date)
}
var timeOnly: String {
    let formatter = DateFormatter(); formatter.dateFormat = "hh : mm"
    return formatter.string(from: self as Date)
}
var timeWithPeriod: String {
    let formatter = DateFormatter(); formatter.dateFormat = "hh : mm a"
    return formatter.string(from: self as Date)
}

var DatewithMonth: String {
    let formatter = DateFormatter(); formatter.dateStyle = .medium ;        return formatter.string(from: self as Date)
}
}

usage let weekday = Date().weekdayName

What are good grep tools for Windows?

I have Cygwin installed on my machine and put the Cygwin bin directory in my environmental path, so the Cygwin grep works like normal in a command line which solves all my scripting needs for grep at the moment.

How to serialize Object to JSON?

Easy way to do it without annotations is to use Gson library

Simple as that:

Gson gson = new Gson();
String json = gson.toJson(listaDePontos);

How to trigger click on page load?

$(function(){

    $(selector).click();

});

"unadd" a file to svn before commit

Try svn revert filename for every file you don't need and haven't yet committed. Or alternatively do svn revert -R folder for the problematic folder and then re-do the operation with correct ignoring configuration.

From the documentation:

 you can undo any scheduling operations:

$ svn add mistake.txt whoops
A         mistake.txt
A         whoops
A         whoops/oopsie.c

$ svn revert mistake.txt whoops
Reverted mistake.txt
Reverted whoops

PostgreSQL delete with inner join

DELETE 
FROM m_productprice B  
     USING m_product C 
WHERE B.m_product_id = C.m_product_id AND
      C.upc = '7094' AND                 
      B.m_pricelist_version_id='1000020';

or

DELETE 
FROM m_productprice
WHERE m_pricelist_version_id='1000020' AND 
      m_product_id IN (SELECT m_product_id 
                       FROM m_product 
                       WHERE upc = '7094'); 

How to detect current state within directive

If you are using ui-router, try $state.is();

You can use it like so:

$state.is('stateName');

Per the documentation:

$state.is ... similar to $state.includes, but only checks for the full state name.

If Cell Starts with Text String... Formula

I know this is a really old post, but I found it in searching for a solution to the same problem. I don't want a nested if-statement, and Switch is apparently newer than the version of Excel I'm using. I figured out what was going wrong with my code, so I figured I'd share here in case it helps someone else.

I remembered that VLOOKUP requires the source table to be sorted alphabetically/numerically for it to work. I was initially trying to do this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"s","l","m"}, {-1,1,0})

and it started working when I did this...

=LOOKUP(LOWER(LEFT($T$3, 1)),  {"l","m","s"}, {1,0,-1})

I was initially thinking the last value might turn out to be a default, so I wanted the zero at the last place. That doesn't seem to be the behavior anyway, so I just put the possible matches in order, and it worked.

Edit: As a final note, I see that the example in the original post has letters in alphabetical order, but I imagine the real use case might have been different if the error was happening and the letters A, B, and C were just examples.

How to pattern match using regular expression in Scala?

To expand a little on Andrew's answer: The fact that regular expressions define extractors can be used to decompose the substrings matched by the regex very nicely using Scala's pattern matching, e.g.:

val Process = """([a-cA-C])([^\s]+)""".r // define first, rest is non-space
for (p <- Process findAllIn "aha bah Cah dah") p match {
  case Process("b", _) => println("first: 'a', some rest")
  case Process(_, rest) => println("some first, rest: " + rest)
  // etc.
}

Differences between cookies and sessions?

A lot contributions on this thread already, just summarize a sequence diagram to illustrate it in another way.

enter image description here

The is also a good link about this topic, https://web.stanford.edu/~ouster/cgi-bin/cs142-fall10/lecture.php?topic=cookie

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

While writing this question, I discovered the answer. Installing a CA from Safari no longer automatically trusts it. I had to manually trust it from the Certificate Trust Settings panel (also mentioned in this question).

enter image description here

I debated canceling the question, but I thought it might be helpful to have some of the relevant code and log details someone might be looking for. Also, I never encountered the issue until iOS 11. I even went back and reconfirmed that it automatically works up through iOS 10.

I've never needed to touch that settings panel before, because any installed certificates were automatically trusted. Maybe it will change by the time iOS 11 ships, but I doubt it. Hopefully this helps save someone the time I wasted.

If anyone knows why this behaves differently for some people on different versions of iOS, I'd love to know in comments.

Update 1: Checking out the first iOS 12 beta, it looks like things remain the same. This question/answer/comments are still relevant on iOS 12.

Update 2: Same solution seems to be needed on iOS 13 beta builds as well.

Getting full JS autocompletion under Sublime Text

Suggestions are (basically) based on the text in the current open file and any snippets or completions you have defined (ref). If you want more text suggestions, I'd recommend:

As a side note, I'd really recommend installing Package control to take full advantage of the Sublime community. Some of the options above use Package control. I'd also highly recommend the tutsplus Sublime tutorial videos, which include all sorts of information about improving your efficiency when using Sublime.

Python - Extracting and Saving Video Frames

This function extracts images from video with 1 fps, IN ADDITION it identifies the last frame and stops reading also:

import cv2
import numpy as np

def extract_image_one_fps(video_source_path):

    vidcap = cv2.VideoCapture(video_source_path)
    count = 0
    success = True
    while success:
      vidcap.set(cv2.CAP_PROP_POS_MSEC,(count*1000))      
      success,image = vidcap.read()

      ## Stop when last frame is identified
      image_last = cv2.imread("frame{}.png".format(count-1))
      if np.array_equal(image,image_last):
          break

      cv2.imwrite("frame%d.png" % count, image)     # save frame as PNG file
      print '{}.sec reading a new frame: {} '.format(count,success)
      count += 1

Batch program to to check if process exists

Try this:

@echo off
set run=
tasklist /fi "imagename eq notepad.exe" | find ":" > nul
if errorlevel 1 set run=yes
if "%run%"=="yes" echo notepad is running
if "%run%"=="" echo notepad is not running
pause

Nodejs convert string into UTF-8

I had the same problem, when i loaded a text file via fs.readFile(), I tried to set the encodeing to UTF8, it keeped the same. my solution now is this:

myString = JSON.parse( JSON.stringify( myString ) )

after this an Ö is realy interpreted as an Ö.

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Converting a year from 4 digit to 2 digit and back again in C#

If you're creating a DateTime object using the expiration dates (month/year), you can use ToString() on your DateTime variable like so:

DateTime expirationDate = new DateTime(2008, 1, 31); // random date
string lastTwoDigitsOfYear = expirationDate.ToString("yy");

Edit: Be careful with your dates though if you use the DateTime object during validation. If somebody selects 05/2008 as their card's expiration date, it expires at the end of May, not on the first.

how to automatically scroll down a html page?

You can use .scrollIntoView() for this. It will bring a specific element into the viewport.

Example:

document.getElementById( 'bottom' ).scrollIntoView();

Demo: http://jsfiddle.net/ThinkingStiff/DG8yR/

Script:

function top() {
    document.getElementById( 'top' ).scrollIntoView();    
};

function bottom() {
    document.getElementById( 'bottom' ).scrollIntoView();
    window.setTimeout( function () { top(); }, 2000 );
};

bottom();

HTML:

<div id="top">top</div>
<div id="bottom">bottom</div>

CSS:

#top {
    border: 1px solid black;
    height: 3000px;
}

#bottom {
    border: 1px solid red;
}

Entity Framework The underlying provider failed on Open

open SQL Server Configuration Manager then click on sql server services a list will be displayed from the list right click sql server and click on start

Parsing Query String in node.js

Starting with Node.js 11, the url.parse and other methods of the Legacy URL API were deprecated (only in the documentation, at first) in favour of the standardized WHATWG URL API. The new API does not offer parsing the query string into an object. That can be achieved using tthe querystring.parse method:

// Load modules to create an http server, parse a URL and parse a URL query.
const http = require('http');
const { URL } = require('url');
const { parse: parseQuery } = require('querystring');

// Provide the origin for relative URLs sent to Node.js requests.
const serverOrigin = 'http://localhost:8000';

// Configure our HTTP server to respond to all requests with a greeting.
const server = http.createServer((request, response) => {
  // Parse the request URL. Relative URLs require an origin explicitly.
  const url = new URL(request.url, serverOrigin);
  // Parse the URL query. The leading '?' has to be removed before this.
  const query = parseQuery(url.search.substr(1));
  response.writeHead(200, { 'Content-Type': 'text/plain' });
  response.end(`Hello, ${query.name}!\n`);
});

// Listen on port 8000, IP defaults to 127.0.0.1.
server.listen(8000);

// Print a friendly message on the terminal.
console.log(`Server running at ${serverOrigin}/`);

If you run the script above, you can test the server response like this, for example:

curl -q http://localhost:8000/status?name=ryan
Hello, ryan!

No Application Encryption Key Has Been Specified

simply run

php artisan key:generate

its worked for me

How many times a substring occurs

string="abc"
mainstr="ncnabckjdjkabcxcxccccxcxcabc"
count=0
for i in range(0,len(mainstr)):
    k=0
    while(k<len(string)):
        if(string[k]==mainstr[i+k]):
            k+=1
        else:
            break   
    if(k==len(string)):
        count+=1;   
print(count)

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

How to sparsely checkout only one single file from a git repository?

If you only need to download the file, no need to check out with Git.

GitHub Mate is much easier to do so, it's a Chrome extension, enables you click the file icon to download it. also open source

$(window).height() vs $(document).height

Well you seem to have mistaken them both for what they do.

$(window).height() gets you an unit-less pixel value of the height of the (browser) window aka viewport. With respect to the web browsers the viewport here is visible portion of the canvas(which often is smaller than the document being rendered).

$(document).height() returns an unit-less pixel value of the height of the document being rendered. However, if the actual document’s body height is less than the viewport height then it will return the viewport height instead.

Hope that clears things a little.

gcc warning" 'will be initialized after'

Class C {
   int a;
   int b;
   C():b(1),a(2){} //warning, should be C():a(2),b(1)
}

the order is important because if a is initialized before b , and a is depend on b. undefined behavior will appear.

jQuery set radio button

In your selector you seem to be attempting to fetch some nested element of your radio button with a given id. If you want to check a radio button, you should select this radio button in the selector and not something else:

$('input:radio[name="cols"]').attr('checked', 'checked');

This assumes that you have the following radio button in your markup:

<input type="radio" name="cols" value="1" />

If your radio button had an id:

<input type="radio" name="cols" value="1" id="myradio" />

you could directly use an id selector:

$('#myradio').attr('checked', 'checked');

Greyscale Background Css Images

Using current browsers you can use it like this:

img {
  -webkit-filter: grayscale(100%); /* Chrome, Safari, Opera */
  filter: grayscale(100%);
}

and to remedy it:

img:hover{
   -webkit-filter: grayscale(0%); /* Chrome, Safari, Opera */
   filter: grayscale(0%);
}

worked with me and is much shorter. There is even more one can do within the CSS:

filter: none | blur() | brightness() | contrast() | drop-shadow() | grayscale() |
        hue-rotate() | invert() | opacity() | saturate() | sepia() | url();

For more information and supporting browsers see this: http://www.w3schools.com/cssref/css3_pr_filter.asp

Running Python on Windows for Node.js dependencies

Set path like below and it will work

> set PYTHON=D:\\ranjith\\installed\\python-3.6.4\\python.exe

> npm config set python D:\\ranjith\\installed\\python-3.6.4\\python.exe

Then build your project (for me like)

> yarn build

Bash script to cd to directory with spaces in pathname

I had a similar problem now were I was using a bash script to dump some data. I ended up creating a symbolic link in the script folder with out any spaces in it. I then pointed my script to the symbolic link and that works fine.

To create your link. ln -s [TARGET DIRECTORY OR FILE] ./[SHORTCUT]

Mau or may not be of use.

Use tab to indent in textarea

Based on all that people had to say here on the answers, its just a combination of keydown(not keyup) + preventDefault() + insert a tab character at the caret. Something like:

var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
   e.preventDefault();
   insertAtCaret('txt', '\t')
}

The earlier answer had a working jsfiddle but it used an alert() on keydown. If you remove this alert, then it didnt work. I ve just added a function to insert a tab at the current cursor position in the textarea.

Here s a working jsfiddle for the same: http://jsfiddle.net/nsHGZ/

Methods vs Constructors in Java

Other instructors and teaching assistants occasionally tell me that constructors are specialized methods. I always argue that in Java constructors are NOT specialized methods.

If constructors were methods at all, I would expect them to have the same abilities as methods. That they would at least be similar in more ways than they are different.

How are constructors different than methods? Let me count the ways...

  1. Constructors must be invoked with the new operator while methods may not be invoked with the new operator. Related: Constructors may not be called by name while methods must be called by name.

  2. Constructors may not have a return type while methods must have a return type.

  3. If a method has the same name as the class, it must have a return type. Otherwise, it is a constructor. The fact that you can have two MyClass() signatures in the same class definition which are treated differently should convince all that constructors and methods are different entities:

    public class MyClass {
       public MyClass() { }                                   // constructor
       public String MyClass() { return "MyClass() method"; } // method
    }
    
  4. Constructors may initialize instance constants while methods may not.

  5. Public and protected constructors are not inherited while public and protected methods are inherited.

  6. Constructors may call the constructors of the super class or same class while methods may not call either super() or this().

So, what is similar about methods and constructors?

  1. They both have parameter lists.

  2. They both have blocks of code that will be executed when that block is either called directly (methods) or invoked via new (constructors).

As for constructors and methods having the same visibility modifiers... fields and methods have more visibility modifiers in common.

  1. Constructors may be: private, protected, public.

  2. Methods may be: private, protected, public, abstract, static, final, synchronized, native, strictfp.

  3. Data fields may be: private, protected, public, static, final, transient, volatile.

In Conclusion

In Java, the form and function of constructors is significantly different than for methods. Thus, calling them specialized methods actually makes it harder for new programmers to learn the differences. They are much more different than similar and learning them as different entities is critical in Java.

I do recognize that Java is different than other languages in this regard, namely C++, where the concept of specialized methods originates and is supported by the language rules. But, in Java, constructors are not methods at all, much less specialized methods.

Even javadoc recognizes the differences between constructors and methods outweigh the similarities; and provides a separate section for constructors.

vuetify center items into v-flex

v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.

So, you should override it with display: flex in your HTML or CSS to make it work with justify-content.

C# winforms combobox dynamic autocomplete

Yes, you surely can... but it needs some work to make it work seamlessly. This is some code I came up with. Bear in mind that it does not use combobox's auto-complete features, and it might be quite slow if you use it to sift thru a lot of items...

string[] data = new string[] {
    "Absecon","Abstracta","Abundantia","Academia","Acadiau","Acamas",
    "Ackerman","Ackley","Ackworth","Acomita","Aconcagua","Acton","Acushnet",
    "Acworth","Ada","Ada","Adair","Adairs","Adair","Adak","Adalberta","Adamkrafft",
    "Adams"

};
public Form1()
{
    InitializeComponent();
}

private void comboBox1_TextChanged(object sender, EventArgs e)
{
    HandleTextChanged();
}

private void HandleTextChanged()
{
    var txt = comboBox1.Text;
    var list = from d in data
               where d.ToUpper().StartsWith(comboBox1.Text.ToUpper())
               select d;
    if (list.Count() > 0)
    {
        comboBox1.DataSource = list.ToList();
        //comboBox1.SelectedIndex = 0;
        var sText = comboBox1.Items[0].ToString();
        comboBox1.SelectionStart = txt.Length;
        comboBox1.SelectionLength = sText.Length - txt.Length;
        comboBox1.DroppedDown = true;
        return;
    }
    else
    {
        comboBox1.DroppedDown = false;
        comboBox1.SelectionStart = txt.Length;
    }
}

private void comboBox1_KeyUp(object sender, KeyEventArgs e)
{
    if (e.KeyCode == Keys.Back)
    {
        int sStart = comboBox1.SelectionStart;
        if (sStart > 0)
        {
            sStart--;
            if (sStart == 0)
            {
                comboBox1.Text = "";
            }
            else
            {
                comboBox1.Text = comboBox1.Text.Substring(0, sStart);
            }
        }
        e.Handled = true;
    }
}

How do you save/store objects in SharedPreferences on Android?

// SharedPrefHelper is a class contains the get and save sharedPrefernce data
public class SharedPrefHelper {

    // save data in sharedPrefences
    public static void setSharedOBJECT(Context context, String key, 
                                           Object value) {

        SharedPreferences sharedPreferences =  context.getSharedPreferences(
                context.getPackageName(), Context.MODE_PRIVATE);

        SharedPreferences.Editor prefsEditor = sharedPreferences.edit();
        Gson gson = new Gson();
        String json = gson.toJson(value);
        prefsEditor.putString(key, json);
        prefsEditor.apply();
    }

    // get data from sharedPrefences 
    public static Object getSharedOBJECT(Context context, String key) {

         SharedPreferences sharedPreferences = context.getSharedPreferences(
                           context.getPackageName(), Context.MODE_PRIVATE);

        Gson gson = new Gson();
        String json = sharedPreferences.getString(key, "");
        Object obj = gson.fromJson(json, Object.class);
        User objData = new Gson().fromJson(obj.toString(), User.class);
        return objData;
    }
}
// save data in your activity

User user = new User("Hussein","[email protected]","3107310890983");        
SharedPrefHelper.setSharedOBJECT(this,"your_key",user);        
User data = (User) SharedPrefHelper.getSharedOBJECT(this,"your_key");

Toast.makeText(this,data.getName()+"\n"+data.getEmail()+"\n"+data.getPhone(),Toast.LENGTH_LONG).show();
// User is the class you want to save its objects

public class User {

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    private String name,email,phone;
    public User(String name,String email,String phone){
          this.name=name;
          this.email=email;
          this.phone=phone;
    }
}
// put this in gradle

compile 'com.google.code.gson:gson:2.7'

hope this helps you :)

Drawing Circle with OpenGL

Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius

void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
    int i;
    int triangleAmount = 20; //# of triangles used to draw circle

    //GLfloat radius = 0.8f; //radius
    GLfloat twicePi = 2.0f * PI;

    glBegin(GL_TRIANGLE_FAN);
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= triangleAmount; i++) {
        glVertex2f(
            x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
            y + ((ycenter-1)* sin(i * twicePi / triangleAmount))
        );
    }
    glEnd();
}

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

I solved this by writing the explicit IP address defined in the Listener.ora file as the hostname.

enter image description here

So, instead of "localhost", I wrote "192.168.1.2" as the "Hostname" in the SQL Developer field.

In the below picture I highlighted the input boxes that I've modified: enter image description here

Android M Permissions: onRequestPermissionsResult() not being called

private void showContacts() {
    if (getActivity().checkSelfPermission(Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {
        requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
    } else {
        doShowContacts();
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        doShowContacts();
    }
}

efficient way to implement paging

you can further improve the performance, chech this

From CityEntities c
Inner Join dbo.MtCity t0 on c.CodCity = t0.CodCity
Where c.Row Between @p0 + 1 AND @p0 + @p1
Order By c.Row Asc

if you will use the from in this way it will give better result:

From   dbo.MtCity  t0
   Inner Join  CityEntities c on c.CodCity = t0.CodCity

reason: because you are using the where class on the CityEntities table which will eliminate many record before joining the MtCity, so 100% sure it will increase the performance many fold...

Anyway answer by rodrigoelp is really helpfull.

Thanks

Single vs Double quotes (' vs ")

The w3 org said:

By default, SGML requires that all attribute values be delimited using either double quotation marks (ASCII decimal 34) or single quotation marks (ASCII decimal 39). Single quote marks can be included within the attribute value when the value is delimited by double quote marks, and vice versa. Authors may also use numeric character references to represent double quotes (&#34;) and single quotes (&#39;). For double quotes authors can also use the character entity reference &quot;.

So... seems to be no difference. Only depends on your style.

What range of values can integer types store in C++

Other folks here will post links to data_sizes and precisions etc.
I'm going to tell you how to figure it out yourself.
Write a small app that will do the following.

unsigned int ui;
std::cout <<  sizeof(ui));

this will (depending on compiler and archicture) print 2, 4 or 8, saying 2 bytes long, 4 bytes long etc.

Lets assume it's 4.

You now want the maximum value 4 bytes can store, the max value for one byte is (in hex)0xFF. The max value of four bytes is 0x followed by 8 f's (one pair of f's for each byte, the 0x tells the compiler that the following string is a hex number). Now change your program to assign that value and print the result

unsigned int ui = 0xFFFFFFFF;
std::cout <<  ui;

Thats the max value an unsigned int can hold, shown in base 10 representation.

Now do that for long's, shorts and any other INTEGER value you're curious about.

NB: This approach will not work for floating point numbers (i.e. double or float).

Hope this helps

Convert IQueryable<> type object to List<T> type?

The List class's constructor can convert an IQueryable for you:

public static List<TResult> ToList<TResult>(this IQueryable source)
{
    return new List<TResult>(source);
}

or you can just convert it without the extension method, of course:

var list = new List<T>(queryable);

How to use a DataAdapter with stored procedure and parameter

    SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();
        builder.DataSource = <sql server name>;
        builder.UserID = <user id>; //User id used to login into SQL
        builder.Password = <password>; //password used to login into SQL
        builder.InitialCatalog = <database name>; //Name of Database

        DataTable orderTable = new DataTable();

        //<sp name> stored procedute name which you want to exceute
        using (var con = new SqlConnection(builder.ConnectionString))
        using (SqlCommand cmd = new SqlCommand(<sp name>, con)) 
        using (var da = new SqlDataAdapter(cmd))
        {
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            //Data adapter(da) fills the data retuned from stored procedure 
           //into orderTable
            da.Fill(orderTable);
        }

JavaFX How to set scene background image

You can change style directly for scene using .root class:

.root {
    -fx-background-image: url("https://www.google.com/images/srpr/logo3w.png");
}

Add this to CSS and load it as "Uluk Biy" described in his answer.

Shift column in pandas dataframe up by one?

To easily shift by 5 values for example and also get rid of the NaN rows, without having to keep track of the number of values you shifted by:

d['gdp'] = df['gdp'].shift(-5)
df = df.dropna()

Fix Access denied for user 'root'@'localhost' for phpMyAdmin

Find config.inc file under C:\wamp\apps\phpmyadmin3.5.1 Inside this file find this one line

$cfg['Servers'][$i]['password'] =";

and replace it with

$cfg['Servers'][$i]['password'] = 'Type your root password here';

javascript windows alert with redirect function

Use this if you also want to consider non-javascript users:

echo ("<SCRIPT LANGUAGE='JavaScript'>
           window.alert('Succesfully Updated')
           window.location.href='http://someplace.com';
       </SCRIPT>
       <NOSCRIPT>
           <a href='http://someplace.com'>Successfully Updated. Click here if you are not redirected.</a>
       </NOSCRIPT>");

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

I had the same problem and I fixed it just by setting this: <item name="android:windowIsFloating">false</item> in styles.xml

How do I find which application is using up my port?

How about netstat?

http://support.microsoft.com/kb/907980

The command is netstat -anob.

(Make sure you run command as admin)

I get:

C:\Windows\system32>netstat -anob

Active Connections

     Proto  Local Address          Foreign Address        State           PID
  TCP           0.0.0.0:80                0.0.0.0:0                LISTENING         4
 Can not obtain ownership information

  TCP    0.0.0.0:135            0.0.0.0:0              LISTENING       692
  RpcSs
 [svchost.exe]

  TCP    0.0.0.0:443            0.0.0.0:0              LISTENING       7540
 [Skype.exe]

  TCP    0.0.0.0:445            0.0.0.0:0              LISTENING       4
 Can not obtain ownership information
  TCP    0.0.0.0:623            0.0.0.0:0              LISTENING       564
 [LMS.exe]

  TCP    0.0.0.0:912            0.0.0.0:0              LISTENING       4480
 [vmware-authd.exe]

And If you want to check for the particular port, command to use is: netstat -aon | findstr 8080 from the same path

Custom pagination view in Laravel 5

In Laravel 5.3+ use

$users->links('view.name')

In Laravel 5.0 - 5.2 instead of

$users->render()

use

@include('pagination.default', ['paginator' => $users])

views/pagination/default.blade.php

@if ($paginator->lastPage() > 1)
<ul class="pagination">
    <li class="{{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
        <a href="{{ $paginator->url(1) }}">Previous</a>
    </li>
    @for ($i = 1; $i <= $paginator->lastPage(); $i++)
        <li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
            <a href="{{ $paginator->url($i) }}">{{ $i }}</a>
        </li>
    @endfor
    <li class="{{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
        <a href="{{ $paginator->url($paginator->currentPage()+1) }}" >Next</a>
    </li>
</ul>
@endif

That's it.


If you have a lot of pages, use this template:

views/pagination/limit_links.blade.php

<?php
// config
$link_limit = 7; // maximum number of links (a little bit inaccurate, but will be ok for now)
?>

@if ($paginator->lastPage() > 1)
    <ul class="pagination">
        <li class="{{ ($paginator->currentPage() == 1) ? ' disabled' : '' }}">
            <a href="{{ $paginator->url(1) }}">First</a>
         </li>
        @for ($i = 1; $i <= $paginator->lastPage(); $i++)
            <?php
            $half_total_links = floor($link_limit / 2);
            $from = $paginator->currentPage() - $half_total_links;
            $to = $paginator->currentPage() + $half_total_links;
            if ($paginator->currentPage() < $half_total_links) {
               $to += $half_total_links - $paginator->currentPage();
            }
            if ($paginator->lastPage() - $paginator->currentPage() < $half_total_links) {
                $from -= $half_total_links - ($paginator->lastPage() - $paginator->currentPage()) - 1;
            }
            ?>
            @if ($from < $i && $i < $to)
                <li class="{{ ($paginator->currentPage() == $i) ? ' active' : '' }}">
                    <a href="{{ $paginator->url($i) }}">{{ $i }}</a>
                </li>
            @endif
        @endfor
        <li class="{{ ($paginator->currentPage() == $paginator->lastPage()) ? ' disabled' : '' }}">
            <a href="{{ $paginator->url($paginator->lastPage()) }}">Last</a>
        </li>
    </ul>
@endif

What to gitignore from the .idea folder?

Github uses the following .gitignore for their programs

https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore

# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf

# Generated files
.idea/**/contentModel.xml

# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml

# Gradle
.idea/**/gradle.xml
.idea/**/libraries

# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn.  Uncomment if using
# auto-import.
# .idea/modules.xml
# .idea/*.iml
# .idea/modules

# CMake
cmake-build-*/

# Mongo Explorer plugin
.idea/**/mongoSettings.xml

# File-based project format
*.iws

# IntelliJ
out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Cursive Clojure plugin
.idea/replstate.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

# Editor-based Rest Client
.idea/httpRequests

# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

C++ initial value of reference to non-const must be an lvalue

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

JPA Query.getResultList() - use in a generic way

Here is the sample on what worked for me. I think that put method is needed in entity class to map sql columns to java class attributes.

    //simpleExample
    Query query = em.createNativeQuery(
"SELECT u.name,s.something FROM user u,  someTable s WHERE s.user_id = u.id", 
NameSomething.class);
    List list = (List<NameSomething.class>) query.getResultList();

Entity class:

    @Entity
    public class NameSomething {

        @Id
        private String name;

        private String something;

        // getters/setters



        /**
         * Generic put method to map JPA native Query to this object.
         *
         * @param column
         * @param value
         */
        public void put(Object column, Object value) {
            if (((String) column).equals("name")) {
                setName(String) value);
            } else if (((String) column).equals("something")) {
                setSomething((String) value);
            }
        }
    }

How to make an Android device vibrate? with different frequency?

Vibrating in Patterns/Waves:

import android.os.Vibrator;
...
// Vibrate for 500ms, pause for 500ms, then start again
private static final long[] VIBRATE_PATTERN = { 500, 500 };

mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    // API 26 and above
    mVibrator.vibrate(VibrationEffect.createWaveform(VIBRATE_PATTERN, 0));
} else {
    // Below API 26
    mVibrator.vibrate(VIBRATE_PATTERN, 0);
}

Plus

The necessary permission in AndroidManifest.xml:

<uses-permission android:name="android.permission.VIBRATE"/>

Web scraping with Java

HTMLUnit can be used to do web scraping, it supports invoking pages, filling & submitting forms. I have used this in my project. It is good java library for web scraping. read here for more

Go To Definition: "Cannot navigate to the symbol under the caret."

I also came across this once. There is something wrong with TFS in VS 2015.

I followed these steps and it worked

  1. Cleared TFS Cache This might be here:

    C:\Users\(UserName)\AppData\Local\Microsoft\Team Foundation\(Version)\Cache

Note: path may vary based on operating system so don't blame me.

  1. Emptied Symbol Cache

    Tools > Options > Debugging > Symbols > EmptySymbolCache

  2. Restarted Visual Studio (It Might ask for connecting to TFS again)

This Worked for me.:)

Why is my power operator (^) not working?

There is no way to use the ^ (Bitwise XOR) operator to calculate the power of a number. Therefore, in order to calculate the power of a number we have two options, either we use a while loop or the pow() function.

1. Using a while loop.

#include <stdio.h>

int main() {

    int base, expo;
    long long result = 1;

    printf("Enter a base no.: ");
    scanf("%d", &base);

    printf("Enter an exponent: ");
    scanf("%d", &expo);

    while (expo != 0) {
        result *= base;
        --expo;
    }

    printf("Answer = %lld", result);
    return 0;
}    
             

2. Using the pow() function

#include <math.h>
#include <stdio.h>

int main() {

    double base, exp, result;

    printf("Enter a base number: ");
    scanf("%lf", &base);

    printf("Enter an exponent: ");
    scanf("%lf", &exp);

    // calculate the power of our input numbers
    result = pow(base, exp);

    printf("%.1lf^%.1lf = %.2lf", base, exp, result);

    return 0;
}
     

Reading my own Jar's Manifest

You can find the URL for your class first. If it's a JAR, then you load the manifest from there. For example,

Class clazz = MyClass.class;
String className = clazz.getSimpleName() + ".class";
String classPath = clazz.getResource(className).toString();
if (!classPath.startsWith("jar")) {
  // Class not from JAR
  return;
}
String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + 
    "/META-INF/MANIFEST.MF";
Manifest manifest = new Manifest(new URL(manifestPath).openStream());
Attributes attr = manifest.getMainAttributes();
String value = attr.getValue("Manifest-Version");

Unable to start the mysql server in ubuntu

Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

sudo apt --reinstall install mysql-server

Decoding JSON String in Java

This is the best and easiest code:

public class test
{
    public static void main(String str[])
    {
        String jsonString = "{\"stat\": { \"sdr\": \"aa:bb:cc:dd:ee:ff\", \"rcv\": \"aa:bb:cc:dd:ee:ff\", \"time\": \"UTC in millis\", \"type\": 1, \"subt\": 1, \"argv\": [{\"type\": 1, \"val\":\"stackoverflow\"}]}}";
        JSONObject jsonObject = new JSONObject(jsonString);
        JSONObject newJSON = jsonObject.getJSONObject("stat");
        System.out.println(newJSON.toString());
        jsonObject = new JSONObject(newJSON.toString());
        System.out.println(jsonObject.getString("rcv"));
       System.out.println(jsonObject.getJSONArray("argv"));
    }
}

The library definition of the json files are given here. And it is not same libraries as posted here, i.e. posted by you. What you had posted was simple json library I have used this library.

You can download the zip. And then create a package in your project with org.json as name. and paste all the downloaded codes there, and have fun.

I feel this to be the best and the most easiest JSON Decoding.

Creating layout constraints programmatically

When using Auto Layout in code, setting the frame does nothing. So the fact that you specified a width of 200 on the view above, doesn't mean anything when you set constraints on it. In order for a view's constraint set to be unambiguous, it needs four things: an x-position, a y-position, a width, and a height for any given state.

Currently in the code above, you only have two (height, relative to the superview, and y-position, relative to the superview). In addition to this, you have two required constraints that could conflict depending on how the view's superview's constraints are setup. If the superview were to have a required constraint that specifies it's height be some value less than 748, you will get an "unsatisfiable constraints" exception.

The fact that you've set the width of the view before setting constraints means nothing. It will not even take the old frame into account and will calculate a new frame based on all of the constraints that it has specified for those views. When dealing with autolayout in code, I typically just create a new view using initWithFrame:CGRectZero or simply init.

To create the constraint set required for the layout you verbally described in your question, you would need to add some horizontal constraints to bound the width and x-position in order to give a fully-specified layout:

[self.view addConstraints:[NSLayoutConstraint
    constraintsWithVisualFormat:@"V:|-[myView(>=748)]-|"
    options:NSLayoutFormatDirectionLeadingToTrailing
    metrics:nil
    views:NSDictionaryOfVariableBindings(myView)]];

[self.view addConstraints:[NSLayoutConstraint
    constraintsWithVisualFormat:@"H:[myView(==200)]-|"
    options:NSLayoutFormatDirectionLeadingToTrailing
    metrics:nil
    views:NSDictionaryOfVariableBindings(myView)]];

Verbally describing this layout reads as follows starting with the vertical constraint:

myView will fill its superview's height with a top and bottom padding equal to the standard space. myView's superview has a minimum height of 748pts. myView's width is 200pts and has a right padding equal to the standard space against its superview.

If you would simply like the view to fill the entire superview's height without constraining the superview's height, then you would just omit the (>=748) parameter in the visual format text. If you think that the (>=748) parameter is required to give it a height - you don't in this instance: pinning the view to the superview's edges using the bar (|) or bar with space (|-, -|) syntax, you are giving your view a y-position (pinning the view on a single-edge), and a y-position with height (pinning the view on both edges), thus satisfying your constraint set for the view.

In regards to your second question:

Using NSDictionaryOfVariableBindings(self.myView) (if you had an property setup for myView) and feeding that into your VFL to use self.myView in your VFL text, you will probably get an exception when autolayout tries to parse your VFL text. It has to do with the dot notation in dictionary keys and the system trying to use valueForKeyPath:. See here for a similar question and answer.

Print second last column/field in awk

awk ' { print ( $(NF-1) ) }' file

How to make a jquery function call after "X" seconds

If you could show the actual page, we, possibly, could help you better.

If you want to trigger the button only after the iframe is loaded, you might want to check if it has been loaded or use the iframe.onload:

<iframe .... onload='buttonWhatever(); '></iframe>


<script type="text/javascript">

    function buttonWhatever() {
        $("#<%=Button1.ClientID%>").click(function (event) {
            $('#<%=TextBox1.ClientID%>').change(function () {
                $('#various3').attr('href', $(this).val());
            });
            $("#<%=Button2.ClientID%>").click();
        });

        function showStickySuccessToast() {
            $().toastmessage('showToast', {
                text: 'Finished Processing!',
                sticky: false,
                position: 'middle-center',
                type: 'success',
                closeText: '',
                close: function () { }
            });
        }
    }

</script>

Target WSGI script cannot be loaded as Python module

Appending path in wsgi.py is the direction, but instead of appending django appending path sys.path.append("/path/to/virtual/environment/lib/pythonX.X/site-packages") fixed my case.

This is for a django project using python2.7 on ubuntu 16.04.

How to implement zoom effect for image view in android?

Here is a great example on how to implement zoom affect on touch with a imageview

Zoom effect on imageview

EDIT:

Also here is another great one.

Pinch to zoom tutorial

array.select() in javascript

There's also Array.find() in ES6 which returns the first matching element it finds.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const myArray = [1, 2, 3]

const myElement = myArray.find((element) => element === 2)

console.log(myElement)
// => 2

For a boolean field, what is the naming convention for its getter/setter?

private boolean current;

public void setCurrent(boolean current){
    this.current=current;
}

public boolean hasCurrent(){
    return this.current;
}

How to export iTerm2 Profiles

There is another way to do this.

From iTerm2 2.9.20140923 you can use Dynamic Profiles as stated in the documentation page:

Dynamic Profiles is a feature that allows you to store your profiles in a file outside the usual macOS preferences database. Profiles may be changed at runtime by editing one or more plist files (formatted as JSON, XML, or in binary). Changes are picked up immediately.

So it is possible to create a file like this one:

    {
        "Profiles": [{
                "Name": "MYSERVER1",
                "Guid": "MYSERVER1",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "M",
                "Tags": [
                    "LOCAL", "THATCOMPANY", "WORK", "NOCLOUD"
                ],
                "Badge Text": "SRV1",
            },
            {
                "Name": "MYOCEANSERVER1",
                "Guid": "MYOCEANSERVER1",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "O",
                "Tags": [
                    "THATCOMPANY", "WORK", "DIGITALOCEAN"
                ],
                "Badge Text": "PPOCEAN1",
            },
            {
                "Name": "PI1",
                "Guid": "PI1",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "1",
                "Tags": [
                    "LOCAL", "PERSONAL", "RASPBERRY", "SMALL"
                ],
                "Badge Text": "LocalServer",
            },
            {
                "Name": "VUZERO",
                "Guid": "VUZERO",
                "Custom Command": "Yes",
                "Command": "ssh [email protected]",
                "Shortcut": "0",
                "Tags": [
                    "LOCAL", "PERSONAL", "SMALL"
                ],
                "Badge Text": "TeleVision",
            }
        ]
    }

in the folder ~/Library/Application\ Support/iTerm2/DynamicProfiles/ and share it across different machines. This enables you to retain some visual differences among iterm2 installations such as font type or dimension, while synchronising remote hosts, shortcuts, commands, and even a small badge to quickly identify a session

badge

What is a callback?

In computer programming, a callback is executable code that is passed as an argument to other code.

Wikipedia: Callback (computer science)

C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).

Angular 6 Material mat-select change method removed

If you're using Reactive forms you can listen for changes to the select control like so..

this.form.get('mySelectControl').valueChanges.subscribe(value => { ... do stuff ... })

How to stop a looping thread in Python?

Depends on what you run in that thread. If that's your code, then you can implement a stop condition (see other answers).

However, if what you want is to run someone else's code, then you should fork and start a process. Like this:

import multiprocessing
proc = multiprocessing.Process(target=your_proc_function, args=())
proc.start()

now, whenever you want to stop that process, send it a SIGTERM like this:

proc.terminate()
proc.join()

And it's not slow: fractions of a second. Enjoy :)

Command output redirect to file and terminal

Yes, if you redirect the output, it won't appear on the console. Use tee.

ls 2>&1 | tee /tmp/ls.txt

How to convert JSON string to array

If you ever need to convert JSON file or structures to PHP-style arrays, with all the nesting levels, you can use this function. First, you must json_decode($yourJSONdata) and then pass it to this function. It will output to your browser window (or console) the correct PHP styled arrays.

https://github.com/mobsted/jsontophparray

React native text going off my screen, refusing to wrap. What to do?

<View style={{flexDirection:'row'}}> 
  <Text style={{flex: 1, flexWrap: 'wrap'}}> 

This will work

getting the X/Y coordinates of a mouse click on an image with jQuery

Here is a better script:

$('#mainimage').click(function(e)
{   
    var offset_t = $(this).offset().top - $(window).scrollTop();
    var offset_l = $(this).offset().left - $(window).scrollLeft();

    var left = Math.round( (e.clientX - offset_l) );
    var top = Math.round( (e.clientY - offset_t) );

    alert("Left: " + left + " Top: " + top);

});

How to remove MySQL completely with config and library files?

With the command:

sudo apt-get remove --purge mysql\*

you can delete anything related to packages named mysql. Those commands are only valid on debian / debian-based linux distributions (Ubuntu for example).

You can list all installed mysql packages with the command:

sudo dpkg -l | grep -i mysql

For more cleanup of the package cache, you can use the command:

sudo apt-get clean

Also, remember to use the command:

sudo updatedb

Otherwise the "locate" command will display old data.

To install mysql again, use the following command:

sudo apt-get install libmysqlclient-dev mysql-client

This will install the mysql client, libmysql and its headers files.

To install the mysql server, use the command:

sudo apt-get install mysql-server

Equivalent of typedef in C#

No, there's no true equivalent of typedef. You can use 'using' directives within one file, e.g.

using CustomerList = System.Collections.Generic.List<Customer>;

but that will only impact that source file. In C and C++, my experience is that typedef is usually used within .h files which are included widely - so a single typedef can be used over a whole project. That ability does not exist in C#, because there's no #include functionality in C# that would allow you to include the using directives from one file in another.

Fortunately, the example you give does have a fix - implicit method group conversion. You can change your event subscription line to just:

gcInt.MyEvent += gcInt_MyEvent;

:)

How to develop Desktop Apps using HTML/CSS/JavaScript?

It seems the solutions for HTML/JS/CSS desktop apps are in no short supply.

One solution I have just come across is TideSDK: http://www.tidesdk.org/, which seems very promising, looking at the documentation.

You can develop with Python, PHP or Ruby, and package it for Mac, Windows or Linux.

Count of "Defined" Array Elements

Remove the values then check (remove null check here if you want)

const x = A.filter(item => item !== undefined || item !== null).length

With Lodash

const x = _.size(_.filter(A, item => !_.isNil(item)))

ImportError: No module named xlsxwriter

Even if it looks like the module is installed, as far as Python is concerned it isn't since it throws that exception.

Try installing the module again using one of the installation methods shown in the XlsxWriter docs and look out for any installation errors.

If there are none then run a sample program like the following:

import xlsxwriter

workbook = xlsxwriter.Workbook('hello.xlsx')
worksheet = workbook.add_worksheet()

worksheet.write('A1', 'Hello world')

workbook.close()

How to get a time zone from a location using latitude and longitude coordinates?

  1. There are several sources online that have geojson data for timezones (here's one, here's another)

  2. Use a geometry library to create polygon objects from the geojson coordinates (shapely [python], GEOS [c++], JTS [java], NTS [.net]).

  3. Convert your lat/lng to a point object (however your library represents that) and check if it intersects the timezone polygon.

    from shapely.geometry import Polygon, Point
    
    def get_tz_from_lat_lng(lat, lng):
        for tz, geojson in timezones.iteritems():
            coordinates = geojson['features'][0]['geometry']['coordinates']
            polygon = Polygon(coordinates)
            point = Point(lng, lat)
            if polygon.contains(point):
                return tz
    

How to smooth a curve in the right way?

EDIT: look at this answer. Using np.cumsum is much faster than np.convolve

A quick and dirty way to smooth data I use, based on a moving average box (by convolution):

x = np.linspace(0,2*np.pi,100)
y = np.sin(x) + np.random.random(100) * 0.8

def smooth(y, box_pts):
    box = np.ones(box_pts)/box_pts
    y_smooth = np.convolve(y, box, mode='same')
    return y_smooth

plot(x, y,'o')
plot(x, smooth(y,3), 'r-', lw=2)
plot(x, smooth(y,19), 'g-', lw=2)

enter image description here

configure: error: C compiler cannot create executables

First get the gcc path using

Command: which gcc

Output: /usr/bin/gcc

I had the same issue, Please set the gcc path in below command and install

CC=/usr/bin/gcc rvm install 1.9.3

Later if you get "Ruby was built without documentation" run below command

rvm docs generate-ri

How to check if the given string is palindrome?

I haven't seen any recursion yet, so here goes...

import re

r = re.compile("[^0-9a-zA-Z]")

def is_pal(s):

    def inner_pal(s):
        if len(s) == 0:
            return True
        elif s[0] == s[-1]:
            return inner_pal(s[1:-1])
        else:
            return False

    r = re.compile("[^0-9a-zA-Z]")
    return inner_pal(r.sub("", s).lower())

How to set margin of ImageView using code, not xml

In Kotlin you can write it in more pleasant way

myView.layoutParams = LinearLayout.LayoutParams(
                RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT
            ).apply {
                setMargins(12, 12, 12, 12)
            }

String literals and escape characters in postgresql

Partially. The text is inserted, but the warning is still generated.

I found a discussion that indicated the text needed to be preceded with 'E', as such:

insert into EscapeTest (text) values (E'This is the first part \n And this is the second');

This suppressed the warning, but the text was still not being returned correctly. When I added the additional slash as Michael suggested, it worked.

As such:

insert into EscapeTest (text) values (E'This is the first part \\n And this is the second');

How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook?

the below lines would also work

!python script.py

Why do Twitter Bootstrap tables always have 100% width?

Bootstrap 3:

Why fight it? Why not simply control your table width using the bootstrap grid?

<div class="row">
    <div class="col-sm-6">
        <table></table>
    </div>
</div>

This will create a table that is half (6 out of 12) of the width of the containing element.

I sometimes use inline styles as per the other answers, but it is discouraged.

Bootstrap 4:

Bootstrap 4 has some nice helper classes for width like w-25, w-50, w-75, w-100, and w-auto. This will make the table 50% width:

<table class="w-50"></table>

Here's the doc: https://getbootstrap.com/docs/4.0/utilities/sizing/

How to group by month from Date field using sql

You can do this by using Year(), Month() Day() and datepart().

In you example this would be:

select  Closing_Date, Category,  COUNT(Status)TotalCount from  MyTable
where Closing_Date >= '2012-02-01' and Closing_Date <= '2012-12-31' 
and Defect_Status1 is not null 
group by Year(Closing_Date), Month(Closing_Date), Category

Remove multiple items from a Python list in just one statement

You can use filterfalse function from itertools module

Example

import random
from itertools import filterfalse

random.seed(42)

data = [random.randrange(5) for _ in range(10)]
clean = [*filterfalse(lambda i: i == 0, data)]
print(f"Remove 0s\n{data=}\n{clean=}\n")


clean = [*filterfalse(lambda i: i in (0, 1), data)]
print(f"Remove 0s and 1s\n{data=}\n{clean=}")

Output:

Remove 0s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 1, 1, 1, 4, 4]

Remove 0s and 1s
data=[0, 0, 2, 1, 1, 1, 0, 4, 0, 4]
clean=[2, 4, 4]

Change New Google Recaptcha (v2) Width

A bit late but I've got an easy workaround:

Just add this code to your "g-recaptcha" class:

width: desired_width;

border-radius: 4px;
border-right: 1px solid #d8d8d8;
overflow: hidden;

Convert DataFrame column type from string to datetime, dd/mm/yyyy format

If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.

df['date'] = df['date'].astype('datetime64[ns]')

or use datetime64[D] if you want Day precision and not nanoseconds

print(type(df_launath['date'].iloc[0]))

yields

<class 'pandas._libs.tslib.Timestamp'> the same as when you use pandas.to_datetime

You can try it with other formats then '%Y-%m-%d' but at least this works.

How To Launch Git Bash from DOS Command Line?

I prefer to use git-bash.exe instead of sh.exe.

start "" "%ProgramFiles%\Git\git-bash.exe" -c "tail -f /c/Windows/win.ini"

You can stop closing the window when call /usr/bin/bash --login -i in the end;

start "" "%ProgramFiles%\Git\git-bash.exe" -c "echo 1 && echo 2 && /usr/bin/bash --login -i"

Note: I'm not sure this is a good way :)

Pass Additional ViewData to a Strongly-Typed Partial View

RenderPartial takes another parameter that is simply a ViewDataDictionary. You're almost there, just call it like this:

Html.RenderPartial(
      "ProductImageForm", 
       image, 
       new ViewDataDictionary { { "index", index } }
); 

Note that this will override the default ViewData that all your other Views have by default. If you are adding anything to ViewData, it will not be in this new dictionary that you're passing to your partial view.

Android Layout Right Align

To support older version Space can be replaced with View as below. Add this view between after left most component and before right most component. This view with weight=1 will stretch and fill the space

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

Complete sample code is given here. It has has 4 components. Two arrows will be on the right and left side. The Text and Spinner will be in the middle.

    <ImageButton
        android:id="@+id/btnGenesis"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center|center_vertical"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="2dp"
        android:background="@null"
        android:gravity="left"
        android:src="@drawable/prev" />

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

    <TextView
        android:id="@+id/lblVerseHeading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:gravity="center"
        android:textSize="25sp" />

    <Spinner
        android:id="@+id/spinnerVerses"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:gravity="center"
        android:textSize="25sp" />

    <View
        android:layout_width="0dp"
        android:layout_height="20dp"
        android:layout_weight="1" />

    <ImageButton
        android:id="@+id/btnExodus"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center|center_vertical"
        android:layout_marginBottom="2dp"
        android:layout_marginLeft="0dp"
        android:layout_marginTop="2dp"
        android:background="@null"
        android:gravity="right"
        android:src="@drawable/next" />
</LinearLayout>

react-router (v4) how to go back?

Each answer here has parts of the total solution. Here's the complete solution that I used to get it to work inside of components deeper than where Route was used:

import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'

^ You need that second line to import function and to export component at bottom of page.

render() {
  return (
  ...
    <div onClick={() => this.props.history.goBack()}>GO BACK</div>
  )
}

^ Required the arrow function vs simply onClick={this.props.history.goBack()}

export default withRouter(MyPage)

^ wrap your component's name with 'withRouter()'

Clearing an input text field in Angular2

1. First Method

you have to assign null or empty string here

this.searchValue = null;
//or
this.searchValue = ' ';

Working Plunker

because no event is being fired from angular change detection. so you have to assign some value either null or string with space

2. Second Method

  • use of [(ngModel)] it should work with ngModel.

why ?

because as you did binding with value attribute which is only property binding not event binding. so angular doesn't run change detection because no event relevant to Angular is fired. If you bind to an event then Angular runs change detection and the binding works and value should be changes.

see working example of same with ngModel

Working Example with ngModel

Fastest way to tell if two files have the same contents in Unix/Linux?

I like @Alex Howansky have used 'cmp --silent' for this. But I need both positive and negative response so I use:

cmp --silent file1 file2 && echo '### SUCCESS: Files Are Identical! ###' || echo '### WARNING: Files Are Different! ###'

I can then run this in the terminal or with a ssh to check files against a constant file.

Node.js Best Practice Exception Handling

I would just like to add that Step.js library helps you handle exceptions by always passing it to the next step function. Therefore you can have as a last step a function that check for any errors in any of the previous steps. This approach can greatly simplify your error handling.

Below is a quote from the github page:

any exceptions thrown are caught and passed as the first argument to the next function. As long as you don't nest callback functions inline your main functions this prevents there from ever being any uncaught exceptions. This is very important for long running node.JS servers since a single uncaught exception can bring the whole server down.

Furthermore, you can use Step to control execution of scripts to have a clean up section as the last step. For example if you want to write a build script in Node and report how long it took to write, the last step can do that (rather than trying to dig out the last callback).