Programs & Examples On #Vcalendar

vcalendar was the preceeding standard prior to icalendar (rfc5545 which obsoleted rfc2445).

Difference between iCalendar (.ics) and the vCalendar (.vcs)

You can try VCS to ICS file converter (Java, works with Windows, Mac, Linux etc.). It has the feature of parsing events and todos. You can convert the VCS generated by your Nokia phone, with bluetooth export or via nbuexplorer.

  • Complete support for UTF-8
  • Quoted-printable encoded strings
  • Completely open source code (GPLv3 and Apache 2.0)
  • Standard iCalendar v2.0 output
  • Encodes multiple files at once (only one event per file)
  • Compatible with Android, iOS, Mozilla Lightning/Sunbird, Google Calendar and others
  • Multiplatform

How do I make a stored procedure in MS Access?

If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:

 PARAMETERS SomeParam Text(10);
 SELECT Field FROM Table
 WHERE OtherField=SomeParam

You can also say:

CREATE PROCEDURE ProcedureName
   (Parameter1 datatype, Parameter2 datatype) AS
   SQLStatement

From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs

Note that the procedure contains only one statement.

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

After insuring that the string "strOutput" has a correct XML structure, you can do this:

Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");

Using SELECT result in another SELECT

You are missing table NewScores, so it can't be found. Just join this table.

If you really want to avoid joining it directly you can replace NewScores.NetScore with SELECT NetScore FROM NewScores WHERE {conditions on which they should be matched}

Append column to pandas dataframe

It seems in general you're just looking for a join:

> dat1 = pd.DataFrame({'dat1': [9,5]})
> dat2 = pd.DataFrame({'dat2': [7,6]})
> dat1.join(dat2)
   dat1  dat2
0     9     7
1     5     6

Angular.js: How does $eval work and why is it different from vanilla eval?

$eval and $parse don't evaluate JavaScript; they evaluate AngularJS expressions. The linked documentation explains the differences between expressions and JavaScript.

Q: What exactly is $eval doing? Why does it need its own mini parsing language?

From the docs:

Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. Expressions are processed by $parse service.

It's a JavaScript-like mini-language that limits what you can run (e.g. no control flow statements, excepting the ternary operator) as well as adds some AngularJS goodness (e.g. filters).

Q: Why isn't plain old javascript "eval" being used?

Because it's not actually evaluating JavaScript. As the docs say:

If ... you do want to run arbitrary JavaScript code, you should make it a controller method and call the method. If you want to eval() an angular expression from JavaScript, use the $eval() method.

The docs linked to above have a lot more information.

How do I navigate to a parent route from a child route?

add Location to your constructor from @angular/common

constructor(private _location: Location) {}

add the back function:

back() {
  this._location.back();
}

and then in your view:

<button class="btn" (click)="back()">Back</button>

HTML5 Canvas and Anti-aliasing

Anti-aliasing cannot be turned on or off, and is controlled by the browser.

Can I turn off antialiasing on an HTML <canvas> element?

TypeError: $(...).autocomplete is not a function

Try this code, Let $ be defined

(function ($, Drupal) {

  'use strict';

  Drupal.behaviors.module_name = {
    attach: function (context, settings) {
        jQuery(document).ready(function($) {
      $("#search_text").autocomplete({
          source:results,
          minLength:2,
          position: { offset:'-30 0' },  
          select: function(event, ui ) { 
                  goTo(ui.item.value);
                  return false;
          }        
        }); 
        });
   }
  };
})(jQuery, Drupal);

What is token-based authentication?

A token is a piece of data which only Server X could possibly have created, and which contains enough data to identify a particular user.

You might present your login information and ask Server X for a token; and then you might present your token and ask Server X to perform some user-specific action.

Tokens are created using various combinations of various techniques from the field of cryptography as well as with input from the wider field of security research. If you decide to go and create your own token system, you had best be really smart.

Removing certain characters from a string in R

This should work

gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "

Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:

gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')

"Yes yes for ever for ever the boys and the girls"

Useful example of a shutdown hook in Java?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

How to make blinking/flashing text with CSS 3

enter image description here

.neon {
  font-size: 20px;
  color: #fff;
  text-shadow: 0 0 8px yellow;
  animation: blinker 6s;
  animation-iteration-count: 1;
}
@keyframes blinker {
  0% {
    opacity: 0.2;
  }
  19% {
    opacity: 0.2;
  }
  20% {
    opacity: 1;
  }
  21% {
    opacity: 1;
  }
  22% {
    opacity: 0.2;
  }
  23% {
    opacity: 0.2;
  }
  36% {
    opacity: 0.2;
  }
  40% {
    opacity: 1;
  }
  41% {
    opacity: 0;
  }
  42% {
    opacity: 1;
  }
  43% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 1;
  }
}

I used font-family: "Quicksand", sans-serif;

This is the import of the font (goes in the top of the style.css)

@import url("https://fonts.googleapis.com/css2?family=Quicksand:wght@300&display=swap");

How do you beta test an iphone app?

Diawi Alternatives

Since diawi.com have added some limitations for free accounds.

Next best available and easy to use alternative is

Microsoft

https://appcenter.ms

Google

https://firebase.google.com/docs/app-distribution/ios/distribute-console

Others

https://hockeyapp.net/

http://buildtry.com

Happy build sharing!

How to print all key and values from HashMap in Android?

First, there are errors in your code, ie. you are missing a semicolon and a closing parenthesis in the for loop.

Then, if you are trying to append values to the view, you should use textview.appendText(), instead of .setText().

There's a similar question here: how to change text in Android TextView

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

The import com.google.android.gms cannot be resolved

In my case or all using android studio

you can import google play service

place in your build.gradle

compile 'com.google.android.gms:play-services:7.8.0'

or latest version of play services depend in time you watch this answer

More Specific import

please review this individual gradle imports

https://developers.google.com/android/guides/setup

Google Maps

com.google.android.gms:play-services-maps:7.8.0

error may occurred

if you face error while you sync project with gradle files

enter image description here

make sure you install latest update

1- Android Support Repository.

2- Android Support Library.

3- Google Repository.

4-Google Play Services.

enter image description here

You may need restart your android studio to response

Updating an object with setState in React

You can try with this: (Note: name of input tag === field of object)

<input name="myField" type="text" 
      value={this.state.myObject.myField} 
     onChange={this.handleChangeInpForm}>
</input>

-----------------------------------------------------------
handleChangeInpForm = (e) => {
   let newObject = this.state.myObject;
   newObject[e.target.name] = e.target.value;
   this.setState({
     myObject: newObject 
   })
}

PHP Unset Array value effect on other indexes

They are as they were. That one key is JUST DELETED

Options for embedding Chromium instead of IE WebBrowser control with WPF/C#

UPDATE 2018 MAY:

Alternatively, you can embed Edge browser, but only targetting windows 10.

Here is the solution.

Java, looping through result set

List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();

String query = "SELECT rlink_id, COUNT(*)"
             + "FROM dbo.Locate  "
             + "GROUP BY rlink_id ";

Statement stmt = yourconnection.createStatement();
try {
    ResultSet rs4 = stmt.executeQuery(query);

    while (rs4.next()) {
        sids.add(rs4.getString(1));
        lids.add(rs4.getString(2));
    }
} finally {
    stmt.close();
}

String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());

Storing integer values as constants in Enum manner in java

The most common valid reason for wanting an integer constant associated with each enum value is to interoperate with some other component which still expects those integers (e.g. a serialization protocol which you can't change, or the enums represent columns in a table, etc).

In almost all cases I suggest using an EnumMap instead. It decouples the components more completely, if that was the concern, or if the enums represent column indices or something similar, you can easily make changes later on (or even at runtime if need be).

 private final EnumMap<Page, Integer> pageIndexes = new EnumMap<Page, Integer>(Page.class);
 pageIndexes.put(Page.SIGN_CREATE, 1);
 //etc., ...

 int createIndex = pageIndexes.get(Page.SIGN_CREATE);

It's typically incredibly efficient, too.

Adding data like this to the enum instance itself can be very powerful, but is more often than not abused.

Edit: Just realized Bloch addressed this in Effective Java / 2nd edition, in Item 33: Use EnumMap instead of ordinal indexing.

How to avoid "ConcurrentModificationException" while removing elements from `ArrayList` while iterating it?

As an alternative to everyone else's answers I've always done something like this:

List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
    if (someCondition) {
        toRemove.add(str);
    }
}
myArrayList.removeAll(toRemove);

This will avoid you having to deal with the iterator directly, but requires another list. I've always preferred this route for whatever reason.

Remove part of string in Java

You should use the substring() method of String object.

Here is an example code:

Assumption: I am assuming here that you want to retrieve the string till the first parenthesis

String strTest = "manchester united(with nice players)";
/*Get the substring from the original string, with starting index 0, and ending index as position of th first parenthesis - 1 */
String strSub = strTest.subString(0,strTest.getIndex("(")-1);

How to override a JavaScript function

You can override any built-in function by just re-declaring it.

parseFloat = function(a){
  alert(a)
};

Now parseFloat(3) will alert 3.

Please help me convert this script to a simple image slider

Problems only surface when I am I trying to give the first loaded content an active state

Does this mean that you want to add a class to the first button?

$('.o-links').click(function(e) {   // ... }).first().addClass('O_Nav_Current'); 

instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:

CSS:

.image-area {     width: 100%;     height: auto;     display: none; }  .image-area:first-of-type {     display: block; } 

JavaScript:

var $slides = $('.image-area'),     $btns = $('a.o-links');  $btns.on('click', function (e) {     var i = $btns.removeClass('O_Nav_Current').index(this);     $(this).addClass('O_Nav_Current');      $slides.filter(':visible').fadeOut(1000, function () {         $slides.eq(i).fadeIn(1000);     });      e.preventDefault();  }).first().addClass('O_Nav_Current'); 

http://jsfiddle.net/RmF57/

Missing Push Notification Entitlement

FIX IDEA Hey guys so i have made an app and did not used any push notification functions but i still got an email. After checking the certificates, ids and profiles of the bundle identifier i used to create my app in apple store connect in the apple developer portal i realized that push notificiations were turned on.

What you have to do is:

go to apple developer login site where you can manage your certificates a.s.o 2. select "Certificates, IDs and Profiles" Tab on the right side 3. now select "Identifiers" 4. and the bundle id from the list to the right 5. now scroll down till you see push notification 6. turn it off 7. archive your build and reupload it to Apple Store Connect

Hope it helps!

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

I had missing application context in the Tomcat Run\Debug configuration:enter image description here

Adding it, solved the problem and I got the right response instead of "The origin server did not find..."

Scale iFrame css width 100% like an image

None of these solutions worked for me inside a Weebly "add your own html" box. Not sure what they are doing with their code. But I found this solution at https://benmarshall.me/responsive-iframes/ and it works perfectly.

CSS

.iframe-container {
  overflow: hidden;
  padding-top: 56.25%;
  position: relative;
}

.iframe-container iframe {
   border: 0;
   height: 100%;
   left: 0;
   position: absolute;
   top: 0;
   width: 100%;
}

/* 4x3 Aspect Ratio */
.iframe-container-4x3 {
  padding-top: 75%;
}

HTML

<div class="iframe-container">
  <iframe src="https://player.vimeo.com/video/106466360" allowfullscreen></iframe>
</div>

What is the difference between substr and substring?

substring(): It has 2 parameters "start" and "end".

  • start parameter is required and specifies the position where to start the extraction.
  • end parameter is optional and specifies the position where the extraction should end.

If the end parameter is not specified, all the characters from the start position till the end of the string are extracted.

_x000D_
_x000D_
var str = "Substring Example";_x000D_
var result = str.substring(0, 10);_x000D_
alert(result);_x000D_
_x000D_
Output : Substring
_x000D_
_x000D_
_x000D_

If the value of start parameter is greater than the value of the end parameter, this method will swap the two arguments. This means start will be used as end and end will be used as start.

_x000D_
_x000D_
var str = "Substring Example";_x000D_
var result = str.substring(10, 0);_x000D_
alert(result);_x000D_
_x000D_
Output : Substring
_x000D_
_x000D_
_x000D_

substr(): It has 2 parameters "start" and "count".

  • start parameter is required and specifies the position where to start the extraction.

  • count parameter is optional and specifies the number of characters to extract.

_x000D_
_x000D_
var str = "Substr Example";_x000D_
var result = str.substr(0, 10);_x000D_
alert(result);_x000D_
_x000D_
_x000D_
Output : Substr Exa
_x000D_
_x000D_
_x000D_

If the count parameter is not specified, all the characters from the start position till the end of the string are extracted. If count is 0 or negative, an empty string is returned.

_x000D_
_x000D_
var str = "Substr Example";_x000D_
var result = str.substr(11);_x000D_
alert(result);_x000D_
_x000D_
Output : ple
_x000D_
_x000D_
_x000D_

What is the best way to create and populate a numbers table?

Here is a couple of extra methods:
Method 1

IF OBJECT_ID('dbo.Numbers', 'U') IS NOT NULL
    DROP TABLE dbo.Numbers
GO

CREATE TABLE Numbers (Number int NOT NULL PRIMARY KEY);
GO

DECLARE @i int = 1;
INSERT INTO dbo.Numbers (Number) 
VALUES (1),(2);

WHILE 2*@i < 1048576
BEGIN
    INSERT INTO dbo.Numbers (Number) 
    SELECT Number + 2*@i
    FROM dbo.Numbers;
    SET @i = @@ROWCOUNT;
END
GO

SELECT COUNT(*) FROM Numbers AS RowCownt --1048576 rows

Method 2

IF OBJECT_ID('dbo.Numbers', 'U') IS NOT NULL
    DROP TABLE dbo.Numbers
GO

CREATE TABLE dbo.Numbers (Number int NOT NULL PRIMARY KEY);
GO

DECLARE @i INT = 0; 
INSERT INTO dbo.Numbers (Number) 
VALUES (1);

WHILE @i <= 9
BEGIN
    INSERT INTO dbo.Numbers (Number)
    SELECT N.Number + POWER(4, @i) * D.Digit 
    FROM dbo.Numbers AS N
        CROSS JOIN (VALUES(1),(2),(3)) AS D(Digit)
    ORDER BY D.Digit, N.Number
    SET @i = @i + 1;
END
GO

SELECT COUNT(*) FROM dbo.Numbers AS RowCownt --1048576 rows

Method 3

IF OBJECT_ID('dbo.Numbers', 'U') IS NOT NULL
    DROP TABLE dbo.Numbers
GO

CREATE TABLE Numbers (Number int identity NOT NULL PRIMARY KEY, T bit NULL);

WITH
    T1(T) AS (SELECT T FROM (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10)) AS T(T)) --10 rows
   ,T2(T) AS (SELECT A.T FROM T1 AS A CROSS JOIN T1 AS B CROSS JOIN T1 AS C) --1,000 rows
   ,T3(T) AS (SELECT A.T FROM T2 AS A CROSS JOIN T2 AS B CROSS JOIN T2 AS C) --1,000,000,000 rows

INSERT INTO dbo.Numbers(T)
SELECT TOP (1048576) NULL
FROM T3;

ALTER TABLE Numbers
    DROP COLUMN T; 
GO

SELECT COUNT(*) FROM dbo.Numbers AS RowCownt --1048576 rows

Method 4, taken from Defensive Database Programming book by Alex Kuznetsov

IF OBJECT_ID('dbo.Numbers', 'U') IS NOT NULL
    DROP TABLE dbo.Numbers
GO

CREATE TABLE Numbers (Number int NOT NULL PRIMARY KEY);
GO

DECLARE @i INT = 1 ; 
INSERT INTO dbo.Numbers (Number) 
VALUES (1);

WHILE @i < 524289 --1048576
BEGIN; 
    INSERT INTO dbo.Numbers (Number) 
    SELECT Number + @i 
    FROM dbo.Numbers; 
    SET @i = @i * 2 ; 
END
GO

SELECT COUNT(*) FROM dbo.Numbers AS RowCownt --1048576 rows

Method 5, taken from Arrays and Lists in SQL Server 2005 and Beyond article by Erland Sommarskog

IF OBJECT_ID('dbo.Numbers', 'U') IS NOT NULL
    DROP TABLE dbo.Numbers
GO

CREATE TABLE Numbers (Number int NOT NULL PRIMARY KEY);
GO

WITH digits (d) AS (
   SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
   SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL
   SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9 UNION ALL
   SELECT 0)
INSERT INTO Numbers (Number)
   SELECT Number
   FROM   (SELECT i.d + ii.d * 10 + iii.d * 100 + iv.d * 1000 +
                  v.d * 10000 + vi.d * 100000 AS Number
           FROM   digits i
           CROSS  JOIN digits ii
           CROSS  JOIN digits iii
           CROSS  JOIN digits iv
           CROSS  JOIN digits v
           CROSS  JOIN digits vi) AS Numbers
   WHERE  Number > 0
GO

SELECT COUNT(*) FROM dbo.Numbers AS RowCownt --999999 rows

Summary:
Among those 5 methods, method 3 seems to be the fastest.

Joining pandas dataframes by column names

you can use the left_on and right_on options as follows:

pd.merge(frame_1, frame_2, left_on='county_ID', right_on='countyid')

I was not sure from the question if you only wanted to merge if the key was in the left hand dataframe. If that is the case then the following will do that (the above will in effect do a many to many merge)

pd.merge(frame_1, frame_2, how='left', left_on='county_ID', right_on='countyid')

VBA equivalent to Excel's mod function

My way to replicate Excel's MOD(a,b) in VBA is to use XLMod(a,b) in VBA where you include the function:

Function XLMod(a, b)
    ' This replicates the Excel MOD function
    XLMod = a - b * Int(a / b)
End Function

in your VBA Module

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

Happened to me on node 13.7.0 and npm 6.13.6 (macOS Mojave).

I had the following as part of my errors:

found X vulnerabilities (Y moderate, Z high)
  run `npm audit fix` to fix them, or `npm audit` for details

And running the following fixed the problem:

  1. $ npm audit fix

  2. $ npm install

Shell script to set environment variables

Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.

Meanwhile you have to use double quotes not single quote to expand variables:

export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"

Semicolons at the end of a single command are also unnecessary.

So far:

#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...

For su you can run it with:

su -c 'sh /path/to/script.sh'

Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using . or source from the interactive shell. It could have been a standalone scipt, or it could have been source'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

How can I check if a MySQL table exists with PHP?

$res = mysql_query("SELECT table_name FROM information_schema.tables WHERE table_schema = '$databasename' AND table_name = '$tablename';");

If no records are returned then it doesn't exist.

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

Plot inline or a separate window using Matplotlib in Spyder IDE

type

%matplotlib qt

when you want graphs in a separate window and

%matplotlib inline

when you want an inline plot

How to implement "Access-Control-Allow-Origin" header in asp.net

From enable-cors.org:

CORS on ASP.NET

If you don't have access to configure IIS, you can still add the header through ASP.NET by adding the following line to your source pages:

Response.AppendHeader("Access-Control-Allow-Origin", "*");

See also: Configuring IIS6 / IIS7

Deleting queues in RabbitMQ

If you do not care about the data in management database; i.e. users, vhosts, messages etc., and neither about other queues, then you can reset via commandline by running the following commands in order:

WARNING: In addition to the queues, this will also remove any users and vhosts, you have configured on your RabbitMQ server; and will delete any persistent messages

rabbitmqctl stop_app
rabbitmqctl reset
rabbitmqctl start_app

The rabbitmq documentation says that the reset command:

Returns a RabbitMQ node to its virgin state.

Removes the node from any cluster it belongs to, removes all data from the management database, such as configured users and vhosts, and deletes all persistent messages.

So, be careful using it.

How to set app icon for Electron / Atom Shell App

If you want to update the app icon in the taskbar, then Update following in main.js (if using typescript then main.ts)

win.setIcon(path.join(__dirname, '/src/assets/logo-small.png'));

__dirname points to the root directory (same directory as package.json) of your application.

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

How to remove specific elements in a numpy array

A Numpy array is immutable, meaning you technically cannot delete an item from it. However, you can construct a new array without the values you don't want, like this:

b = np.delete(a, [2,3,6])

PHP function to generate v4 UUID

Anyone using composer dependencies, you might want to consider this library: https://github.com/ramsey/uuid

It doesn't get any easier than this:

Uuid::uuid4();

powershell mouse move does not prevent idle mode

The solution from the blog Prevent desktop lock or screensaver with PowerShell is working for me. Here is the relevant script, which simply sends a single period to the shell:

param($minutes = 60)

$myshell = New-Object -com "Wscript.Shell"

for ($i = 0; $i -lt $minutes; $i++) {
  Start-Sleep -Seconds 60
  $myshell.sendkeys(".")
}

and an alternative from the comments, which moves the mouse a single pixel:

$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) + 1) , $Pos.Y)
$Pos = [System.Windows.Forms.Cursor]::Position
[System.Windows.Forms.Cursor]::Position = New-Object System.Drawing.Point((($Pos.X) - 1) , $Pos.Y)

How do I detect if software keyboard is visible on Android Device or not?

Here is a workaround to know if softkeyboard is visible.

  1. Check for running services on the system using ActivityManager.getRunningServices(max_count_of_services);
  2. From the returned ActivityManager.RunningServiceInfo instances, check clientCount value for soft keyboard service.
  3. The aforementioned clientCount will be incremented every time, the soft keyboard is shown. For example, if clientCount was initially 1, it would be 2 when the keyboard is shown.
  4. On keyboard dismissal, clientCount is decremented. In this case, it resets to 1.

Some of the popular keyboards have certain keywords in their classNames:

  1. Google AOSP = IME
  2. Swype = IME
  3. Swiftkey = KeyboardService
  4. Fleksy = keyboard
  5. Adaptxt = IME (KPTAdaptxtIME)
  6. Smart = Keyboard (SmartKeyboard)

From ActivityManager.RunningServiceInfo, check for the above patterns in ClassNames. Also, ActivityManager.RunningServiceInfo's clientPackage=android, indicating that the keyboard is bound to system.

The above mentioned information could be combined for a strict way to find out if soft keyboard is visible.

How do I suspend painting for a control and its children?

Based on ng5000's answer, I like using this extension:

        #region Suspend
        [DllImport("user32.dll")]
        private static extern int SendMessage(IntPtr hWnd, Int32 wMsg, bool wParam, Int32 lParam);
        private const int WM_SETREDRAW = 11;
        public static IDisposable BeginSuspendlock(this Control ctrl)
        {
            return new suspender(ctrl);
        }
        private class suspender : IDisposable
        {
            private Control _ctrl;
            public suspender(Control ctrl)
            {
                this._ctrl = ctrl;
                SendMessage(this._ctrl.Handle, WM_SETREDRAW, false, 0);
            }
            public void Dispose()
            {
                SendMessage(this._ctrl.Handle, WM_SETREDRAW, true, 0);
                this._ctrl.Refresh();
            }
        }
        #endregion

Use:

using (this.BeginSuspendlock())
{
    //update GUI
}

Loading another html page from javascript

You can use the following code :

<!DOCTYPE html>
<html>
    <body onLoad="triggerJS();">

    <script>
        function triggerJS(){
        location.replace("http://www.google.com");
        /*
        location.assign("New_WebSite_Url");
        //Use assign() instead of replace if you want to have the first page in the history (i.e if you want the user to be able to navigate back when New_WebSite_Url is loaded)
        */
        }
    </script>

    </body>
</html>

What are the rules for JavaScript's automatic semicolon insertion (ASI)?

Straight from the ECMA-262, Fifth Edition ECMAScript Specification:

7.9.1 Rules of Automatic Semicolon Insertion

There are three basic rules of semicolon insertion:

  1. When, as the program is parsed from left to right, a token (called the offending token) is encountered that is not allowed by any production of the grammar, then a semicolon is automatically inserted before the offending token if one or more of the following conditions is true:
    • The offending token is separated from the previous token by at least one LineTerminator.
    • The offending token is }.
  2. When, as the program is parsed from left to right, the end of the input stream of tokens is encountered and the parser is unable to parse the input token stream as a single complete ECMAScript Program, then a semicolon is automatically inserted at the end of the input stream.
  3. When, as the program is parsed from left to right, a token is encountered that is allowed by some production of the grammar, but the production is a restricted production and the token would be the first token for a terminal or nonterminal immediately following the annotation "[no LineTerminator here]" within the restricted production (and therefore such a token is called a restricted token), and the restricted token is separated from the previous token by at least one LineTerminator, then a semicolon is automatically inserted before the restricted token.

However, there is an additional overriding condition on the preceding rules: a semicolon is never inserted automatically if the semicolon would then be parsed as an empty statement or if that semicolon would become one of the two semicolons in the header of a for statement (see 12.6.3).

Does List<T> guarantee insertion order?

The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.

According to MSDN:

...List "Represents a strongly typed list of objects that can be accessed by index."

The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.

You might be getting odd results from your code if you're moving the item later in the list, as your Remove() will move all of the other items down one place before the call to Insert().

Can you boil your code down to something small enough to post?

How do I change the font color in an html table?

table td{
  color:#0000ff;
}

<table>
  <tbody>
    <tr>
    <td>
      <select name="test">
        <option value="Basic">Basic : $30.00 USD - yearly</option>
        <option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
        <option value="Supporting">Supporting : $120.00 USD - yearly</option>
      </select>
    </td>
    </tr>
  </tbody>
</table>

How do I set up Android Studio to work completely offline?

Not sure if it was removed before, I heard it was kinda buggy in 0.5.8 but in AS 0.5.9 the settings is there:

Gradle > Global Gradle settings > Offline work

REST API Login Pattern

Principled Design of the Modern Web Architecture by Roy T. Fielding and Richard N. Taylor, i.e. sequence of works from all REST terminology came from, contains definition of client-server interaction:

All REST interactions are stateless. That is, each request contains all of the information necessary for a connector to understand the request, independent of any requests that may have preceded it.

This restriction accomplishes four functions, 1st and 3rd are important in this particular case:

  • 1st: it removes any need for the connectors to retain application state between requests, thus reducing consumption of physical resources and improving scalability;
  • 3rd: it allows an intermediary to view and understand a request in isolation, which may be necessary when services are dynamically rearranged;

And now lets go back to your security case. Every single request should contains all required information, and authorization/authentication is not an exception. How to achieve this? Literally send all required information over wires with every request.

One of examples how to archeive this is hash-based message authentication code or HMAC. In practice this means adding a hash code of current message to every request. Hash code calculated by cryptographic hash function in combination with a secret cryptographic key. Cryptographic hash function is either predefined or part of code-on-demand REST conception (for example JavaScript). Secret cryptographic key should be provided by server to client as resource, and client uses it to calculate hash code for every request.

There are a lot of examples of HMAC implementations, but I'd like you to pay attention to the following three:

How it works in practice

If client knows the secret key, then it's ready to operate with resources. Otherwise he will be temporarily redirected (status code 307 Temporary Redirect) to authorize and to get secret key, and then redirected back to the original resource. In this case there is no need to know beforehand (i.e. hardcode somewhere) what the URL to authorize the client is, and it possible to adjust this schema with time.

Hope this will helps you to find the proper solution!

Two Radio Buttons ASP.NET C#

I can see it's an old question, if you want to put other HTML inside could use the radiobutton with GroupName propery same in all radiobuttons and in the Text property set something like an image or the html you need.

   <asp:RadioButton GroupName="group1" runat="server" ID="paypalrb" Text="<img src='https://www.paypalobjects.com/webstatic/mktg/logo/bdg_secured_by_pp_2line.png' border='0' alt='Secured by PayPal' style='width: 103px; height: 61px; padding:10px;'>" />

Tesseract OCR simple example

I was able to get it to work by following these instructions.

  • Download the sample code Tesseract sample code

  • Unzip it to a new location

  • Open ~\tesseract-samples-master\src\Tesseract.Samples.sln (I used Visual Studio 2017)

  • Install the Tesseract NuGet package for that project (or uninstall/reinstall as I had to) NuGet Tesseract

  • Uncomment the last two meaningful lines in Tesseract.Samples.Program.cs: Console.Write("Press any key to continue . . . "); Console.ReadKey(true);

  • Run (hit F5)

  • You should get this windows console output enter image description here

Beginner Python: AttributeError: 'list' object has no attribute

They are lists because you type them as lists in the dictionary:

bikes = {
    # Bike designed for children"
    "Trike": ["Trike", 20, 100],
    # Bike designed for everyone"
    "Kruzer": ["Kruzer", 50, 165]
    }

You should use the bike-class instead:

bikes = {
    # Bike designed for children"
    "Trike": Bike("Trike", 20, 100),
    # Bike designed for everyone"
    "Kruzer": Bike("Kruzer", 50, 165)
    }

This will allow you to get the cost of the bikes with bike.cost as you were trying to.

for bike in bikes.values():
    profit = bike.cost * margin
    print(bike.name + " : " + str(profit))

This will now print:

Kruzer : 33.0
Trike : 20.0

(Built-in) way in JavaScript to check if a string is a valid number

If anyone ever gets this far down, I spent some time hacking on this trying to patch moment.js (https://github.com/moment/moment). Here's something that I took away from it:

function isNumeric(val) {
    var _val = +val;
    return (val !== val + 1) //infinity check
        && (_val === +val) //Cute coercion check
        && (typeof val !== 'object') //Array/object check
}

Handles the following cases:

True! :

isNumeric("1"))
isNumeric(1e10))
isNumeric(1E10))
isNumeric(+"6e4"))
isNumeric("1.2222"))
isNumeric("-1.2222"))
isNumeric("-1.222200000000000000"))
isNumeric("1.222200000000000000"))
isNumeric(1))
isNumeric(0))
isNumeric(-0))
isNumeric(1010010293029))
isNumeric(1.100393830000))
isNumeric(Math.LN2))
isNumeric(Math.PI))
isNumeric(5e10))

False! :

isNumeric(NaN))
isNumeric(Infinity))
isNumeric(-Infinity))
isNumeric())
isNumeric(undefined))
isNumeric('[1,2,3]'))
isNumeric({a:1,b:2}))
isNumeric(null))
isNumeric([1]))
isNumeric(new Date()))

Ironically, the one I am struggling with the most:

isNumeric(new Number(1)) => false

Any suggestions welcome. :]

Is it possible to remove inline styles with jQuery?

Update: while the following solution works, there's a much easier method. See below.


Here's what I came up with, and I hope this comes in handy - to you or anybody else:

$('#element').attr('style', function(i, style)
{
    return style && style.replace(/display[^;]+;?/g, '');
});

This will remove that inline style.

I'm not sure this is what you wanted. You wanted to override it, which, as pointed out already, is easily done by $('#element').css('display', 'inline').

What I was looking for was a solution to REMOVE the inline style completely. I need this for a plugin I'm writing where I have to temporarily set some inline CSS values, but want to later remove them; I want the stylesheet to take back control. I could do it by storing all of its original values and then putting them back inline, but this solution feels much cleaner to me.


Here it is in plugin format:

(function($)
{
    $.fn.removeStyle = function(style)
    {
        var search = new RegExp(style + '[^;]+;?', 'g');

        return this.each(function()
        {
            $(this).attr('style', function(i, style)
            {
                return style && style.replace(search, '');
            });
        });
    };
}(jQuery));

If you include this plugin in the page before your script, you can then just call

$('#element').removeStyle('display');

and that should do the trick.


Update: I now realized that all this is futile. You can simply set it to blank:

$('#element').css('display', '');

and it'll automatically be removed for you.

Here's a quote from the docs:

Setting the value of a style property to an empty string — e.g. $('#mydiv').css('color', '') — removes that property from an element if it has already been directly applied, whether in the HTML style attribute, through jQuery's .css() method, or through direct DOM manipulation of the style property. It does not, however, remove a style that has been applied with a CSS rule in a stylesheet or <style> element.

I don't think jQuery is doing any magic here; it seems the style object does this natively.

How can I limit the visible options in an HTML <select> dropdown?

You can use the size attribute to make the <select> appear as a box instead of a dropdown. The number you use in the size attribute defines how many options are visible in the box without scrolling.

<select size="5">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>4</option>
    <option>5</option>
    <option>6</option>
    <option>7</option>
    <option>8</option>
    <option>9</option>
    <option>10</option>
    <option>11</option>
    <option>12</option>
</select>

You can’t apply this to a <select> and have it still appear as a drop-down list though. The browser/operating system will decide how many options should be displayed for drop-down lists, unless you use HTML, CSS and JavaScript to create a fake dropdown list.

Problem with converting int to string in Linq to entities

Using MySql, the SqlFunctions.StringConvert didn't work for me. Since I use SelectListItem in 20+ places in my project, I wanted a solution that work without contorting the 20+ LINQ statements. My solution was to sub-class SelectedListItem in order to provide an integer setter, which moves type conversion away from LINQ. Obviously, this solution is difficult to generalize, but was quite helpful for my specific project.

To use, create the following type and use in your LINQ query in place of SelectedListItem and use IntValue in place of Value.

public class BtoSelectedListItem : SelectListItem
{
    public int IntValue
    {
        get { return string.IsNullOrEmpty(Value) ? 0 : int.Parse(Value); }
        set { Value = value.ToString(); }
    }
}

How to set HttpResponse timeout for Android in Java

In my example, two timeouts are set. The connection timeout throws java.net.SocketTimeoutException: Socket is not connected and the socket timeout java.net.SocketTimeoutException: The operation timed out.

HttpGet httpGet = new HttpGet(url);
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used. 
int timeoutConnection = 3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT) 
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
HttpResponse response = httpClient.execute(httpGet);

If you want to set the Parameters of any existing HTTPClient (e.g. DefaultHttpClient or AndroidHttpClient) you can use the function setParams().

httpClient.setParams(httpParameters);

Gnuplot line types

Until version 4.6

The dash type of a linestyle is given by the linetype, which does also select the line color unless you explicitely set an other one with linecolor.

However, the support for dashed lines depends on the selected terminal:

  1. Some terminals don't support dashed lines, like png (uses libgd)
  2. Other terminals, like pngcairo, support dashed lines, but it is disables by default. To enable it, use set termoption dashed, or set terminal pngcairo dashed ....
  3. The exact dash patterns differ between terminals. To see the defined linetype, use the test command:

Running

set terminal pngcairo dashed
set output 'test.png'
test
set output

gives:

enter image description here

whereas, the postscript terminal shows different dash patterns:

set terminal postscript eps color colortext
set output 'test.eps'
test
set output

enter image description here

Version 5.0

Starting with version 5.0 the following changes related to linetypes, dash patterns and line colors are introduced:

  • A new dashtype parameter was introduced:

    To get the predefined dash patterns, use e.g.

    plot x dashtype 2
    

    You can also specify custom dash patterns like

    plot x dashtype (3,5,10,5),\
         2*x dashtype '.-_'
    
  • The terminal options dashed and solid are ignored. By default all lines are solid. To change them to dashed, use e.g.

    set for [i=1:8] linetype i dashtype i
    
  • The default set of line colors was changed. You can select between three different color sets with set colorsequence default|podo|classic:

enter image description here

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

You're looking for the MemoryStream.Write method.

For example, the following code will write the contents of a byte[] array into a memory stream:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream();
stream.Write(myByteArray, 0, myByteArray.Length);

Alternatively, you could create a new, non-resizable MemoryStream object based on the byte array:

byte[] myByteArray = new byte[10];
MemoryStream stream = new MemoryStream(myByteArray);

How can I split a text file using PowerShell?

Sounds like a job for the UNIX command split:

split MyBigFile.csv

Just split my 55 GB csv file in 21k chunks in less than 10 minutes.

It's not native to PowerShell though, but comes with, for instance, the git for windows package https://git-scm.com/download/win

Break string into list of characters in Python

In python many things are iterable including files and strings. Iterating over a filehandler gives you a list of all the lines in that file. Iterating over a string gives you a list of all the characters in that string.

charsFromFile = []
filePath = r'path\to\your\file.txt' #the r before the string lets us use backslashes

for line in open(filePath):
    for char in line:
        charsFromFile.append(char) 
        #apply code on each character here

or if you want a one liner

#the [0] at the end is the line you want to grab.
#the [0] can be removed to grab all lines
[list(a) for a in list(open('test.py'))][0]  

.

.

Edit: as agf mentions you can use itertools.chain.from_iterable

His method is better, unless you want the ability to specify which lines to grab list(itertools.chain.from_iterable(open(filename, 'rU)))

This does however require one to be familiar with itertools, and as a result looses some readablity

If you only want to iterate over the chars, and don't care about storing a list, then I would use the nested for loops. This method is also the most readable.

angular2: Error: TypeError: Cannot read property '...' of undefined

Safe navigation operator or Existential Operator or Null Propagation Operator is supported in Angular Template. Suppose you have Component class

  myObj:any = {
    doSomething: function () { console.log('doing something'); return 'doing something'; },
  };
  myArray:any;
  constructor() { }

  ngOnInit() {
    this.myArray = [this.myObj];
  }

You can use it in template html file as following:

<div>test-1: {{  myObj?.doSomething()}}</div>
<div>test-2: {{  myArray[0].doSomething()}}</div>
<div>test-3: {{  myArray[2]?.doSomething()}}</div>

print spaces with String.format()

You need to specify the minimum width of the field.

String.format("%" + numberOfSpaces + "s", ""); 

Why do you want to generate a String of spaces of a certain length.

If you want a column of this length with values then you can do:

String.format("%" + numberOfSpaces + "s", "Hello"); 

which gives you numberOfSpaces-5 spaces followed by Hello. If you want Hello to appear on the left then add a minus sign in before numberOfSpaces.

JQuery add class to parent element

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

sort csv by column

To sort by MULTIPLE COLUMN (Sort by column_1, and then sort by column_2)

with open('unsorted.csv',newline='') as csvfile:
    spamreader = csv.DictReader(csvfile, delimiter=";")
    sortedlist = sorted(spamreader, key=lambda row:(row['column_1'],row['column_2']), reverse=False)


with open('sorted.csv', 'w') as f:
    fieldnames = ['column_1', 'column_2', column_3]
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    for row in sortedlist:
        writer.writerow(row)

Take n rows from a spark dataframe and pass to toPandas()

Try it:

def showDf(df, count=None, percent=None, maxColumns=0):
    if (df == None): return
    import pandas
    from IPython.display import display
    pandas.set_option('display.encoding', 'UTF-8')
    # Pandas dataframe
    dfp = None
    # maxColumns param
    if (maxColumns >= 0):
        if (maxColumns == 0): maxColumns = len(df.columns)
        pandas.set_option('display.max_columns', maxColumns)
    # count param
    if (count == None and percent == None): count = 10 # Default count
    if (count != None):
        count = int(count)
        if (count == 0): count = df.count()
        pandas.set_option('display.max_rows', count)
        dfp = pandas.DataFrame(df.head(count), columns=df.columns)
        display(dfp)
    # percent param
    elif (percent != None):
        percent = float(percent)
        if (percent >=0.0 and percent <= 1.0):
            import datetime
            now = datetime.datetime.now()
            seed = long(now.strftime("%H%M%S"))
            dfs = df.sample(False, percent, seed)
            count = df.count()
            pandas.set_option('display.max_rows', count)
            dfp = dfs.toPandas()    
            display(dfp)

Examples of usages are:

# Shows the ten first rows of the Spark dataframe
showDf(df)
showDf(df, 10)
showDf(df, count=10)

# Shows a random sample which represents 15% of the Spark dataframe
showDf(df, percent=0.15) 

In Rails, how do you render JSON using a view?

Just add show.json.erb file with the contents

<%= @user.to_json %>

Sometimes it is useful when you need some extra helper methods that are not available in controller, i.e. image_path(@user.avatar) or something to generate additional properties in JSON:

<%= @user.attributes.merge(:avatar => image_path(@user.avatar)).to_json %>

How to split a string into a list?

I want my python function to split a sentence (input) and store each word in a list

The str().split() method does this, it takes a string, splits it into a list:

>>> the_string = "this is a sentence"
>>> words = the_string.split(" ")
>>> print(words)
['this', 'is', 'a', 'sentence']
>>> type(words)
<type 'list'> # or <class 'list'> in Python 3.0

The problem you're having is because of a typo, you wrote print(words) instead of print(word):

Renaming the word variable to current_word, this is what you had:

def split_line(text):
    words = text.split()
    for current_word in words:
        print(words)

..when you should have done:

def split_line(text):
    words = text.split()
    for current_word in words:
        print(current_word)

If for some reason you want to manually construct a list in the for loop, you would use the list append() method, perhaps because you want to lower-case all words (for example):

my_list = [] # make empty list
for current_word in words:
    my_list.append(current_word.lower())

Or more a bit neater, using a list-comprehension:

my_list = [current_word.lower() for current_word in words]

What's causing my java.net.SocketException: Connection reset?

FWIW, I was getting this error when I was accidentally making a GET request to an endpoint that was expecting a POST request. Presumably that was just that particular servers way of handling the problem.

Undefined reference to pthread_create in Linux

I believe the proper way of adding pthread in CMake is with the following

find_package (Threads REQUIRED)

target_link_libraries(helloworld
    ${CMAKE_THREAD_LIBS_INIT}
)

Simple Popup by using Angular JS

If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.

Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">

      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>

    </div>
  </div>

</div>

</body>
</html>

PHP Header redirect not working

Don't include header.php. You should not output HTML when you are going to redirect.

Make a new file, eg. "pre.php". Put this in it:

<?php
include('class.user.php');
include('class.Connection.php');
?>

Then in header.php, include that, in stead of including the two other files. In form.php, include pre.php in stead of header.php.

How do I prevent 'git diff' from using a pager?

By default git uses uses less as pager. I normally prefer more, as it will print the first page and then allow you to scroll through the content.

Further, the content will remain in the console when done. This is usually convenient, as you often want to do something with the content after lookup (eg. email the commiter and tell him he introduced a bug in his last commit).

If you then want to pipe content, it would be inconvenient to scroll to print everything. The good thing with more is you will be able to combine it with pipeline and it will pipe through everything, eg.

# Find the commit abcdef123 in the full commit history and read author and commit message
git log |grep -C 5 'abcdef123'

Basically more is all you would ever need, unless you do not want the content to remain in the console when done. To use more instead, do as below.

git config --global core.pager 'more'

How do I disable directory browsing?

To complete @GauravKachhadiya's answer :

IndexIgnore *.jpg

means "hide only .jpg extension files from indexing.

IndexIgnore directive uses wildcard expression to match against directories and files.

  • a star character , it matches any charactes in a string ,eg : foo or foo.extension, in the following example, we are going to turn off the directory listing, no files or dirs will appear in the index :

    IndexIgnore *

Or if you want to hide spacific files , in the directory listing, then we can use

IndexIgnore *.php

*.php => matches a string that starts with any char and ends with .php

The example above hides all files that end with .php

How to get attribute of element from Selenium?

Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");

R define dimensions of empty data frame

You may use NULL instead of NA. This creates a truly empty data frame.

Center an element in Bootstrap 4 Navbar

In Bootstrap 4, there is a new utility known as .mx-auto. You just need to specify the width of the centered element.

Ref: http://v4-alpha.getbootstrap.com/utilities/spacing/#horizontal-centering

Diffferent from Bass Jobsen's answer, which is a relative center to the elements on both ends, the following example is absolute centered.

Here's the HTML:

<nav class="navbar bg-faded">
  <div class="container">
    <ul class="nav navbar-nav pull-sm-left">
      <li class="nav-item">
        <a class="nav-link" href="#">Link 1</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 2</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 3</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 4</a>
      </li>
    </ul>
    <ul class="nav navbar-nav navbar-logo mx-auto">
      <li class="nav-item">
        <a class="nav-link" href="#">Brand</a>
      </li>
    </ul>
    <ul class="nav navbar-nav pull-sm-right">
      <li class="nav-item">
        <a class="nav-link" href="#">Link 5</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link 6</a>
      </li>
    </ul>
  </div>
</nav>

And CSS:

.navbar-logo {
  width: 90px;
}

jQuery set checkbox checked

This works.

 $("div.row-form input[type='checkbox']").attr('checked','checked');

Split (explode) pandas dataframe string entry to separate rows

The string function split can take an option boolean argument 'expand'.

Here is a solution using this argument:

(a.var1
  .str.split(",",expand=True)
  .set_index(a.var2)
  .stack()
  .reset_index(level=1, drop=True)
  .reset_index()
  .rename(columns={0:"var1"}))

How do I make XAML DataGridColumns fill the entire DataGrid?

Make sure your DataGrid has Width set to something like {Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window,AncestorLevel=1}}.

Like that, your setting of Width="*" attribute on DataGrid.Columns/DataGridXXXXColumn elements should work.

vertical-align: middle with Bootstrap 2

i use this

<style>
html, body{height:100%;margin:0;padding:0 0} 
.container-fluid{height:100%;display:table;width:100%;padding-right:0;padding-left: 0}   
.row-fluid{height:100%;display:table-cell;vertical-align:middle;width:100%}
.centering{float:none;margin:0 auto} 
</style>
<body>
<div class="container-fluid">
     <div class="row-fluid">
     <div class="offset3 span6 centering">
            content here
         </div>
    </div>
 </div>
</body>

PHP: HTML: send HTML select option attribute in POST

You can use jquery function.

<form name='add'>
   <input type='text' name='stud_name' id="stud_name" value=""/>
   Age: <select name='age' id="age">
   <option value='1' stud_name='sre'>23</option>
   <option value='2' stud_name='sam'>24</option>
   <option value='5' stud_name='john'>25</option>
   </select>
   <input type='submit' name='submit'/>
</form>

jquery code :

<script type="text/javascript" src="jquery.js"></script>

<script>
    $(function() {
          $("#age").change(function(){
          var option = $('option:selected', this).attr('stud_name');
          $('#stud_name').val(option);
       });
    });
</script>

CSS3 animate border color

You can use a CSS3 transition for this. Have a look at this example:

http://jsfiddle.net/ujDkf/1/

Here is the main code:

#box {
  position : relative;
  width : 100px;
  height : 100px;
  background-color : gray;
  border : 5px solid black;
  -webkit-transition : border 500ms ease-out;
  -moz-transition : border 500ms ease-out;
  -o-transition : border 500ms ease-out;
  transition : border 500ms ease-out;
}

#box:hover {
   border : 10px solid red;   
}

How to use Git?

this is my blog on git and its for beginners who want to get started on git. https://techxposers.com/git-for-beginners/

Convert image from PIL to openCV format

The code commented works as well, just choose which do you prefer

import numpy as np
from PIL import Image


def convert_from_cv2_to_image(img: np.ndarray) -> Image:
    # return Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    return Image.fromarray(img)


def convert_from_image_to_cv2(img: Image) -> np.ndarray:
    # return cv2.cvtColor(numpy.array(img), cv2.COLOR_RGB2BGR)
    return np.asarray(img)

How to open the second form?

I assume your talking about windows forms:

To display your form use the Show() method:

Form form2 = new Form();
form2.Show();

to close the form use Close():

form2.Close();

Import Certificate to Trusted Root but not to Personal [Command Line]

The below 'd help you to add the cert to the Root Store-

certutil -enterprise -f -v -AddStore "Root" <Cert File path>

This worked for me perfectly.

How to use external ".js" files

In your head element add

<script type="text/javascript" src="myscript.js"></script>

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

If you need to override IE's Compatibility View Settings for intranet sites you can do so in the web.config (IIS7) or through the custom HTTP headers in the web site's properties (IIS6) and set X-UA-Compatible there. The meta tag doesn't override IE's intranet setting in Compatibility View Settings, but if you set it at the hosting server it will override the compatibility.

Example for web.config in IIS7:

<system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="X-UA-Compatible" value="IE=EmulateIE8" />
      </customHeaders>
    </httpProtocol>
</system.webServer>

Edit: I removed the clear code from just before the add; it was an unnecessary oversight from copying and pasting. Good catch, commenters!

How to convert JSON to a Ruby hash

I'm surprised nobody pointed out JSON's [] method, which makes it very easy and transparent to decode and encode from/to JSON.

If object is string-like, parse the string and return the parsed result as a Ruby data structure. Otherwise generate a JSON text from the Ruby data structure object and return it.

Consider this:

require 'json'

hash = {"val":"test","val1":"test1","val2":"test2"} # => {:val=>"test", :val1=>"test1", :val2=>"test2"}
str = JSON[hash] # => "{\"val\":\"test\",\"val1\":\"test1\",\"val2\":\"test2\"}"

str now contains the JSON encoded hash.

It's easy to reverse it using:

JSON[str] # => {"val"=>"test", "val1"=>"test1", "val2"=>"test2"}

Custom objects need to_s defined for the class, and inside it convert the object to a Hash then use to_json on it.

Redeploy alternatives to JRebel

By the Spring guys, used for Grails reloading but works with Java too:

https://github.com/SpringSource/spring-loaded

Return index of greatest value in an array

Here is another solution, If you are using ES6 using spread operator:

var arr = [0, 21, 22, 7];

const indexOfMaxValue = arr.indexOf(Math.max(...arr));

Simple Vim commands you wish you'd known earlier

ZZ (works like :wq)

And about the cursor position: I found that a cursor which always stays in the middle of screen is cool -

set scrolloff=9999

Extract data from XML Clob using SQL from Oracle Database

This should work

SELECT EXTRACTVALUE(column_name, '/DCResponse/ContextData/Decision') FROM traptabclob;

I have assumed the ** were just for highlighting?

How to format number of decimal places in wpf using style/template?

The accepted answer does not show 0 in integer place on giving input like 0.299. It shows .3 in WPF UI. So my suggestion to use following string format

<TextBox Text="{Binding Value,  StringFormat={}{0:#,0.0}}" 

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

See if you can recreate the issue in an Incognito tab. If you find that the problem no longer occurs then I would recommend you go through your extensions, perhaps disabling them one at a time. This is commonly the cause as touched on by Nikola

What is the purpose of willSet and didSet in Swift?

My understanding is that set and get are for computed properties (no backing from stored properties)

if you are coming from an Objective-C bare in mind that the naming conventions have changed. In Swift an iVar or instance variable is named stored property

Example 1 (read only property) - with warning:

var test : Int {
    get {
        return test
    }
}

This will result in a warning because this results in a recursive function call (the getter calls itself).The warning in this case is "Attempting to modify 'test' within its own getter".

Example 2. Conditional read/write - with warning

var test : Int {
    get {
        return test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        //(prevents same value being set)
        if (aNewValue != test) {
            test = aNewValue
        }
    }
}

Similar problem - you cannot do this as it's recursively calling the setter. Also, note this code will not complain about no initialisers as there is no stored property to initialise.

Example 3. read/write computed property - with backing store

Here is a pattern that allows conditional setting of an actual stored property

//True model data
var _test : Int = 0

var test : Int {
    get {
        return _test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        if (aNewValue != test) {
            _test = aNewValue
        }
    }
}

Note The actual data is called _test (although it could be any data or combination of data) Note also the need to provide an initial value (alternatively you need to use an init method) because _test is actually an instance variable

Example 4. Using will and did set

//True model data
var _test : Int = 0 {

    //First this
    willSet {
        println("Old value is \(_test), new value is \(newValue)")
    }

    //value is set

    //Finaly this
    didSet {
        println("Old value is \(oldValue), new value is \(_test)")
    }
}

var test : Int {
    get {
        return _test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        if (aNewValue != test) {
            _test = aNewValue
        }
    }
}

Here we see willSet and didSet intercepting a change in an actual stored property. This is useful for sending notifications, synchronisation etc... (see example below)

Example 5. Concrete Example - ViewController Container

//Underlying instance variable (would ideally be private)
var _childVC : UIViewController? {
    willSet {
        //REMOVE OLD VC
        println("Property will set")
        if (_childVC != nil) {
            _childVC!.willMoveToParentViewController(nil)
            self.setOverrideTraitCollection(nil, forChildViewController: _childVC)
            _childVC!.view.removeFromSuperview()
            _childVC!.removeFromParentViewController()
        }
        if (newValue) {
            self.addChildViewController(newValue)
        }

    }

    //I can't see a way to 'stop' the value being set to the same controller - hence the computed property

    didSet {
        //ADD NEW VC
        println("Property did set")
        if (_childVC) {
//                var views  = NSDictionaryOfVariableBindings(self.view)    .. NOT YET SUPPORTED (NSDictionary bridging not yet available)

            //Add subviews + constraints
            _childVC!.view.setTranslatesAutoresizingMaskIntoConstraints(false)       //For now - until I add my own constraints
            self.view.addSubview(_childVC!.view)
            let views = ["view" : _childVC!.view] as NSMutableDictionary
            let layoutOpts = NSLayoutFormatOptions(0)
            let lc1 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("|[view]|",  options: layoutOpts, metrics: NSDictionary(), views: views)
            let lc2 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: layoutOpts, metrics: NSDictionary(), views: views)
            self.view.addConstraints(lc1)
            self.view.addConstraints(lc2)

            //Forward messages to child
            _childVC!.didMoveToParentViewController(self)
        }
    }
}


//Computed property - this is the property that must be used to prevent setting the same value twice
//unless there is another way of doing this?
var childVC : UIViewController? {
    get {
        return _childVC
    }
    set(suggestedVC) {
        if (suggestedVC != _childVC) {
            _childVC = suggestedVC
        }
    }
}

Note the use of BOTH computed and stored properties. I've used a computed property to prevent setting the same value twice (to avoid bad things happening!); I've used willSet and didSet to forward notifications to viewControllers (see UIViewController documentation and info on viewController containers)

I hope this helps, and please someone shout if I've made a mistake anywhere here!

Converting int to string in C

Before I continue, I must warn you that itoa is NOT an ANSI function — it's not a standard C function. You should use sprintf to convert an int into a string.

itoa takes three arguments.

  • The first one is the integer to be converted.
  • The second is a pointer to an array of characters - this is where the string is going to be stored. The program may crash if you pass in a char * variable, so you should pass in a normal sized char array and it will work fine.
  • The last one is NOT the size of the array, but it's the BASE of your number - base 10 is the one you're most likely to use.

The function returns a pointer to its second argument — where it has stored the converted string.

itoa is a very useful function, which is supported by some compilers - it's a shame it isn't support by all, unlike atoi.

If you still want to use itoa, here is how should you use it. Otherwise, you have another option using sprintf (as long as you want base 8, 10 or 16 output):

char str[5];
printf("15 in binary is %s\n",  itoa(15, str, 2));

Fastest way to reset every value of std::vector<int> to 0

I had the same question but about rather short vector<bool> (afaik the standard allows to implement it internally differently than just a continuous array of boolean elements). Hence I repeated the slightly modified tests by Fabio Fracassi. The results are as follows (times, in seconds):

            -O0       -O3
         --------  --------
memset     0.666     1.045
fill      19.357     1.066
iterator  67.368     1.043
assign    17.975     0.530
for i     22.610     1.004

So apparently for these sizes, vector<bool>::assign() is faster. The code used for tests:

#include <vector>
#include <cstring>
#include <cstdlib>

#define TEST_METHOD 5
const size_t TEST_ITERATIONS = 34359738;
const size_t TEST_ARRAY_SIZE = 200;

using namespace std;

int main(int argc, char** argv) {

    std::vector<int> v(TEST_ARRAY_SIZE, 0);

    for(size_t i = 0; i < TEST_ITERATIONS; ++i) {
#if TEST_METHOD == 1
        memset(&v[0], false, v.size() * sizeof v[0]);
#elif TEST_METHOD == 2
        std::fill(v.begin(), v.end(), false);
   #elif TEST_METHOD == 3
        for (std::vector<int>::iterator it=v.begin(), end=v.end(); it!=end; ++it) {
            *it = 0;
        }
   #elif TEST_METHOD == 4
      v.assign(v.size(),false);
   #elif TEST_METHOD == 5
      for (size_t i = 0; i < TEST_ARRAY_SIZE; i++) {
          v[i] = false;
      }
#endif
    }

    return EXIT_SUCCESS;
}

I used GCC 7.2.0 compiler on Ubuntu 17.10. The command line for compiling:

g++ -std=c++11 -O0 main.cpp
g++ -std=c++11 -O3 main.cpp

raw vs. html_safe vs. h to unescape html

The best safe way is: <%= sanitize @x %>

It will avoid XSS!

Spring Boot Adding Http Request Interceptors

Since you're using Spring Boot, I assume you'd prefer to rely on Spring's auto configuration where possible. To add additional custom configuration like your interceptors, just provide a configuration or bean of WebMvcConfigurerAdapter.

Here's an example of a config class:

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

  @Autowired 
  HandlerInterceptor yourInjectedInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(...)
    ...
    registry.addInterceptor(getYourInterceptor()); 
    registry.addInterceptor(yourInjectedInterceptor);
    // next two should be avoid -- tightly coupled and not very testable
    registry.addInterceptor(new YourInterceptor());
    registry.addInterceptor(new HandlerInterceptor() {
        ...
    });
  }
}

NOTE do not annotate this with @EnableWebMvc, if you want to keep Spring Boots auto configuration for mvc.

DataGridView checkbox column - value and functionality

If you try it on CellContentClick Event

Use:

dataGridView1.EndEdit();  //Stop editing of cell.
MessageBox.Show("0 = " + dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());

Increasing (or decreasing) the memory available to R processes

From:

http://gking.harvard.edu/zelig/docs/How_do_I2.html (mirror)

Windows users may get the error that R has run out of memory.

If you have R already installed and subsequently install more RAM, you may have to reinstall R in order to take advantage of the additional capacity.

You may also set the amount of available memory manually. Close R, then right-click on your R program icon (the icon on your desktop or in your programs directory). Select ``Properties'', and then select the ``Shortcut'' tab. Look for the ``Target'' field and after the closing quotes around the location of the R executible, add

--max-mem-size=500M

as shown in the figure below. You may increase this value up to 2GB or the maximum amount of physical RAM you have installed.

If you get the error that R cannot allocate a vector of length x, close out of R and add the following line to the ``Target'' field:

--max-vsize=500M

or as appropriate. You can always check to see how much memory R has available by typing at the R prompt

memory.limit()

which gives you the amount of available memory in MB. In previous versions of R you needed to use: round(memory.limit()/2^20, 2).

Hibernate: best practice to pull all lazy collections

Not the best solution, but here is what I got:

1) Annotate getter you want to initialize with this annotation:

@Retention(RetentionPolicy.RUNTIME)
public @interface Lazy {

}

2) Use this method (can be put in a generic class, or you can change T with Object class) on a object after you read it from database:

    public <T> void forceLoadLazyCollections(T entity) {

    Session session = getSession().openSession();
    Transaction tx = null;
    try {

        tx = session.beginTransaction();
        session.refresh(entity);
        if (entity == null) {
            throw new RuntimeException("Entity is null!");
        }
        for (Method m : entityClass.getMethods()) {

            Lazy annotation = m.getAnnotation(Lazy.class);
            if (annotation != null) {
                m.setAccessible(true);
                logger.debug(" method.invoke(obj, arg1, arg2,...); {} field", m.getName());
                try {
                    Hibernate.initialize(m.invoke(entity));
                }
                catch (Exception e) {
                    logger.warn("initialization exception", e);
                }
            }
        }

    }
    finally {
        session.close();
    }
}

How to enable assembly bind failure logging (Fusion) in .NET

I usually use the Fusion Log Viewer (Fuslogvw.exe from a Visual Studio command prompt or Fusion Log Viewer from the start menu) - my standard setup is:

  • Open Fusion Log Viewer as administrator
  • Click settings
  • Check the Enable custom log path checkbox
  • Enter the location you want logs to get written to, for example, c:\FusionLogs (Important: make sure that you have actually created this folder in the file system.)
  • Make sure that the right level of logging is on (I sometimes just select Log all binds to disk just to make sure things are working right)
  • Click OK
  • Set the log location option to Custom

Remember to turn of logging off once you're done!

(I just posted this on a similar question - I think it's relevant here too.)

Set up an HTTP proxy to insert a header

i'd try tinyproxy. in fact, the vey best would be to embedd a scripting language there... sounds like a perfect job for Lua, especially after seeing how well it worked for mysqlproxy

How to send email from SQL Server?

Here's an example of how you might concatenate email addresses from a table into a single @recipients parameter:

CREATE TABLE #emailAddresses (email VARCHAR(25))

INSERT #emailAddresses (email) VALUES ('[email protected]')
INSERT #emailAddresses (email) VALUES ('[email protected]')
INSERT #emailAddresses (email) VALUES ('[email protected]')

DECLARE @recipients VARCHAR(MAX)
SELECT @recipients = COALESCE(@recipients + ';', '') + email 
FROM #emailAddresses

SELECT @recipients

DROP TABLE #emailAddresses

The resulting @recipients will be:

[email protected];[email protected];[email protected]

How do I get the base URL with PHP?

Try the following code :

$config['base_url'] = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on") ? "https" : "http");
$config['base_url'] .= "://".$_SERVER['HTTP_HOST'];
$config['base_url'] .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
echo $config['base_url'];

How do I populate a JComboBox with an ArrayList?

By combining existing answers (this one and this one) the proper type safe way to add an ArrayList to a JComboBox is the following:

private DefaultComboBoxModel<YourClass> getComboBoxModel(List<YourClass> yourClassList)
{
    YourClass[] comboBoxModel = yourClassList.toArray(new YourClass[0]);
    return new DefaultComboBoxModel<>(comboBoxModel);
}

In your GUI code you set the entire list into your JComboBox as follows:

DefaultComboBoxModel<YourClass> comboBoxModel = getComboBoxModel(yourClassList);
comboBox.setModel(comboBoxModel);

LINQ select one field from list of DTO objects to array

This is very simple in LinQ... You can use the select statement to get an Enumerable of properties of the objects.

var mySkus = myLines.Select(x => x.Sku);

Or if you want it as an Array just do...

var mySkus = myLines.Select(x => x.Sku).ToArray();

Twitter Bootstrap 3, vertically center content

Option 1 is to use display:table-cell. You need to unfloat the Bootstrap col-* using float:none..

.center {
    display:table-cell;
    vertical-align:middle;
    float:none;
}

http://bootply.com/94394


Option 2 is display:flex to vertical align the row with flexbox:

.row.center {
   display: flex;
   align-items: center;
}

http://www.bootply.com/7rAuLpMCwr


Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456

Getting time and date from timestamp with php

$mydatetime = "2012-04-02 02:57:54";
$datetimearray = explode(" ", $mydatetime);
$date = $datetimearray[0];
$time = $datetimearray[1];
$reformatted_date = date('d-m-Y',strtotime($date));
$reformatted_time = date('Gi.s',strtotime($time));

Center image in div horizontally

I hope this would be helpful:

.top_image img{
display: block;
margin: 0 auto;
}

How to get a value from a Pandas DataFrame and not the index and object type

Use the values attribute to return the values as a np array and then use [0] to get the first value:

In [4]:
df.loc[df.Letters=='C','Letters'].values[0]

Out[4]:
'C'

EDIT

I personally prefer to access the columns using subscript operators:

df.loc[df['Letters'] == 'C', 'Letters'].values[0]

This avoids issues where the column names can have spaces or dashes - which mean that accessing using ..

External VS2013 build error "error MSB4019: The imported project <path> was not found"

Me - nothing was helping in changing the v11.0 value of VisualStudioVersion variable to v10.0. Changing variable in .csproj file didn't. Setting it through command promt didn't. Etc...

Ended up copying my local folder of that specific version (v11.0) to my build server.

Query to display all tablespaces in a database and datafiles

If you want to get a list of all tablespaces used in the current database instance, you can use the DBA_TABLESPACES view as shown in the following SQL script example:

SQL> connect SYSTEM/fyicenter
Connected.

SQL> SELECT TABLESPACE_NAME, STATUS, CONTENTS
  2  FROM USER_TABLESPACES;
TABLESPACE_NAME                STATUS    CONTENTS
------------------------------ --------- ---------
SYSTEM                         ONLINE    PERMANENT
UNDO                           ONLINE    UNDO
SYSAUX                         ONLINE    PERMANENT
TEMP                           ONLINE    TEMPORARY
USERS                          ONLINE    PERMANENT

http://dba.fyicenter.com/faq/oracle/Show-All-Tablespaces-in-Current-Database.html

Change the icon of the exe file generated from Visual Studio 2010

Check the project properties. It's configurable there if you are using another .net windows application for example

How to change Android version and code version number?

The easiest way to set the version in Android Studio:

1. Press SHIFT+CTRL+ALT+S (or File -> Project Structure -> app)

Android Studio < 3.4:

  1. Choose tab 'Flavors'
  2. The last two fields are 'Version Code' and 'Version Name'

Android Studio >= 3.4:

  1. Choose 'Modules' in the left panel.
  2. Choose 'app' in middle panel.
  3. Choose 'Default Config' tab in the right panel.
  4. Scroll down to see and edit 'Version Code' and 'Version Name' fields.

The type or namespace name could not be found

just changed Application's target framework to ".Net Framework 4".

And error got Disappeared.

good luck; :D

Rewrite URL after redirecting 404 error htaccess

Try this in your .htaccess:

.htaccess

ErrorDocument 404 http://example.com/404/
ErrorDocument 500 http://example.com/500/
# or map them to one error document:
# ErrorDocument 404 /pages/errors/error_redirect.php
# ErrorDocument 500 /pages/errors/error_redirect.php

RewriteEngine On
RewriteBase /

RewriteCond %{REQUEST_URI} ^/404/$
RewriteRule ^(.*)$ /pages/errors/404.php [L]

RewriteCond %{REQUEST_URI} ^/500/$
RewriteRule ^(.*)$ /pages/errors/500.php [L]

# or map them to one error document:
#RewriteCond %{REQUEST_URI} ^/404/$ [OR]
#RewriteCond %{REQUEST_URI} ^/500/$
#RewriteRule ^(.*)$ /pages/errors/error_redirect.php [L]

The ErrorDocument redirects all 404s to a specific URL, all 500s to another url (replace with your domain).

The Rewrite rules map that URL to your actual 404.php script. The RewriteCond regular expressions can be made more generic if you want, but I think you have to explicitly define all ErrorDocument codes you want to override.

Local Redirect:

Change .htaccess ErrorDocument to a file that exists (must exist, or you'll get an error):

ErrorDocument 404 /pages/errors/404_redirect.php

404_redirect.php

<?php
   header('Location: /404/');
   exit;
?>

Redirect based on error number

Looks like you'll need to specify an ErrorDocument line in .htaccess for every error you want to redirect (see: Apache ErrorDocument and Apache Custom Error). The .htaccess example above has multiple examples in it. You can use the following as the generic redirect script to replace 404_redirect.php above.

error_redirect.php

<?php
   $error_url = $_SERVER["REDIRECT_STATUS"] . '/';
   $error_path = $error_url . '.php';

   if ( ! file_exists($error_path)) {
      // this is the default error if a specific error page is not found
      $error_url = '404/';
   }

   header('Location: ' . $error_url);
   exit;
?>

How to fix "Referenced assembly does not have a strong name" error?

You can use unsigned assemblies if your assembly is also unsigned.

Get the cartesian product of a series of lists?

itertools.product

Available from Python 2.6.

import itertools

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]
for element in itertools.product(*somelists):
    print(element)

Which is the same as,

for element in itertools.product([1, 2, 3], ['a', 'b'], [4, 5]):
    print(element)

Testing javascript with Mocha - how can I use console.log to debug a test?

You may have also put your console.log after an expectation that fails and is uncaught, so your log line never gets executed.

GDB: break if variable equal value

First, you need to compile your code with appropriate flags, enabling debug into code.

$ gcc -Wall -g -ggdb -o ex1 ex1.c

then just run you code with your favourite debugger

$ gdb ./ex1

show me the code.

(gdb) list
1   #include <stdio.h>
2   int main(void)
3   { 
4     int i = 0;
5     for(i=0;i<7;++i)
6       printf("%d\n", i);
7   
8     return 0;
9   }

break on lines 5 and looks if i == 5.

(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i

checking breakpoints

(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x00000000004004fb in main at ex1.c:5
    breakpoint already hit 1 time
5       read watchpoint keep y                      i
    stop only if i==5

running the program

(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i

Value = 5
0x0000000000400523 in main () at ex1.c:5
5     for(i=0;i<7;++i)

Get total size of file in bytes

You can use the length() method on File which returns the size in bytes.

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'] will give you the referrer page's URL if there exists any. If users use a bookmark or directly visit your site by manually typing in the URL, http_referer will be empty. Also if the users are posting to your page programatically (CURL) then they're not obliged to set the http_referer as well. You're missing all _, is that a typo?

Align button to the right

Maybe you can use float:right;:

_x000D_
_x000D_
.one {_x000D_
  padding-left: 1em;_x000D_
  text-color: white;_x000D_
   display:inline; _x000D_
}_x000D_
.two {_x000D_
  background-color: #00ffff;_x000D_
}_x000D_
.pull-right{_x000D_
  float:right;_x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
 _x000D_
  </head>_x000D_
  <body>_x000D_
      <div class="row">_x000D_
       <h3 class="one">Text</h3>_x000D_
       <button class="btn btn-secondary pull-right">Button</button>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to perform a LEFT JOIN in SQL Server between two SELECT statements?

SELECT * FROM 
(SELECT [UserID] FROM [User]) a
LEFT JOIN (SELECT [TailUser], [Weight] FROM [Edge] WHERE [HeadUser] = 5043) b
ON a.UserId = b.TailUser

Using OpenSSL what does "unable to write 'random state'" mean?

Apparently, I needed to run OpenSSL as root in order for it to have permission to the seeding file.

Get mouse wheel events in jQuery?

As of now in 2017, you can just write

$(window).on('wheel', function(event){

  // deltaY obviously records vertical scroll, deltaX and deltaZ exist too
  if(event.originalEvent.deltaY < 0){
    // wheeled up
  }
  else {
    // wheeled down
  }
});

Works with current Firefox 51, Chrome 56, IE9+

Access props inside quotes in React JSX

React (or JSX) doesn't support variable interpolation inside an attribute value, but you can put any JS expression inside curly braces as the entire attribute value, so this works:

<img className="image" src={"images/" + this.props.image} />

How to convert all tables in database to one collation?

For phpMyAdmin I figured this out:

SELECT GROUP_CONCAT("ALTER TABLE ", TABLE_SCHEMA, '.', TABLE_NAME," CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;" SEPARATOR ' ') AS    OneSQLString
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA="yourtableschemaname"
AND TABLE_TYPE="BASE TABLE"

Just change yourtableschemaname and you're fine.

Object Library Not Registered When Adding Windows Common Controls 6.0

...and on my 64 bit W7 machine, with VB6 installed... in DOS, as Admin, this worked to solve an OCX problem I was having with a VB6 App:

cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

YES! This solution solved the problem I had using MSCAL.OCX (The Microsoft Calendar Control) in VB6.

Thank you guys! :-)

Jquery, Clear / Empty all contents of tbody element?

        <table id="table_id" class="table table-hover">
          <thead>
            <tr>
             ...
             ...
            </tr>
          </thead>
        </table>

use this command to clear the body of that table: $("#table_id tbody").empty()

I use jquery to load the table content dynamically, and use this command to clear the body when doing the refreshing.

hope this helps you.

Function pointer as parameter

You need to declare disconnectFunc as a function pointer, not a void pointer. You also need to call it as a function (with parentheses), and no "*" is needed.

Android notification is not showing

Actually the answer by ƒernando Valle doesn't seem to be correct. Then again, your question is overly vague because you fail to mention what is wrong or isn't working.

Looking at your code I am assuming the Notification simply isn't showing.

Your notification is not showing, because you didn't provide an icon. Even though the SDK documentation doesn't mention it being required, it is in fact very much so and your Notification will not show without one.

addAction is only available since 4.1. Prior to that you would use the PendingIntent to launch an Activity. You seem to specify a PendingIntent, so your problem lies elsewhere. Logically, one must conclude it's the missing icon.

Check whether there is an Internet connection available on Flutter app

Using

dependencies:
  connectivity: ^0.4.2

what we got from resouces is

      import 'package:connectivity/connectivity.dart';

      Future<bool> check() async {
        var connectivityResult = await (Connectivity().checkConnectivity());
        if (connectivityResult == ConnectivityResult.mobile) {
          return true;
        } else if (connectivityResult == ConnectivityResult.wifi) {
          return true;
        }
        return false;
      }

Future is little problematic for me, we have to implement it every single time like :

check().then((intenet) {
      if (intenet != null && intenet) {
        // Internet Present Case
      }
      // No-Internet Case
    });

So to solve this problem i have created a class Which accept a function with boolean isNetworkPresent parameter like this

methodName(bool isNetworkPresent){}

And the Utility Class is

import 'package:connectivity/connectivity.dart';

class NetworkCheck {
  Future<bool> check() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    if (connectivityResult == ConnectivityResult.mobile) {
      return true;
    } else if (connectivityResult == ConnectivityResult.wifi) {
      return true;
    }
    return false;
  }

  dynamic checkInternet(Function func) {
    check().then((intenet) {
      if (intenet != null && intenet) {
        func(true);
      }
      else{
    func(false);
  }
    });
  }
}

And to use connectivity-check utilty

  fetchPrefrence(bool isNetworkPresent) {
    if(isNetworkPresent){

    }else{

    }
  }

i will use this syntax

NetworkCheck networkCheck = new NetworkCheck();
networkCheck.checkInternet(fetchPrefrence)

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do it with drop_duplicates as you wanted

# initialisation
d = pd.DataFrame({'A' : [1,1,2,3,3], 'B' : [2,2,7,4,4],  'C' : [1,4,1,0,8]})

d = d.sort_values("C", ascending=False)
d = d.drop_duplicates(["A","B"])

If it's important to get the same order

d = d.sort_index()

Clear all fields in a form upon going back with browser back button

If you need to compatible with older browsers as well "pageshow" option might not work. Following code worked for me.

$(window).load(function() {
    $('form').get(0).reset(); //clear form data on page load
});

Access mysql remote database from command line

Must check whether incoming access to port 3306 is block or not by the firewall.

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

In my case, I disabled McAfee and then successfully installed tensorflow2.0 RC

Can I specify maxlength in css?

Not with CSS, but you can emulate and extend / customize the desired behavior with JavaScript.

How to remove docker completely from ubuntu 14.04

@miyuru. As suggested by him run all the steps.

Ubuntu version 16.04

Still when I ran docker --version it was returning a version. So to uninstall it completely

Again run the dpkg -l | grep -i docker which will list package still there in system.

For example:

ii  docker-ce-cli      5:19.03.6~3-0~ubuntu-xenial               
amd64        Docker CLI: the open-source application container engine

Now remove them as show below :

sudo apt-get purge -y docker-ce-cli

sudo apt-get autoremove -y --purge docker-ce-cli

sudo apt-get autoclean

Hope this will resolve it, as it did in my case.

A monad is just a monoid in the category of endofunctors, what's the problem?

Note: No, this isn't true. At some point there was a comment on this answer from Dan Piponi himself saying that the cause and effect here was exactly the opposite, that he wrote his article in response to James Iry's quip. But it seems to have been removed, perhaps by some compulsive tidier.

Below is my original answer.


It's quite possible that Iry had read From Monoids to Monads, a post in which Dan Piponi (sigfpe) derives monads from monoids in Haskell, with much discussion of category theory and explicit mention of "the category of endofunctors on Hask" . In any case, anyone who wonders what it means for a monad to be a monoid in the category of endofunctors might benefit from reading this derivation.

CSS Equivalent of the "if" statement

There is no native IF/ELSE for CSS available. CSS preprocessors like SASS (and Compass) can help, but if you’re looking for more feature-specific if/else conditions you should give Modernizr a try. It does feature-detection and then adds classes to the HTML element to indicate which CSS3 & HTML5 features the browser supports and doesn’t support. You can then write very if/else-like CSS right in your CSS without any preprocessing, like this:

.geolocation #someElem {
   /* only apply this if the browser supports Geolocation */
}
.no-geolocation #someElem {
   /* only apply this if the browser DOES NOT support Geolocation */
}

Keep in mind that you should always progressively enhance, so rather than the above example (which illustrates the point better), you should write something more like this:

#someElem {
   /* default styles, suitable for both Geolocation support and lack thereof */
}
.geolocation #someElem {
   /* only properties as needed to overwrite the default styling  */
}

Note that Modernizr does rely on JavaScript, so if JS is disabled you wouldn’t get anything. Hence the progressive enhancement approach of #someElem first, as a no-js foundation.

When should I use git pull --rebase?

Just remember:

  • pull = fetch + merge
  • pull --rebase = fetch + rebase

So, choose the way what you want to handle your branch.

You'd better know the difference between merge and rebase :)

how to delete files from amazon s3 bucket?

Welcome to 2020 here is the answer in Python/Django:

from django.conf import settings 
import boto3   
s3 = boto3.client('s3')
s3.delete_object(Bucket=settings.AWS_STORAGE_BUCKET_NAME, Key=f"media/{item.file.name}")

Took me far too long to find the answer and it was as simple as this.

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

Just leaving this here for future visitors:

In my case the /WEB-INF/classes directory was missing. If you are using Eclipse, make sure the .settings/org.eclipse.wst.common.component is correct (Deployment Assembly in the project settings).

In my case it was missing

    <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>
    <wb-resource deploy-path="/WEB-INF/classes" source-path="/src/test/resources"/>

This file is also a common source of errors as mentioned by Anuj (missing dependencies of other projects).

Otherwise, hopefully the other answers (or the "Problems" tab) will help you.

How to add a new object (key-value pair) to an array in javascript?

If you're doing jQuery, and you've got a serializeArray thing going on concerning your form data, such as :

var postData = $('#yourform').serializeArray();

// postData (array with objects) : 
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, etc]

...and you need to add a key/value to this array with the same structure, for instance when posting to a PHP ajax request then this :

postData.push({"name": "phone", "value": "1234-123456"});

Result:

// postData : 
// [{name: "firstname", value: "John"}, {name: "lastname", value: "Doe"}, {"name":"phone","value":"1234-123456"}]

Expand Python Search Path to Other Source

You should also read about python packages here: http://docs.python.org/tutorial/modules.html.

From your example, I would guess that you really have a package at ~/codez/project. The file __init__.py in a python directory maps a directory into a namespace. If your subdirectories all have an __init__.py file, then you only need to add the base directory to your PYTHONPATH. For example:

PYTHONPATH=$PYTHONPATH:$HOME/adaifotis/project

In addition to testing your PYTHONPATH environment variable, as David explains, you can test it in python like this:

$ python
>>> import project                      # should work if PYTHONPATH set
>>> import sys
>>> for line in sys.path: print line    # print current python path

...

How to approach a "Got minus one from a read call" error when connecting to an Amazon RDS Oracle instance

I would like to augment to Stephen C's answer, my case was on the first dot. So since we have DHCP to allocate IP addresses in the company, DHCP changed my machine's address without of course asking neither me nor Oracle. So out of the blue oracle refused to do anything and gave the minus one dreaded exception. So if you want to workaround this once and for ever, and since TCP.INVITED_NODES of SQLNET.ora file does not accept wildcards as stated here, you can add you machine's hostname instead of the IP address.

Start an activity from a fragment

with Kotlin I execute this code:

requireContext().startActivity<YourTargetActivity>()

Is a URL allowed to contain a space?

Why does it have to be encoded? A request looks like this:

GET /url HTTP/1.1
(Ignoring headers)

There are 3 fields separated by a white space. If you put a space in your url:

GET /url end_url HTTP/1.1

You know have 4 fields, the HTTP server will tell you it is an invalid request.

GET /url%20end_url HTTP/1.1

3 fields => valid

Note: in the query string (after ?), a space is usually encoded as a +

GET /url?var=foo+bar HTTP/1.1 

rather than

GET /url?var=foo%20bar HTTP/1.1 

How do I select an element in jQuery by using a variable for the ID?

You can do it like this:

row_id = 5;
row = $("body").find('#'+row_id);

Environ Function code samples for VBA

As alluded to by Eric, you can use environ with ComputerName argument like so:

MsgBox Environ("USERNAME")

Some additional information that might be helpful for you to know:

  1. The arguments are not case sensitive.
  2. There is a slightly faster performing string version of the Environ function. To invoke it, use a dollar sign. (Ex: Environ$("username")) This will net you a small performance gain.
  3. You can retrieve all System Environment Variables using this function. (Not just username.) A common use is to get the "ComputerName" value to see which computer the user is logging onto from.
  4. I don't recommend it for most situations, but it can be occasionally useful to know that you can also access the variables with an index. If you use this syntax the the name of argument and the value are returned. In this way you can enumerate all available variables. Valid values are 1 - 255.
    Sub EnumSEVars()
        Dim strVar As String
        Dim i As Long
        For i = 1 To 255
            strVar = Environ$(i)
            If LenB(strVar) = 0& Then Exit For
            Debug.Print strVar
        Next
    End Sub

Format price in the current locale and currency

Unformatted and formatted:

$price = $product->getPrice();
$formatted = Mage::helper('core')->currency($price, true, false);

Or use:

Mage::helper('core')->formatPrice($price, true);

Filter multiple values on a string column in dplyr

Using the base package:

df <- data.frame(days = c(88, 11, 2, 5, 22, 1, 222, 2), name = c("Lynn", "Tom", "Chris", "Lisa", "Kyla", "Tom", "Lynn", "Lynn"))

# Three lines
target <- c("Tom", "Lynn")
index <- df$name %in% target
df[index, ]

# One line
df[df$name %in% c("Tom", "Lynn"), ] 

Output:

  days name
1   88 Lynn
2   11  Tom
6    1  Tom
7  222 Lynn
8    2 Lynn

Using sqldf:

library(sqldf)
# Two alternatives:
sqldf('SELECT *
      FROM df 
      WHERE name = "Tom" OR name = "Lynn"')
sqldf('SELECT *
      FROM df 
      WHERE name IN ("Tom", "Lynn")')

How to use jQuery Plugin with Angular 4?

ngOnInit() {
     const $ = window["$"];
     $('.flexslider').flexslider({
        animation: 'slide',
        start: function (slider) {
          $('body').removeClass('loading')
        }
     })
}

Should I learn C before learning C++?

If you decide to learn both (and as other people have mentioned, there's no explicit need to learn both), learn C first. Going from C to C++ feels like a natural progression; going the other way feels like deliberately tying one hand behind your back. :-)

Cleaning `Inf` values from an R dataframe

Also, if someone need the Infs' coordinates, can do this:

library(rlist)
list.clean(apply(df, 2, function(x){which(is.infinite(x))}), function(x) length(x) == 0L, TRUE)

Result:

$colname1
[1] row1 row2 ...
$colname2
[2] row1 row2 ... 

With this information, you can replace the Inf values in particular places with the mean, median, or whatever operator that you want.

For example (for element 01):

repInf = list.clean(apply(df, 2, function(x){which(is.infinite(x))}), function(x) length(x) == 0L, TRUE)
df[repInf[[1]], names(repInf)[[1]]] = median or mean(is.finite(df[ ,names(repInf)[[1]]]), na.rm = TRUE)

In loop:

for (nonInf in 1:length(repInf)) {
df[repInf[[nonInf]], names(repInf)[[nonInf]]] = mean(is.finite(df[ , names(repInf)[[nonInf]]]))
}

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

I think it is jar file version problem. I had the same issue and I fixed it by changing the commons-codec-1.6.jar file from the build path. Earlier I was using latest version 1.10. Gradually I decreased the versions and 1.6 version fixed my issue.

jQuery Loop through each div

Like this:

$(".target").each(function(){
    var images = $(this).find(".scrolling img");
    var width = images.width();
    var imgLength = images.length;
    $(this).find(".scrolling").width( width * imgLength * 1.2 );
});

The $(this) refers to the current .target which will be looped through. Within this .target I'm looking for the .scrolling img and get the width. And then keep on going...

Images with different widths

If you want to calculate the width of all images (when they have different widths) you can do it like this:

// Get the total width of a collection.
$.fn.getTotalWidth = function(){
    var width = 0;
    this.each(function(){
        width += $(this).width();
    });
    return width;
}

$(".target").each(function(){
    var images = $(this).find(".scrolling img");
    var width = images.getTotalWidth();
    $(this).find(".scrolling").width( width * 1.2 );
});

Letsencrypt add domain to existing certificate

This is how i registered my domain:

sudo letsencrypt --apache -d mydomain.com

Then it was possible to use the same command with additional domains and follow the instructions:

sudo letsencrypt --apache -d mydomain.com,x.mydomain.com,y.mydomain.com

Most efficient way to find smallest of 3 numbers Java?

Math.min uses a simple comparison to do its thing. The only advantage to not using Math.min is to save the extra function calls, but that is a negligible saving.

If you have more than just three numbers, having a minimum method for any number of doubles might be valuable and would look something like:

public static double min(double ... numbers) {
    double min = numbers[0];
    for (int i=1 ; i<numbers.length ; i++) {
        min = (min <= numbers[i]) ? min : numbers[i];
    }
    return min;
}

For three numbers this is the functional equivalent of Math.min(a, Math.min(b, c)); but you save one method invocation.

JNI converting jstring to char *

Thanks Jason Rogers's answer first.

In Android && cpp should be this:

const char *nativeString = env->GetStringUTFChars(javaString, nullptr);

// use your string

env->ReleaseStringUTFChars(javaString, nativeString);

Can fix this errors:

1.error: base operand of '->' has non-pointer type 'JNIEnv {aka _JNIEnv}'

2.error: no matching function for call to '_JNIEnv::GetStringUTFChars(JNIEnv*&, _jstring*&, bool)'

3.error: no matching function for call to '_JNIEnv::ReleaseStringUTFChars(JNIEnv*&, _jstring*&, char const*&)'

4.add "env->DeleteLocalRef(nativeString);" at end.

Access Form - Syntax error (missing operator) in query expression

Extra ( ) brackets may create problems in else if flow. This also creates Syntax error (missing operator) in query expression.

If (Array.Length == 0)

do you mean empty or null, two different things,

if the array is instantiated but empty, then length is correct, if it has not been instantiated then test vs null

Zoom in on a point (using scale and translate)

Here's a code implementation of @tatarize's answer, using PIXI.js. I have a viewport looking at part of a very big image (e.g. google maps style).

$canvasContainer.on('wheel', function (ev) {

    var scaleDelta = 0.02;
    var currentScale = imageContainer.scale.x;
    var nextScale = currentScale + scaleDelta;

    var offsetX = -(mousePosOnImage.x * scaleDelta);
    var offsetY = -(mousePosOnImage.y * scaleDelta);

    imageContainer.position.x += offsetX;
    imageContainer.position.y += offsetY;

    imageContainer.scale.set(nextScale);

    renderer.render(stage);
});
  • $canvasContainer is my html container.
  • imageContainer is my PIXI container that has the image in it.
  • mousePosOnImage is the mouse position relative to the entire image (not just the view port).

Here's how I got the mouse position:

  imageContainer.on('mousemove', _.bind(function(ev) {
    mousePosOnImage = ev.data.getLocalPosition(imageContainer);
    mousePosOnViewport.x = ev.data.originalEvent.offsetX;
    mousePosOnViewport.y = ev.data.originalEvent.offsetY;
  },self));

posting hidden value

You have to use $_POST['date'] instead of $date if it's coming from a POST request ($_GET if it's a GET request).

Python argparse: default value or specified value

The difference between:

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)

and

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)

is thus:

myscript.py => debug is 7 (from default) in the first case and "None" in the second

myscript.py --debug => debug is 1 in each case

myscript.py --debug 2 => debug is 2 in each case

Cannot open Windows.h in Microsoft Visual Studio

For my case, I had to right click the solution and click "Retarget Projects". In my case I retargetted to Windows SDK version 10.0.1777.0 and Platform Toolset v142. I also had to change "Windows.h"to<windows.h>

I am running Visual Studio 2019 version 16.25 on a windows 10 machine

Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?

To use unsafe code blocks, the project has to be compiled with the /unsafe switch on.

Open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox.

Change Circle color of radio button

For those who want to change disable, checked and enabled states you cat do the following steps:

<!-- Or androidX radio button or material design radio button -->
<android.support.v7.widget.AppCompatRadioButton
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:buttonTint="@color/black"
                    android:text="Radiobutton1"
                    app:buttonTint="@color/radio_button_color" />

then in color res folder make a file named "radio_button_color.xml":

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/yellow900" android:state_selected="true" />
    <item android:color="@color/yellow800" android:state_checked="true" />
    <item android:color="@color/gray800" android:state_enabled="false" />
    <item android:color="@color/yellow800" android:state_enabled="true" />
</selector>

PHP - remove all non-numeric characters from a string

Use \D to match non-digit characters.

preg_replace('~\D~', '', $str);

How abstraction and encapsulation differ?

I think they are slightly different concepts, but often they are applied together. Encapsulation is a technique for hiding implementation details from the caller, whereas abstraction is more a design philosophy involving creating objects that are analogous to familiar objects/processes, to aid understanding. Encapsulation is just one of many techniques that can be used to create an abstraction.

For example, take "windows". They are not really windows in the traditional sense, they are just graphical squares on the screen. But it's useful to think of them as windows. That's an abstraction.

If the "windows API" hides the details of how the text or graphics is physically rendered within the boundaries of a window, that's encapsulation.

SQL Server date format yyyymmdd

SELECT TO_CHAR(created_at, 'YYYY-MM-DD') FROM table; //converts any date format to YYYY-MM-DD

On localhost, how do I pick a free port number?

In my experience, just pick a relatively high number (between 1024-65535) that you think is unlikely to be used by anything else. For example, port # 8080 and # 5555 are ones that I routinely use. Just pick a port number like this as opposed to just making the code randomly select it and then having to find the port number later is much easier for me.

For example, in my current ChatBot project:

port = 8080

Input type number "only numeric value" validation

I had a similar problem, too: I wanted numbers and null on an input field that is not required. Worked through a number of different variations. I finally settled on this one, which seems to do the trick. You place a Directive, ntvFormValidity, on any form control that has native invalidity and that doesn't swizzle that invalid state into ng-invalid.

Sample use: <input type="number" formControlName="num" placeholder="0" ntvFormValidity>

Directive definition:

import { Directive, Host, Self, ElementRef, AfterViewInit } from '@angular/core';
import { FormControlName, FormControl, Validators } from '@angular/forms';

@Directive({
  selector: '[ntvFormValidity]'
})
export class NtvFormControlValidityDirective implements AfterViewInit {

  constructor(@Host() private cn: FormControlName, @Host() private el: ElementRef) { }

  /* 
  - Angular doesn't fire "change" events for invalid <input type="number">
  - We have to check the DOM object for browser native invalid state
  - Add custom validator that checks native invalidity
  */
  ngAfterViewInit() {
    var control: FormControl = this.cn.control;

    // Bridge native invalid to ng-invalid via Validators
    const ntvValidator = () => !this.el.nativeElement.validity.valid ? { error: "invalid" } : null;
    const v_fn = control.validator;

    control.setValidators(v_fn ? Validators.compose([v_fn, ntvValidator]) : ntvValidator);
    setTimeout(()=>control.updateValueAndValidity(), 0);
  }
}

The challenge was to get the ElementRef from the FormControl so that I could examine it. I know there's @ViewChild, but I didn't want to have to annotate each numeric input field with an ID and pass it to something else. So, I built a Directive which can ask for the ElementRef.

On Safari, for the HTML example above, Angular marks the form control invalid on inputs like "abc".

I think if I were to do this over, I'd probably build my own CVA for numeric input fields as that would provide even more control and make for a simple html.

Something like this:

<my-input-number formControlName="num" placeholder="0">

PS: If there's a better way to grab the FormControl for the directive, I'm guessing with Dependency Injection and providers on the declaration, please let me know so I can update my Directive (and this answer).

How do I unset an element in an array in javascript?

This is how I would do it

 myArray.splice( myArray.indexOf('bar') , 1) 

Write a formula in an Excel Cell using VBA

The correct character (comma or colon) depends on the purpose.

Comma (,) will sum only the two cells in question.

Colon (:) will sum all the cells within the range with corners defined by those two cells.

The preferred way of creating a new element with jQuery

I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.

docker error - 'name is already in use by container'

The Problem: you trying to create new container while in background container with same name is running and this situation causes conflicts.

The error would be like:

Cannot create continer for service X :Conflict. The name X is already in use by container abc123xyz. You have to remove ot delete (or rename) that container to be able to reuse that name.

Solution rename the service name in docker-compose.yml or delete the running container and rebuild it again (this solution related to Unix/Linux/macOS systems):

  1. get all running containers sudo docker ps -a
  2. get the specific container id
  3. stop and remove the duplicated container / force remove it
sudo docker stop <container_id>
sudo docker rm <container_id>

or

sudo docker rm --force <container_id>

Adding values to a C# array

I think this is the best method how to do that
Array Push Example

public void ArrayPush<T>(ref T[] table, object value)
{
    Array.Resize(ref table, table.Length + 1); // Resizing the array for the cloned length (+-) (+1)
    table.SetValue(value, table.Length - 1); // Setting the value for the new element
}

Installing Java 7 (Oracle) in Debian via apt-get

Managed to get answer after do some google..

echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
apt-get update
# Java 7
apt-get install oracle-java7-installer
# For Java 8 command is:
apt-get install oracle-java8-installer

Simple URL GET/POST function in Python

Even easier: via the requests module.

import requests
get_response = requests.get(url='http://google.com')
post_data = {'username':'joeb', 'password':'foobar'}
# POST some form-encoded data:
post_response = requests.post(url='http://httpbin.org/post', data=post_data)

To send data that is not form-encoded, send it serialised as a string (example taken from the documentation):

import json
post_response = requests.post(url='http://httpbin.org/post', data=json.dumps(post_data))
# If using requests v2.4.2 or later, pass the dict via the json parameter and it will be encoded directly:
post_response = requests.post(url='http://httpbin.org/post', json=post_data)

How to quickly and conveniently create a one element arraylist

Collections.singletonList(object)

the list created by this method is immutable.

How can I style a PHP echo text?

Store your results in variables, and use them in your HTML and add the necessary styling.

$usercity = $ip['cityName'];
$usercountry = $ip['countryName'];

And in the HTML, you could do:

<div id="userdetails">
<p> User's IP: <?php echo $usercity; ?> </p>
<p> Country: <?php echo $usercountry; ?> </p>
</div>

Now, you can simply add the styles for country class in your CSS, like so:

#userdetails {

/* styles go here */

}

Alternatively, you could also use this in your HTML:

<p style="font-size:15px; font-color: green;"><?php echo $userip; ?> </p>
<p style="font-size:15px; font-color: green;"><?php echo $usercountry; ?> </p>

Hope this helps!

Checking for directory and file write permissions in .NET

The accepted answer by Kev to this question doesn't actually give any code, it just points to other resources that I don't have access to. So here's my best attempt at the function. It actually checks that the permission it's looking at is a "Write" permission and that the current user belongs to the appropriate group.

It might not be complete with regard to network paths or whatever, but it's good enough for my purpose, checking local configuration files under "Program Files" for writability:

using System.Security.Principal;
using System.Security.AccessControl;

private static bool HasWritePermission(string FilePath)
{
    try
    {
        FileSystemSecurity security;
        if (File.Exists(FilePath))
        {
            security = File.GetAccessControl(FilePath);
        }
        else
        {
            security = Directory.GetAccessControl(Path.GetDirectoryName(FilePath));
        }
        var rules = security.GetAccessRules(true, true, typeof(NTAccount));

        var currentuser = new WindowsPrincipal(WindowsIdentity.GetCurrent());
        bool result = false;
        foreach (FileSystemAccessRule rule in rules)
        {
            if (0 == (rule.FileSystemRights &
                (FileSystemRights.WriteData | FileSystemRights.Write)))
            {
                continue;
            }

            if (rule.IdentityReference.Value.StartsWith("S-1-"))
            {
                var sid = new SecurityIdentifier(rule.IdentityReference.Value);
                if (!currentuser.IsInRole(sid))
                {
                    continue;
                }
            }
            else
            {
                if (!currentuser.IsInRole(rule.IdentityReference.Value))
                {
                    continue;
                }
            }

            if (rule.AccessControlType == AccessControlType.Deny)
                return false;
            if (rule.AccessControlType == AccessControlType.Allow)
                result = true;
        }
        return result;
    }
    catch
    {
        return false;
    }
}

I cannot access tomcat admin console?

Perhaps manager app does not exist look if you the manager application is on $APACHE_HOME/server/webapps directory. on this directory you must have : docs,examples, host-manager,manager, ROOT.

"Unable to find remote helper for 'https'" during git clone

On CentOS 5.x, installing curl-devel fixed the problem for me.

PHP Accessing Parent Class Variable

With parent::$bb; you try to retrieve the static constant defined with the value of $bb.

Instead, do:

echo $this->bb;

Note: you don't need to call parent::_construct if B is the only class that calls it. Simply don't declare __construct in B class.

Textarea that can do syntax highlighting on the fly?

Update: Bespin is now ACE, which is mentioned by the highest rated answer here. Use ACE instead.

Gotta go with Bespin by Mozilla. It's built using HTML5 features (so it's quick and fast, but doesn't support legacy browsers though), but definitely amazing to use and beats everything I've come across - probably beacause it's Mozilla backing it, and they develop Firefox so yeah... There's also a jQuery Plugin which contains a extension for it to make it a bit easier to use with jQuery.

Timeout jQuery effects

You can do something like this:

$('.notice')
    .fadeIn()
    .animate({opacity: '+=0'}, 2000)   // Does nothing for 2000ms
    .fadeOut('fast');

Sadly, you can't just do .animate({}, 2000) -- I think this is a bug, and will report it.