Programs & Examples On #Generic test

String to Binary in C#

Here you go:

public static byte[] ConvertToByteArray(string str, Encoding encoding)
{
    return encoding.GetBytes(str);
}

public static String ToBinary(Byte[] data)
{
    return string.Join(" ", data.Select(byt => Convert.ToString(byt, 2).PadLeft(8, '0')));
}

// Use any sort of encoding you like. 
var binaryString = ToBinary(ConvertToByteArray("Welcome, World!", Encoding.ASCII));

How to run script as another user without password?

`su -c "Your command right here" -s /bin/sh username`

The above command is correct, but on Red Hat if selinux is enforcing it will not allow cron to execute scripts as another user. example; execl: couldn't exec /bin/sh execl: Permission denied

I had to install setroubleshoot and setools and run the following to allow it:

yum install setroubleshoot setools
sealert -a /var/log/audit/audit.log
grep crond /var/log/audit/audit.log | audit2allow -M mypol
semodule -i mypol.p

file_get_contents(): SSL operation failed with code 1, Failed to enable crypto

I fixed this by making sure that that OpenSSL was installed on my machine and then adding this to my php.ini:

openssl.cafile=/usr/local/etc/openssl/cert.pem

how to call service method from ng-change of select in angularjs?

You have at least two issues in your code:

  • ng-change="getScoreData(Score)

    Angular doesn't see getScoreData method that refers to defined service

  • getScoreData: function (Score, callback)

    We don't need to use callback since GET returns promise. Use then instead.

Here is a working example (I used random address only for simulation):

HTML

<select ng-model="score"
        ng-change="getScoreData(score)" 
        ng-options="score as score.name for score in  scores"></select>
    <pre>{{ScoreData|json}}</pre> 

JS

var fessmodule = angular.module('myModule', ['ngResource']);

fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {

    $scope.scores = [{
        name: 'Bukit Batok Street 1',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
    }, {
        name: 'London 8',
        URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
    }];

    $scope.getScoreData = function(score) {
        ScoreDataService.getScoreData(score).then(function(result) {
            $scope.ScoreData = result;
        }, function(result) {
            alert("Error: No data returned");
        });
    };

});

fessmodule.$inject = ['$scope', 'ScoreDataService'];

fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {

    var factory = {
        getScoreData: function(score) {
            console.log(score);
            var data = $http({
                method: 'GET',
                url: score.URL
            });


            return data;
        }
    }
    return factory;
}]);

Demo Fiddle

Merge development branch with master

This is how I usually do it. First, sure that you are ready to merge your changes into master.

  1. Check if development is up to date with the latest changes from your remote server with a git fetch
  2. Once the fetch is completed git checkout master.
  3. Ensure the master branch has the latest updates by executing git pull
  4. Once the preparations have been completed, you can start the merge with git merge development
  5. Push the changes with git push -u origin master and you are done.

You can find more into about git merging in the article.

Day Name from Date in JS

Take a look at this :

var event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012

console.log(event.toLocaleDateString('ar-EG', options));
// expected output: ??????? ?? ??????? ????

console.log(event.toLocaleDateString('ko-KR', options));
// expected output: 2012? 12? 20? ???

Source : Mozilla Doc

System.Net.WebException: The operation has timed out

Close/dispose your WebResponse object.

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

I got this error when attempting to build with Xcode 10. It appears to be a bug in the Swift compiler. Building with Whole Module Optimization on, resolves the issue: https://forums.swift.org/t/illegal-instruction-4-when-trying-to-compile-project/16118

This is not an ideal solution, I will continue to use Xcode 9.4.1 until this issue is resolved.

Adding IN clause List to a JPA Query

The proper JPA query format would be:

el.name IN :inclList

If you're using an older version of Hibernate as your provider you have to write:

el.name IN (:inclList)

but that is a bug (HHH-5126) (EDIT: which has been resolved by now).

Python: Generate random number between x and y which is a multiple of 5

The simplest way is to generate a random nuber between 0-1 then strech it by multiplying, and shifting it.
So yo would multiply by (x-y) so the result is in the range of 0 to x-y,
Then add x and you get the random number between x and y.

To get a five multiplier use rounding. If this is unclear let me know and I'll add code snippets.

How to rollback just one step using rake db:migrate

Other people have already answered you how to rollback, but you also asked how you could identify the version number of a migration.

  • rake db:migrate:status gives a list of your migrations version, name and status (up or down)
  • Your can also find the migration file, which contain a timestamp in the filename, that is the version number. Migrations are located in folder: /db/migrate

How to load up CSS files using Javascript?

If you want to know (or wait) until the style itself has loaded this works:

// this will work in IE 10, 11 and Safari/Chrome/Firefox/Edge
// add ES6 poly-fill for the Promise, if needed (or rewrite to use a callback)

let fetchStyle = function(url) {
  return new Promise((resolve, reject) => {
    let link = document.createElement('link');
    link.type = 'text/css';
    link.rel = 'stylesheet';
    link.onload = function() { resolve(); console.log('style has loaded'); };
    link.href = url;

    let headScript = document.querySelector('script');
    headScript.parentNode.insertBefore(link, headScript);
  });
};

Get a Div Value in JQuery

myDivObj = document.getElementById("myDiv");
if ( myDivObj ) {
   alert ( myDivObj.innerHTML ); 
}else{
   alert ( "Alien Found" );
}

Above code will show the innerHTML, i.e if you have used html tags inside div then it will show even those too. probably this is not what you expected. So another solution is to use: innerText / textContent property [ thanx to bobince, see his comment ]

function showDivText(){
            divObj = document.getElementById("myDiv");
            if ( divObj ){
                if ( divObj.textContent ){ // FF
                    alert ( divObj.textContent );
                }else{  // IE           
                    alert ( divObj.innerText );  //alert ( divObj.innerHTML );
                } 
            }  
        }

How to get time difference in minutes in PHP

Subtract the past most one from the future most one and divide by 60.

Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

Sergey is correct, but if you need to get a response from your home-spun dialog(s) for evaluation in the same block of code that invoked it, you should use .showAndWait(), not .show(). Here's my rendition of a couple of the dialog types that are provided in Swing's OptionPane:

public class FXOptionPane {

public enum Response { NO, YES, CANCEL };

private static Response buttonSelected = Response.CANCEL;

private static ImageView icon = new ImageView();

static class Dialog extends Stage {
    public Dialog( String title, Stage owner, Scene scene, String iconFile ) {
        setTitle( title );
        initStyle( StageStyle.UTILITY );
        initModality( Modality.APPLICATION_MODAL );
        initOwner( owner );
        setResizable( false );
        setScene( scene );
        icon.setImage( new Image( getClass().getResourceAsStream( iconFile ) ) );
    }
    public void showDialog() {
        sizeToScene();
        centerOnScreen();
        showAndWait();
    }
}

static class Message extends Text {
    public Message( String msg ) {
        super( msg );
        setWrappingWidth( 250 );
    }
}

public static Response showConfirmDialog( Stage owner, String message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Confirm.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button yesButton = new Button( "Yes" );
    yesButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.YES;
        }
    } );
    Button noButton = new Button( "No" );
    noButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
            buttonSelected = Response.NO;
        }
    } );
    BorderPane bp = new BorderPane();
    HBox buttons = new HBox();
    buttons.setAlignment( Pos.CENTER );
    buttons.setSpacing( 10 );
    buttons.getChildren().addAll( yesButton, noButton );
    bp.setCenter( buttons );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, new Message( message ) );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
    return buttonSelected;
}

public static void showMessageDialog( Stage owner, String message, String title ) {
    showMessageDialog( owner, new Message( message ), title );
}
public static void showMessageDialog( Stage owner, Node message, String title ) {
    VBox vb = new VBox();
    Scene scene = new Scene( vb );
    final Dialog dial = new Dialog( title, owner, scene, "res/Info.png" );
    vb.setPadding( new Inset(10,10,10,10) );
    vb.setSpacing( 10 );
    Button okButton = new Button( "OK" );
    okButton.setAlignment( Pos.CENTER );
    okButton.setOnAction( new EventHandler<ActionEvent>() {
        @Override public void handle( ActionEvent e ) {
            dial.close();
        }
    } );
    BorderPane bp = new BorderPane();
    bp.setCenter( okButton );
    HBox msg = new HBox();
    msg.setSpacing( 5 );
    msg.getChildren().addAll( icon, message );
    vb.getChildren().addAll( msg, bp );
    dial.showDialog();
}

}

How to extract the year from a Python datetime object?

The other answers to this question seem to hit it spot on. Now how would you figure this out for yourself without stack overflow? Check out IPython, an interactive Python shell that has tab auto-complete.

> ipython
import Python 2.5 (r25:51908, Nov  6 2007, 16:54:01)
Type "copyright", "credits" or "license" for more information.

IPython 0.8.2.svn.r2750 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.

In [1]: import datetime
In [2]: now=datetime.datetime.now()
In [3]: now.

press tab a few times and you'll be prompted with the members of the "now" object:

now.__add__           now.__gt__            now.__radd__          now.__sub__           now.fromordinal       now.microsecond       now.second            now.toordinal         now.weekday
now.__class__         now.__hash__          now.__reduce__        now.astimezone        now.fromtimestamp     now.min               now.strftime          now.tzinfo            now.year
now.__delattr__       now.__init__          now.__reduce_ex__     now.combine           now.hour              now.minute            now.strptime          now.tzname
now.__doc__           now.__le__            now.__repr__          now.ctime             now.isocalendar       now.month             now.time              now.utcfromtimestamp
now.__eq__            now.__lt__            now.__rsub__          now.date              now.isoformat         now.now               now.timetuple         now.utcnow
now.__ge__            now.__ne__            now.__setattr__       now.day               now.isoweekday        now.replace           now.timetz            now.utcoffset
now.__getattribute__  now.__new__           now.__str__           now.dst               now.max               now.resolution        now.today             now.utctimetuple

and you'll see that now.year is a member of the "now" object.

How to set and reference a variable in a Jenkinsfile

The error is due to that you're only allowed to use pipeline steps inside the steps directive. One workaround that I know is to use the script step and wrap arbitrary pipeline script inside of it and save the result in the environment variable so that it can be used later.

So in your case:

pipeline {
    agent any
    stages {
        stage("foo") {
            steps {
                script {
                    env.FILENAME = readFile 'output.txt'
                }
                echo "${env.FILENAME}"
            }
        }
    }
}

Programmatically read from STDIN or input file in Perl

while (<>) {
print;
}

will read either from a file specified on the command line or from stdin if no file is given

If you are required this loop construction in command line, then you may use -n option:

$ perl -ne 'print;'

Here you just put code between {} from first example into '' in second

No generated R.java file in my project

Go to Project and hit Clean. This should, among others, regenerate your R.java file.

Also get rid of any import android.R.* statements and then do the clean up I mentioned.

Apparently Jonas problem was related to incorrect target build settings. His target build was set to Android 2.1 (SDK v7) where his layout XML used Android 2.2 (SDK v8) elements (layout parameter match_parent), due to this there was no way for Eclipse to correctly generate the R.java file which caused all the problems.

How can I change the user on Git Bash?

For Mac Users

I am using Mac and I was facing same problem while I was trying to push a project from Android Studio. The reason for that other user had previously logged into Github and his credentials were saved in Keychain Access.

You need to remove those credentials from Keychain Access and then try to push.

Hope it help to Mac users.

Imitating a blink tag with CSS3 animations

Please find below solution for your code.

_x000D_
_x000D_
@keyframes blink {_x000D_
  50% {_x000D_
    color: transparent;_x000D_
  }_x000D_
}_x000D_
_x000D_
.loader__dot {_x000D_
  animation: 1s blink infinite;_x000D_
}_x000D_
_x000D_
.loader__dot:nth-child(2) {_x000D_
  animation-delay: 250ms;_x000D_
}_x000D_
_x000D_
.loader__dot:nth-child(3) {_x000D_
  animation-delay: 500ms;_x000D_
}
_x000D_
Loading <span class="loader__dot">.</span><span class="loader__dot">.</span><span class="loader__dot">.</span>
_x000D_
_x000D_
_x000D_

Change width of select tag in Twitter Bootstrap

I did a workaround by creating a new css class in my custom stylesheet as follows:

.selectwidthauto
{
     width:auto !important;
}

And then applied this class to all my select elements either manually like:

<select id="State" class="selectwidthauto">
...
</select>

Or using jQuery:

$('select').addClass('selectwidthauto');

How do I check if a number is a palindrome?

public boolean isPalindrome(int x) {
        if (isNegative(x))
            return false;

        boolean isPalindrome = reverseNumber(x) == x ? true : false;
        return isPalindrome;
    }

    private boolean isNegative(int x) {
        if (x < 0)
            return true;
        return false;
    }

    public int reverseNumber(int x) {

        int reverseNumber = 0;

        while (x > 0) {
            int remainder = x % 10;
            reverseNumber = reverseNumber * 10 + remainder;
            x = x / 10;
        }

        return reverseNumber;
    }

Regular expression \p{L} and \p{N}

\p{L} matches a single code point in the category "letter".
\p{N} matches any kind of numeric character in any script.

Source: regular-expressions.info

If you're going to work with regular expressions a lot, I'd suggest bookmarking that site, it's very useful.

How to escape double quotes in a title attribute

It may work with any character from the HTML Escape character list, but I had the same problem with a Java project. I used StringEscapeUtils.escapeHTML("Testing \" <br> <p>") and the title was <a href=".." title="Test&quot; &lt;br&gt; &lt;p&gt;">Testing</a>.

It only worked for me when I changed the StringEscapeUtils to StringEscapeUtils.escapeJavascript("Testing \" <br> <p>") and it worked in every browser.

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

What is the use of the square brackets [] in sql statements?

The brackets are required if you use keywords or special chars in the column names or identifiers. You could name a column [First Name] (with a space)--but then you'd need to use brackets every time you referred to that column.

The newer tools add them everywhere just in case or for consistency.

What is a callback URL in relation to an API?

A callback URL will be invoked by the API method you're calling after it's done. So if you call

POST /api.example.com/foo?callbackURL=http://my.server.com/bar

Then when /foo is finished, it sends a request to http://my.server.com/bar. The contents and method of that request are going to vary - check the documentation for the API you're accessing.

How to add text inside the doughnut chart using Chart.js?

You have to modify the code like: in chart.Doughnut.defaults

labelFontFamily : "Arial",
labelFontStyle : "normal",
labelFontSize : 24,
labelFontColor : "#666"

and then in function drawPieSegments

ctx.fillText(data[0].value + "%", width/2 - 20, width/2, 200);

See this pull: https://github.com/nnnick/Chart.js/pull/35

here is a fiddle http://jsfiddle.net/mayankcpdixit/6xV78/ implementing the same.

How to find and restore a deleted file in a Git repository

For the best way to do that, try it.


First, find the commit id of the commit that deleted your file. It will give you a summary of commits which deleted files.

git log --diff-filter=D --summary

git checkout 84sdhfddbdddf~1

Note: 84sdhfddbddd is your commit id

Through this you can easily recover all deleted files.

How to hide .php extension in .htaccess

1) Are you sure mod_rewrite module is enabled? Check phpinfo()

2) Your above rule assumes the URL starts with "folder". Is this correct? Did you acutally want to have folder in the URL? This would match a URL like:

/folder/thing -> /folder/thing.php

If you actually want

/thing -> /folder/thing.php

You need to drop the folder from the match expression.

I usually use this to route request to page without php (but yours should work which leads me to think that mod_rewrite may not be enabled):

RewriteRule ^([^/\.]+)/?$ $1.php  [L,QSA]

3) Assuming you are declaring your rules in an .htaccess file, does your installation allow for setting Options (AllowOverride) overrides in .htaccess files? Some shared hosts do not.

When the server finds an .htaccess file (as specified by AccessFileName) it needs to know which directives declared in that file can override earlier access information.

'module' object has no attribute 'DataFrame'

I have faced similar problem, 'int' object has no attribute 'DataFrame',

This was because i have mistakenly used pd as a variable in my code and assigned an integer to it, while using the same pd as my pandas dataframe object by declaring - import pandas as pd.

I realized this, and changed my variable to something else, and fixed the error.

How do I update a Tomcat webapp without restarting the entire service?

In conf directory of apache tomcat you can find context.xml file. In that edit tag as <Context reloadable="true">. this should solve the issue and you need not restart the server

How to enumerate an enum with String type?

Swift 4.2+

Starting with Swift 4.2 (with Xcode 10), just add protocol conformance to CaseIterable to benefit from allCases. To add this protocol conformance, you simply need to write somewhere:

extension Suit: CaseIterable {}

If the enum is your own, you may specify the conformance directly in the declaration:

enum Suit: String, CaseIterable { case spades = "?"; case hearts = "?"; case diamonds = "?"; case clubs = "?" }

Then the following code will print all possible values:

Suit.allCases.forEach {
    print($0.rawValue)
}

Compatibility with earlier Swift versions (3.x and 4.x)

If you need to support Swift 3.x or 4.0, you may mimic the Swift 4.2 implementation by adding the following code:

#if !swift(>=4.2)
public protocol CaseIterable {
    associatedtype AllCases: Collection where AllCases.Element == Self
    static var allCases: AllCases { get }
}
extension CaseIterable where Self: Hashable {
    static var allCases: [Self] {
        return [Self](AnySequence { () -> AnyIterator<Self> in
            var raw = 0
            var first: Self?
            return AnyIterator {
                let current = withUnsafeBytes(of: &raw) { $0.load(as: Self.self) }
                if raw == 0 {
                    first = current
                } else if current == first {
                    return nil
                }
                raw += 1
                return current
            }
        })
    }
}
#endif

print highest value in dict with key

just :

 mydict = {'A':4,'B':10,'C':0,'D':87}
 max(mydict.items(), key=lambda x: x[1])

How to write and read a file with a HashMap?

The simplest solution that I can think of is using Properties class.

Saving the map:

Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();

for (Map.Entry<String,String> entry : ldapContent.entrySet()) {
    properties.put(entry.getKey(), entry.getValue());
}

properties.store(new FileOutputStream("data.properties"), null);

Loading the map:

Map<String, String> ldapContent = new HashMap<String, String>();
Properties properties = new Properties();
properties.load(new FileInputStream("data.properties"));

for (String key : properties.stringPropertyNames()) {
   ldapContent.put(key, properties.get(key).toString());
}

EDIT:

if your map contains plaintext values, they will be visible if you open file data via any text editor, which is not the case if you serialize the map:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.ser"));
out.writeObject(ldapContent);
out.close();

EDIT2:

instead of for loop (as suggested by OldCurmudgeon) in saving example:

properties.putAll(ldapContent);

however, for the loading example this is the best that can be done:

ldapContent = new HashMap<Object, Object>(properties);

Promise Error: Objects are not valid as a React child

You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

render: function() {
  return (
    <span>
      // This will go through all the elements in arrayFromJson and
      // render each one as a <SomeComponent /> with data from the object
      {this.state.arrayFromJson.map(function(object) {
        return (
          <SomeComponent key={object.id} data={object} />
        );
      })}
    </span>
  );
}

Can jQuery read/write cookies to a browser?

To answer your question, yes. The other have answered that part, but it also seems like you're asking if that's the best way to do it.

It would probably depend on what you are doing. Typically you would have a user click what items they want to buy (ordering for example). Then they would hit a buy or checkout button. Then the form would send off to a page and process the result. You could do all of that with a cookie but I would find it to be more difficult.

You may want to consider posting your second question in another topic.

datatable jquery - table header width not aligned with body width

CAUSE

Most likely your table is hidden initially which prevents jQuery DataTables from calculating column widths.

SOLUTION

  • If table is in the collapsible element, you need to adjust headers when collapsible element becomes visible.

    For example, for Bootstrap Collapse plugin:

    $('#myCollapsible').on('shown.bs.collapse', function () {
       $($.fn.dataTable.tables(true)).DataTable()
          .columns.adjust();
    });
    
  • If table is in the tab, you need to adjust headers when tab becomes visible.

    For example, for Bootstrap Tab plugin:

    $('a[data-toggle="tab"]').on('shown.bs.tab', function(e){
       $($.fn.dataTable.tables(true)).DataTable()
          .columns.adjust();
    });
    

Code above adjusts column widths for all tables on the page. See columns().adjust() API methods for more information.

RESPONSIVE, SCROLLER OR FIXEDCOLUMNS EXTENSIONS

If you're using Responsive, Scroller or FixedColumns extensions, you need to use additional API methods to solve this problem.

LINKS

See jQuery DataTables – Column width issues with Bootstrap tabs for solutions to the most common problems with columns in jQuery DataTables when table is initially hidden.

Binding a WPF ComboBox to a custom list

I had what at first seemed to be an identical problem, but it turned out to be due to an NHibernate/WPF compatibility issue. The problem was caused by the way WPF checks for object equality. I was able to get my stuff to work by using the object ID property in the SelectedValue and SelectedValuePath properties.

<ComboBox Name="CategoryList"
          DisplayMemberPath="CategoryName"
          SelectedItem="{Binding Path=CategoryParent}"
          SelectedValue="{Binding Path=CategoryParent.ID}"
          SelectedValuePath="ID">

See the blog post from Chester, The WPF ComboBox - SelectedItem, SelectedValue, and SelectedValuePath with NHibernate, for details.

How can I convert an image into a Base64 string?

Here is the encoding and decoding code in Kotlin:

 fun encode(imageUri: Uri): String {
    val input = activity.getContentResolver().openInputStream(imageUri)
    val image = BitmapFactory.decodeStream(input , null, null)

    // Encode image to base64 string
    val baos = ByteArrayOutputStream()
    image.compress(Bitmap.CompressFormat.JPEG, 100, baos)
    var imageBytes = baos.toByteArray()
    val imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT)
    return imageString
}

fun decode(imageString: String) {

    // Decode base64 string to image
    val imageBytes = Base64.decode(imageString, Base64.DEFAULT)
    val decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)

    imageview.setImageBitmap(decodedImage)
}

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

I have encounter the same issue and found that i have forgot to prefix the commit message with project identifier. Project identifier is must in our case followed by the commit message. So at the server end it doesn't found the prefix and raised the issue.

Difference between "git add -A" and "git add ."

Both git add . and git add -A will stage all new, modified and deleted files in the newer versions of Git.

The difference is that git add -A stages files in "higher, current and subdirectories" that belong to your working Git repository. But doing a git add . only stages files in the current directory and subdirectories following it (not the files lying outside, i.e., higher directories).

Here's an example:

/my-repo
  .git/
  subfolder/
    nested-file.txt
  rootfile.txt

If your current working directory is /my-repo, and you do rm rootfile.txt, then cd subfolder, followed by git add ., then it will not stage the deleted file. But doing git add -A will certainly stage this change no matter where you perform the command from.

How to see the changes between two commits without commits in-between?

$git log

commit-1(new/latest/recent commit)
commit-2
commit-3
commit-4
*
*
commit-n(first commit)

$git diff commit-2 commit-1

display's all changes between commit-2 to commit-1 (patch of commit-1 alone & equivalent to git diff HEAD~1 HEAD)

similarly $git diff commit-4 commit-1

display's all changes between commit-4 to commit-1 (patch of commit-1, commit-2 & commit-3 together. Equivalent to git diff HEAD~3 HEAD)

$git diff commit-1 commit-2

By changing order commit ID's it is possible to get revert patch . ("$git diff commit-1 commit-2 > revert_patch_of_commit-1.diff")

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

Had the same issue installing angular material CDK:

npm install --save @angular/material @angular/cdk @angular/animations

Adding -dev like below worked for me:

npm install --save-dev @angular/material @angular/cdk @angular/animations

Thymeleaf using path variables to th:href

A cleaner and easier way to do this

<a href="somepage.html" th:href="@{|/my/url/${variable}|}">A Link</a>

I found this solution in Thymeleaf Documentation on "4.8 Literal substitutions".

Configuring user and password with Git Bash

Make sure you are using the SSH URL for the GitHub repository rather than the HTTPS URL. It will ask for username and password when you are using HTTPS and not SSH. You can check the file .git/config or run git config -e or git remote show origin to verify the URL and change it if needed.

How can I make an svg scale with its parent container?

You'll want to do a transform as such:

with JavaScript:

document.getElementById(yourtarget).setAttribute("transform", "scale(2.0)");

With CSS:

#yourtarget {
  transform:scale(2.0);
  -webkit-transform:scale(2.0);
}

Wrap your SVG Page in a Group tag as such and target it to manipulate the whole page:

<svg>
  <g id="yourtarget">
    your svg page
  </g>
</svg>

Note: Scale 1.0 is 100%

scp from remote host to local host

There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.

And then you can copy for example the file "test.txt" from a remote host to the local host

scp [email protected]:test.txt /local/dir


@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.

In UNIX, absolute paths must start with '/'.

How to fix request failed on channel 0

Just add these lines to your /etc/mtab and /etc/fstab, and reboot the system.

none    /dev/pts    devpts    defaults    0    0

Stop setInterval call in JavaScript

In nodeJS you can you use the "this" special keyword within the setInterval function.

You can use this this keyword to clearInterval, and here is an example:

setInterval(
    function clear() {
            clearInterval(this) 
       return clear;
    }()
, 1000)

When you print the value of this special keyword within the function you outpout a Timeout object Timeout {...}

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.

Proxy Error

The proxy server received an invalid response from an upstream server.
 The proxy server could not handle the request GET /lin/Campaignn.jsp.

As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.

Cannot use special principal dbo: Error 15405

This is happening because the user 'sarin' is the actual owner of the database "dbemployee" - as such, they can only have db_owner, and cannot be assigned any further database roles.

Nor do they need to be. If they're the DB owner, they already have permission to do anything they want to within this database.

(To see the owner of the database, open the properties of the database. The Owner is listed on the general tab).

To change the owner of the database, you can use sp_changedbowner or ALTER AUTHORIZATION (the latter being apparently the preferred way for future development, but since this kind of thing tends to be a one off...)

How to get Enum Value from index in Java?

Try this

Months.values()[index]

Creating a .p12 file

I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.

I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!

  1. Generate 2048-bit RSA private key:

    openssl genrsa -out key.pem 2048

  2. Generate a Certificate Signing Request:

    openssl req -new -sha256 -key key.pem -out csr.csr

  3. Generate a self-signed x509 certificate suitable for use on web servers.

    openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem

  4. Create SSL identity file in PKCS12 as mentioned here

    openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem

Custom CSS Scrollbar for Firefox

As of now there is just two property for firefox scrollbar customization is available .

scrollbar-color & scrollbar width

scrollbar-color:red yellow; (track,thumb) scrollbar-width:5px;

HTML

<div class="demo">

css

.demo {
overflow-y:scroll;
}

.demo {
scrollbar-color:red yellow;
scrollbar-width:5px;
}

JSON parse error: Can not construct instance of java.time.LocalDate: no String-argument constructor/factory method to deserialize from String value

Spring Boot 2.2.2 / Gradle:

Gradle (build.gradle):

implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310")

Entity (User.class):

LocalDate dateOfBirth;

Code:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
User user = mapper.readValue(json, User.class);

Waiting until the task finishes

In Swift 3, there is no need for completion handler when DispatchQueue finishes one task. Furthermore you can achieve your goal in different ways

One way is this:

    var a: Int?

    let queue = DispatchQueue(label: "com.app.queue")
    queue.sync {

        for  i in 0..<10 {

            print("??" , i)
            a = i
        }
    }

    print("After Queue \(a)")

It will wait until the loop finishes but in this case your main thread will block.

You can also do the same thing like this:

    let myGroup = DispatchGroup()
    myGroup.enter()
    //// Do your task

    myGroup.leave() //// When your task completes
     myGroup.notify(queue: DispatchQueue.main) {

        ////// do your remaining work
    }

One last thing: If you want to use completionHandler when your task completes using DispatchQueue, you can use DispatchWorkItem.

Here is an example how to use DispatchWorkItem:

let workItem = DispatchWorkItem {
    // Do something
}

let queue = DispatchQueue.global()
queue.async {
    workItem.perform()
}
workItem.notify(queue: DispatchQueue.main) {
    // Here you can notify you Main thread
}

Round number to nearest integer

For this purpose I would suggest just do the following thing -

int(round(x))

This will give you nearest integer.

Hope this helps!!

Angular no provider for NameService

Hi , You can use this in your .ts file :

first import your service in this .ts file:

import { Your_Service_Name } from './path_To_Your_Service_Name';

Then in the same file you can add providers: [Your_Service_Name] :

 @Component({
      selector: 'my-app',
      providers: [Your_Service_Name],
      template: `
        <h1>Hello World</h1> `   
    })

Why is my element value not getting changed? Am I using the wrong function?

Sounds like we need to assume that your textbox name and ID are both set to "Tue." If that's the case, try using a lower-case V on .value.

Center Plot title in ggplot2

From the release news of ggplot 2.2.0: "The main plot title is now left-aligned to better work better with a subtitle". See also the plot.title argument in ?theme: "left-aligned by default".

As pointed out by @J_F, you may add theme(plot.title = element_text(hjust = 0.5)) to center the title.

ggplot() +
  ggtitle("Default in 2.2.0 is left-aligned")

enter image description here

ggplot() +
  ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
  theme(plot.title = element_text(hjust = 0.5))

enter image description here

What does the term "Tuple" Mean in Relational Databases?

Tuples are known values which is used to relate the table in relational DB.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.

The JSON snippet you have posted is malformed.

You have posted:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe"[{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }]

while the correct JSON would be:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe" : [{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }
        ]
    }
]

How do you reindex an array in PHP but with indexes starting from 1?

Sorting is just a sort(), reindexing seems a bit silly but if it is needed this will do it. Though not in-place. Use array_walk() if you will do this in a bunch of places, just use a for-key-value loop if this is a one-time operation.

<?php

function reindex(&$item, $key, &$reindexedarr) {
    $reindexedarr[$key+1] = $item;
}

$arr = Array (2 => 'c', 1 => 'b', 0 => 'a');

sort($arr);
$newarr = Array();
array_walk($arr, reindex, &$newarr);
$arr = $newarr;
print_r($arr); // Array ( [1] => a [2] => b [3] => c )

?>

How to align checkboxes and their labels consistently cross-browsers

I found the only way I could line them up was using position absolute for the input. Playing around with input's top variable got the result I wanted.

div {
  clear:    both;
  float:    none;
  position: relative;
}

input {
  left:     5px;
  position: absolute;
  top:      3px;
}

label {
  display:     block;
  margin-left: 20px;
}

Converting an object to a string

One option:

console.log('Item: ' + JSON.stringify(o));

o is printed as a string

Another option (as soktinpk pointed out in the comments), and better for console debugging IMO:

console.log('Item: ', o);

o is printed as an object, which you could drill down if you had more fields

Updating the value of data attribute using jQuery

$('.toggle img').data('block', 'something');
$('.toggle img').attr('src', 'something.jpg');

Use jQuery.data and jQuery.attr.

I'm showing them to you separately for the sake of understanding.

What's the best way to join on the same table twice?

SELECT
    T1.ID
    T1.PhoneNumber1,
    T1.PhoneNumber2
    T2A.SomeOtherField AS "SomeOtherField of PhoneNumber1",
    T2B.SomeOtherField AS "SomeOtherField of PhoneNumber2"  
FROM
    Table1 T1
    LEFT JOIN Table2 T2A ON T1.PhoneNumber1 = T2A.PhoneNumber
    LEFT JOIN Table2 T2B ON T1.PhoneNumber2 = T2B.PhoneNumber
WHERE
    T1.ID = 'FOO';

LEFT JOIN or JOIN also return same result. Tested success with PostgreSQL 13.1.1 .

enter image description here

golang why don't we have a set datastructure

Partly, because Go doesn't have generics (so you would need one set-type for every type, or fall back on reflection, which is rather inefficient).

Partly, because if all you need is "add/remove individual elements to a set" and "relatively space-efficient", you can get a fair bit of that simply by using a map[yourtype]bool (and set the value to true for any element in the set) or, for more space efficiency, you can use an empty struct as the value and use _, present = the_setoid[key] to check for presence.

Click events on Pie Charts in Chart.js

If you are using TypeScript, the code is a little funky because there is no type inference, but this works to get the index of the data that has been supplied to the chart: // events public chartClicked(e:any):void { //console.log(e);

    try {
        console.log('DS ' + e.active['0']._datasetIndex);
        console.log('ID ' +  e.active['0']._index);
        console.log('Label: ' + this.doughnutChartLabels[e.active['0']._index]);
        console.log('Value: ' + this.doughnutChartData[e.active['0']._index]);


    } catch (error) {
        console.log("Error In LoadTopGraph", error);
    }

    try {
        console.log(e[0].active);
    } catch (error) {
        //console.log("Error In LoadTopGraph", error);
    }



}

android - setting LayoutParams programmatically

  LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                   /*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
                   /*height*/ ViewGroup.LayoutParams.MATCH_PARENT,
                   /*weight*/ 1.0f
            );
            YOUR_VIEW.setLayoutParams(param);

How to reset index in a pandas dataframe?

data1.reset_index(inplace=True)

Two values from one input in python?

You can't really do it the C way (I think) but a pythonic way of doing this would be (if your 'inputs' have spaces in between them):

raw_answer = raw_input()
answers = raw_answer.split(' ') # list of 'answers'

So you could rewrite your try to:

var1, var2 = raw_input("enter two numbers:").split(' ')

Note that this it somewhat less flexible than using the 'first' solution (for example if you add a space at the end this will already break).

Also be aware that var1 and var2 will still be strings with this method when not cast to int.

What is the meaning of "POSIX"?

POSIX stands for Portable Operating System Interface, and is an IEEE standard designed to facilitate application portability. POSIX is an attempt by a consortium of vendors to create a single standard version of UNIX.

Class 'ViewController' has no initializers in swift

Sometimes this error also appears when you have a var or a let that hasn't been intialized.

For example

class ViewController: UIViewController {
    var x: Double
    // or
    var y: String
    // or
    let z: Int
}

Depending on what your variable is supposed to do you might either set that var type as an optional or initialize it with a value like the following

class ViewController: UIViewCOntroller {
    // Set an initial value for the variable
    var x: Double = 0
    // or an optional String
    var y: String?
    // or
    let z: Int = 2
}

Setting network adapter metric priority in Windows 7

Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.

To change the priority of the connections:

  • Open your Adapter Settings (Control Panel\Network and Internet\Network Connections)
  • Click Alt to pull up the menu bar
  • Select Advanced -> Advanced Settings
  • Change the order of the connections so that the connection you want to have priority is top on the list

Given a DateTime object, how do I get an ISO 8601 date in string format?

Note to readers: Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.

DateTime.UtcNow.ToString("yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz");

This gives you a date similar to 2008-09-22T13:57:31.2311892-04:00.

Another way is:

DateTime.UtcNow.ToString("o");

which gives you 2008-09-22T14:01:54.9571247Z

To get the specified format, you can use:

DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")

DateTime Formatting Options

How to embed fonts in HTML?

And it's unlikely too -- EOT is a fairly restrictive format that is supported only by IE. Both Safari 3.1 and Firefox 3.1 (well the current alpha) and possibly Opera 9.6 support true type font (ttf) embedding, and at least Safari supports SVG fonts through the same mechanism. A list apart had a good discussion about this a while back.

How to Validate Google reCaptcha on Form Submit

var googleResponse = jQuery('#g-recaptcha-response').val();
if (!googleResponse) {
    $('<p style="color:red !important" class=error-captcha"><span class="glyphicon glyphicon-remove " ></span> Please fill up the captcha.</p>" ').insertAfter("#html_element");
    return false;
} else {            
    return true;
}

Put this in a function. Call this function on submit... #html_element is my empty div.

What is the best way to get the count/length/size of an iterator?

You will always have to iterate. Yet you can use Java 8, 9 to do the counting without looping explicitely:

Iterable<Integer> newIterable = () -> iter;
long count = StreamSupport.stream(newIterable.spliterator(), false).count();

Here is a test:

public static void main(String[] args) throws IOException {
    Iterator<Integer> iter = Arrays.asList(1, 2, 3, 4, 5).iterator();
    Iterable<Integer> newIterable = () -> iter;
    long count = StreamSupport.stream(newIterable.spliterator(), false).count();
    System.out.println(count);
}

This prints:

5

Interesting enough you can parallelize the count operation here by changing the parallel flag on this call:

long count = StreamSupport.stream(newIterable.spliterator(), *true*).count();

Android/Java - Date Difference in days

        public void dateDifferenceExample() {

        // Set the date for both of the calendar instance
        GregorianCalendar calDate = new GregorianCalendar(2012, 10, 02,5,23,43);
        GregorianCalendar cal2 = new GregorianCalendar(2015, 04, 02);

        // Get the represented date in milliseconds
        long millis1 = calDate.getTimeInMillis();
        long millis2 = cal2.getTimeInMillis();

        // Calculate difference in milliseconds
        long diff = millis2 - millis1;

        // Calculate difference in seconds
        long diffSeconds = diff / 1000;

        // Calculate difference in minutes
        long diffMinutes = diff / (60 * 1000);

        // Calculate difference in hours
        long diffHours = diff / (60 * 60 * 1000);

        // Calculate difference in days
        long diffDays = diff / (24 * 60 * 60 * 1000);
    Toast.makeText(getContext(), ""+diffSeconds, Toast.LENGTH_SHORT).show();


}

How to make the Facebook Like Box responsive?

As of August 4 2015, the native facebook like box have a responsive code snippet available at Facebook Developers page.

You can generate your responsive Facebook likebox here

https://developers.facebook.com/docs/plugins/page-plugin

This is the best solution ever rather than hacking CSS.

CSS to hide INPUT BUTTON value text

I had the very same problem. And as many other posts reported: the padding trick only works for IE.

font-size:0px still shows some small dots.

The only thing that worked for me is doing the opposite

font-size:999px

... but I only had buttons of 25x25 pixels.

Are SSL certificates bound to the servers ip address?

SSL certificates are bound to a 'common name', which is usually a fully qualified domain name but can be a wildcard name (eg. *.domain.com) or even an IP address, but it usually isn't.

In your case, you are accessing your LDAP server by a hostname and it sounds like your two LDAP servers have different SSL certificates installed. Are you able to view (or download and view) the details of the SSL certificate? Each SSL certificate will have a unique serial numbers and fingerprint which will need to match. I assume the certificate is being rejected as these details don't match with what's in your certificate store.

Your solution will be to ensure that both LDAP servers have the same SSL certificate installed.

BTW - you can normally override DNS entries on your workstation by editing a local 'hosts' file, but I wouldn't recommend this.

How to use sed to remove the last n lines of a file

With the answers here you'd have already learnt that sed is not the best tool for this application.

However I do think there is a way to do this in using sed; the idea is to append N lines to hold space untill you are able read without hitting EOF. When EOF is hit, print the contents of hold space and quit.

sed -e '$!{N;N;N;N;N;N;H;}' -e x

The sed command above will omit last 5 lines.

Differences between unique_ptr and shared_ptr

unique_ptr is the light-weight smart pointer of choice if you just have a dynamic object somewhere for which one consumer has sole (hence "unique") responsibility -- maybe a wrapper class that needs to maintain some dynamically allocated object. unique_ptr has very little overhead. It is not copyable, but movable. Its type is template <typename D, typename Deleter> class unique_ptr;, so it depends on two template parameters.

unique_ptr is also what auto_ptr wanted to be in the old C++ but couldn't because of that language's limitations.

shared_ptr on the other hand is a very different animal. The obvious difference is that you can have many consumers sharing responsibility for a dynamic object (hence "shared"), and the object will only be destroyed when all shared pointers have gone away. Additionally you can have observing weak pointers which will intelligently be informed if the shared pointer they're following has disappeared.

Internally, shared_ptr has a lot more going on: There is a reference count, which is updated atomically to allow the use in concurrent code. Also, there's plenty of allocation going on, one for an internal bookkeeping "reference control block", and another (often) for the actual member object.

But there's another big difference: The shared pointers type is always template <typename T> class shared_ptr;, and this is despite the fact that you can initialize it with custom deleters and with custom allocators. The deleter and allocator are tracked using type erasure and virtual function dispatch, which adds to the internal weight of the class, but has the enormous advantage that different sorts of shared pointers of type T are all compatible, no matter the deletion and allocation details. Thus they truly express the concept of "shared responsibility for T" without burdening the consumer with the details!

Both shared_ptr and unique_ptr are designed to be passed by value (with the obvious movability requirement for the unique pointer). Neither should make you worried about the overhead, since their power is truly astounding, but if you have a choice, prefer unique_ptr, and only use shared_ptr if you really need shared responsibility.

How to install sshpass on mac?

Another option in 2020 is this homebrew tap, maintained by esolitos

brew install esolitos/ipa/sshpass

How to find MAC address of an Android device programmatically

Here the Kotlin version of Arth Tilvas answer:

fun getMacAddr(): String {
    try {
        val all = Collections.list(NetworkInterface.getNetworkInterfaces())
        for (nif in all) {
            if (!nif.getName().equals("wlan0", ignoreCase=true)) continue

            val macBytes = nif.getHardwareAddress() ?: return ""

            val res1 = StringBuilder()
            for (b in macBytes) {
                //res1.append(Integer.toHexString(b & 0xFF) + ":");
                res1.append(String.format("%02X:", b))
            }

            if (res1.length > 0) {
                res1.deleteCharAt(res1.length - 1)
            }
            return res1.toString()
        }
    } catch (ex: Exception) {
    }

    return "02:00:00:00:00:00"
}

Using ExcelDataReader to read Excel data starting from a particular cell

Very easy with ExcelReaderFactory 3.1 and up:

using (var openFileDialog1 = new OpenFileDialog { Filter = "Excel Workbook|*.xls;*.xlsx;*.xlsm", ValidateNames = true })
{
    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        var fs = File.Open(openFileDialog1.FileName, FileMode.Open, FileAccess.Read);
        var reader = ExcelReaderFactory.CreateBinaryReader(fs);
        var dataSet = reader.AsDataSet(new ExcelDataSetConfiguration
        {
            ConfigureDataTable = _ => new ExcelDataTableConfiguration
            {
                UseHeaderRow = true // Use first row is ColumnName here :D
            }
        });
        if (dataSet.Tables.Count > 0)
        {
            var dtData = dataSet.Tables[0];
            // Do Something
        }
    }
}

Unstaged changes left after git reset --hard

For some reason

git add .

didn't work, but

$ git add -A

worked out!

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

Calendar currentTime = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
currentTime.set(Calendar.ZONE_OFFSET, TimeZone.getTimeZone("UTC").getRawOffset());
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, currentTime.get(Calendar.HOUR_OF_DAY));
calendar.getTimeInMillis()

is working for me

how to change the default positioning of modal in bootstrap?

Add the following css to your html and try changing the top, right, bottom, left values.

.modal {
   position: absolute;
   top: 10px;
   right: 100px;
   bottom: 0;
   left: 0;
   z-index: 10040;
   overflow: auto;
   overflow-y: auto;
}

Subset and ggplot2

Are you looking for the following plot:

library(ggplot2) 
l<-df[df$ID %in% c("P1","P3"),]
myplot<-ggplot(l)+geom_line(aes(Value1, Value2, group=ID, colour=ID))

enter image description here

Excel VBA code to copy a specific string to clipboard

Add a reference to the Microsoft Forms 2.0 Object Library and try this code. It only works with text, not with other data types.

Dim DataObj As New MSForms.DataObject

'Put a string in the clipboard
DataObj.SetText "Hello!"
DataObj.PutInClipboard

'Get a string from the clipboard
DataObj.GetFromClipboard
Debug.Print DataObj.GetText

Here you can find more details about how to use the clipboard with VBA.

How to handle-escape both single and double quotes in an SQL-Update statement

When SET QUOTED_IDENTIFIER is OFF, literal strings in expressions can be delimited by single or double quotation marks.

If a literal string is delimited by double quotation marks, the string can contain embedded single quotation marks, such as apostrophes.

What are some uses of template template parameters?

Here is a simple example taken from 'Modern C++ Design - Generic Programming and Design Patterns Applied' by Andrei Alexandrescu:

He uses a classes with template template parameters in order to implement the policy pattern:

// Library code
template <template <class> class CreationPolicy>
class WidgetManager : public CreationPolicy<Widget>
{
   ...
};

He explains: Typically, the host class already knows, or can easily deduce, the template argument of the policy class. In the example above, WidgetManager always manages objects of type Widget, so requiring the user to specify Widget again in the instantiation of CreationPolicy is redundant and potentially dangerous.In this case, library code can use template template parameters for specifying policies.

The effect is that the client code can use 'WidgetManager' in a more elegant way:

typedef WidgetManager<MyCreationPolicy> MyWidgetMgr;

Instead of the more cumbersome, and error prone way that a definition lacking template template arguments would have required:

typedef WidgetManager< MyCreationPolicy<Widget> > MyWidgetMgr;

Git push hangs when pushing to Github?

Its worth checking if you are using the cygwin git or an external git (ie github).

If whereis git returns just /cygdrive/c/Program Files (x86)/Git/cmd/git.exe or similar its best to install the cygwin git package, this solved the problem for me.

How to build a DataTable from a DataGridView?

First convert you datagridview's data to List, then convert List to DataTable

        public static DataTable ToDataTable<T>( this List<T> list) where T : class {
        Type type = typeof(T);
        var ps = type.GetProperties ( );
        var cols = from p in ps
                   select new DataColumn ( p.Name , p.PropertyType );

        DataTable dt = new DataTable();
        dt.Columns.AddRange(cols.ToArray());

        list.ForEach ( (l) => {
            List<object> objs = new List<object>();
            objs.AddRange ( ps.Select ( p => p.GetValue ( l , null ) ) );
            dt.Rows.Add ( objs.ToArray ( ) );
        } );

        return dt;
    }

Leaflet - How to find existing markers, and delete markers?

In my case, I have various layer groups so that users can show/hide clusters of like type markers. But, in any case you delete an individual marker by looping over your layer groups to find and delete it. While looping, search for a marker with a custom attribute, in my case a 'key', added when the marker was added to the layer group. Add your 'key' just like adding a title attribute. Later this is gotten an a layer option. When you find that match, you .removeLayer() and it gets rid of that particular marker. Hope that helps you out!

eventsLayerGroup.addLayer(L.marker([tag.latitude, tag.longitude],{title:tag.title, layer:tag.layer, timestamp:tag.timestamp, key:tag.key, bounceOnAdd: true, icon: L.AwesomeMarkers.icon({icon: 'vignette', markerColor: 'blue', prefix: '', iconColor: 'white'}) }).bindPopup(customPopup(tag),customOptions).on('click', markerClick)); 

function removeMarker(id){
    var layerGroupsArray = [eventsLayerGroup,landmarksLayerGroup,travelerLayerGroup,marketplaceLayerGroup,myLayerGroup];
    $.each(layerGroupsArray, function (key, value) {
        value.eachLayer(function (layer) {
            if(typeof value !== "undefined"){
                if (layer.options.layer){
                    console.log(layer.options.key);
                    console.log(id);
                    if (id === layer.options.key){
                        value.removeLayer(layer);
                    }
                }
            }
        });
    });
}

How to find the users list in oracle 11g db?

I am not sure what you understand by "execute from the Command line interface", but you're probably looking after the following select statement:

select * from dba_users;

or

select username from dba_users;

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

for xcode 11.1which doesn't contain ipad pro iPad Pro (2nd Gen) 12.9" Display run this command in terminal

xcrun simctl create "iPad Pro (12.9-inch) (2nd generation)" "com.apple.CoreSimulator.SimDeviceType.iPad-Pro--12-9-inch---2nd-generation-" "com.apple.CoreSimulator.SimRuntime.iOS-13-1"

look here

Upload Image using POST form data in Python-requests

For Rest API to upload images from host to host:

import urllib2
import requests

api_host = 'https://host.url.com/upload/'
headers = {'Content-Type' : 'image/jpeg'}
image_url = 'http://image.url.com/sample.jpeg'

img_file = urllib2.urlopen(image_url)

response = requests.post(api_host, data=img_file.read(), headers=headers, verify=False)

You can use option verify set to False to omit SSL verification for HTTPS requests.

How to set image name in Dockerfile?

Here is another version if you have to reference a specific docker file:

version: "3"
services:
  nginx:
    container_name: nginx
    build:
      context: ../..
      dockerfile: ./docker/nginx/Dockerfile
    image: my_nginx:latest

Then you just run

docker-compose build

Can I use VARCHAR as the PRIMARY KEY?

It is ok for sure. With just few hundred of entries, it will be fast.

You can add an unique id as as primary key (int autoincrement) ans set your coupon_code as unique. So if you need to do request in other tables it's better to use int than varchar

Mongodb: failed to connect to server on first connect

If the mongo instance is build on the cloud.mongodb.com this error appears when the instance can work only from known IP addresses set in the IP whitelist pool when the instance was configured.

So from the mongo dashboard need to be set the current IP address on the IP whitelist from network access menu on the left.

BR,

Failing to run jar file from command line: “no main manifest attribute”

If you are using Spring boot, you should add this plugin in your pom.xml:

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

How do I add a auto_increment primary key in SQL Server database?

you can try this... ALTER TABLE Your_Table ADD table_ID int NOT NULL PRIMARY KEY auto_increment;

Unit Tests not discovered in Visual Studio 2017

The Issue

The problem is that Visual Studio is getting 'confused' over the dotnet core versions on the machine. When I went to control panel -> uninstall programs I had 8 different dotnet core SDK's and Runtimes installed. This was somehow causing VS to silently have an error when trying to find tests.

Validate The Issue

You can validate the issue by going to the command line and getting the version of dotnet your on $ dotnet --version. If you see anything except the latest version you have installed then your machine has some mismatch and is not using the correct version. Example...If you have dotnet core 1.0.1 installed but when you get the version at command prompt and it says 1.0.0 thats a problem.

The Solution

Delete all the old stuff. I started with only what I though I needed to remove (the oldest dotnet rc versions) but it still gave the wrong version when testing the issue. Eventually I conceded to do a full clean. I...

  • Uninstalled all visual studio applications (on my machine VS2015 and VS2017)
  • Uninstalled all versions of dotnet core (even most recent)

After my machine was completely empty of all VS and donet I installed only VS2017 (it comes packaged with latest dotnet). I created a xUnit test project and the test explorer found the test immediately SOLVED

This may seem like overkill but I spent two weeks trying to fix this in other ways. If your having the issue just do it, even though it may take you hours to uninstall/reinstall items it will probably save you time.

References

  • See @epestic blog post where he gives more detail on fixing the issue.

SQL where datetime column equals today's date?

Looks like you're using SQL Server, in which case GETDATE() or current_timestamp may help you. But you will have to ensure that the format of the date with which you are comparing the system dates matches (timezone, granularity etc.)

e.g.

where convert(varchar(10), submission_date, 102) 
    = convert(varchar(10), getdate(), 102)

Switch to selected tab by name in Jquery-UI Tabs

Use this function:

function uiTabs(i){
    $("#tabs").tabs("option", "selected", i);
}

And use following code to switch between tabs:

<a onclick="uiTabs(0)">Tab 1</a>
<a onclick="uiTabs(1)">Tab 2</a>
<a onclick="uiTabs(2)">Tab 3</a>

Add an element to an array in Swift

To add to the end, use the += operator:

myArray += ["Craig"]
myArray += ["Jony", "Eddy"]

That operator is generally equivalent to the append(contentsOf:) method. (And in really old Swift versions, could append single elements, not just other collections of the same element type.)

There's also insert(_:at:) for inserting at any index.

If, say, you'd like a convenience function for inserting at the beginning, you could add it to the Array class with an extension.

Can I call an overloaded constructor from another constructor of the same class in C#?

No, You can't do that, the only place you can call the constructor from another constructor in C# is immediately after ":" after the constructor. for example

class foo
{
    public foo(){}
    public foo(string s ) { }
    public foo (string s1, string s2) : this(s1) {....}

}

vertical divider between two columns in bootstrap

_x000D_
_x000D_
.row.vertical-divider {_x000D_
  overflow: hidden;_x000D_
}_x000D_
.row.vertical-divider > div[class^="col-"] {_x000D_
  text-align: center;_x000D_
  padding-bottom: 100px;_x000D_
  margin-bottom: -100px;_x000D_
  border-left: 3px solid #F2F7F9;_x000D_
  border-right: 3px solid #F2F7F9;_x000D_
}_x000D_
.row.vertical-divider div[class^="col-"]:first-child {_x000D_
  border-left: none;_x000D_
}_x000D_
.row.vertical-divider div[class^="col-"]:last-child {_x000D_
  border-right: none;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="row vertical-divider" style="margin-top: 30px">_x000D_
  <div class="col-xs-6">Hi there</div>_x000D_
  <div class="col-xs-6">Hi world<br/>hi world</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to run cron once, daily at 10pm

To run once, daily at 10PM you should do something like this:

0 22 * * *

enter image description here

Full size image: http://i.stack.imgur.com/BeXHD.jpg

Source: softpanorama.org

Creating stored procedure with declare and set variables

I assume you want to pass the Order ID in. So:

CREATE PROCEDURE [dbo].[Procedure_Name]
(
    @OrderID INT
) AS
BEGIN
    Declare @OrderItemID AS INT
    DECLARE @AppointmentID AS INT
    DECLARE @PurchaseOrderID AS INT
    DECLARE @PurchaseOrderItemID AS INT
    DECLARE @SalesOrderID AS INT
    DECLARE @SalesOrderItemID AS INT

    SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
    SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
    SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END

swift How to remove optional String Character

Although we might have different contexts, the below worked for me.

I wrapped every part of my variable in brackets and then added an exclamation mark outside the right closing bracket.

For example, print(documentData["mileage"]) is changed to:

print((documentData["mileage"])!)

How can I dynamically switch web service addresses in .NET without a recompile?

As long as the web service methods and underlying exposed classes do not change, it's fairly trivial. With Visual Studio 2005 (and newer), adding a web reference creates an app.config (or web.config, for web apps) section that has this URL. All you have to do is edit the app.config file to reflect the desired URL.

In our project, our simple approach was to just have the app.config entries commented per environment type (development, testing, production). So we just uncomment the entry for the desired environment type. No special coding needed there.

Changing the color of a clicked table row using jQuery

Remove the second id declaration of table:

<table id="data" border="1" cellspacing="1" width="500" **id="table1"**>

How can I make setInterval also work when a tab is inactive in Chrome?

Heavily influenced by Ruslan Tushov's library, I've created my own small library. Just add the script in the <head> and it will patch setInterval and setTimeout with ones that use WebWorker.

Change Screen Orientation programmatically using a Button

Wherever possible, please don't use SCREEN_ORIENTATION_LANDSCAPE or SCREEN_ORIENTATION_PORTRAIT. Instead use:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

These allow the user to orient the device to either landscape orientation, or either portrait orientation, respectively. If you've ever had to play a game with a charging cable being driven into your stomach, then you know exactly why having both orientations available is important to the user.

Note: For phones, at least several that I've checked, it only allows the "right side up" portrait mode, however, SENSOR_PORTRAIT works properly on tablets.

Note: this feature was introduced in API Level 9, so if you must support 8 or lower (not likely at this point), then instead use:

setRequestedOrientation(Build.VERSION.SDK_INT < 9 ?
                        ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE :
                        ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
setRequestedOrientation(Build.VERSION.SDK_INT < 9 ?
                        ActivityInfo.SCREEN_ORIENTATION_PORTRAIT :
                        ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT);

How can I get column names from a table in SQL Server?

You can try this.This gives all the column names with their respective data types.

desc <TABLE NAME> ;

How to retrieve form values from HTTPPOST, dictionary or?

You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:

[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
    var value1 = model.SimpleProp1;
    var value2 = model.SimpleProp2;
    var value3 = model.ComplexProp1.SimpleProp1;
    ...

    ... return something ...
}

Another (obviously uglier) way is:

[HttpPost]
public ActionResult SubmitAction()
{
    var value1 = Request["SimpleProp1"];
    var value2 = Request["SimpleProp2"];
    var value3 = Request["ComplexProp1.SimpleProp1"];
    ...

    ... return something ...
}

CSS: Responsive way to center a fluid div (without px width) while limiting the maximum width?

This might sound really simplistic...

But this will center the div inside the div, exactly in the center in relation to left and right margin or parent container, but you can adjust percentage symmetrically on left and right.

margin-right: 10%;
margin-left: 10%;

Then you can adjust % to make it as wide as you want it.

Select all 'tr' except the first one

Though the question has a decent answer already, I just want to stress that the :first-child tag goes on the item type that represents the children.

For example, in the code:

<div id"someDiv">
     <input id="someInput1" /> 
     <input id="someInput2" />
     <input id="someInput2" />
</div

If you want to affect only the second two elements with a margin, but not the first, you would do:

#someDiv > input {
     margin-top: 20px;
}
#someDiv > input:first-child{
     margin-top: 0px;
}

that is, since the inputs are the children, you would place first-child on the input portion of the selector.

How can I pass a file argument to my bash script using a Terminal command in Linux?

It'll be easier (and more "proper", see below) if you just run your script as

myprogram /path/to/file

Then you can access the path within the script as $1 (for argument #1, similarly $2 is argument #2, etc.)

file="$1"
externalprogram "$file" [other parameters]

Or just

externalprogram "$1" [otherparameters]

If you want to extract the path from something like --file=/path/to/file, that's usually done with the getopts shell function. But that's more complicated than just referencing $1, and besides, switches like --file= are intended to be optional. I'm guessing your script requires a file name to be provided, so it doesn't make sense to pass it in an option.

How to set downloading file name in ASP.NET Web API

Considering the previous answers, it is necessary to be careful with globalized characters.

Suppose the name of the file is: "Esdrújula prenda ñame - güena.jpg"

Raw result to download: "Esdrújula prenda ñame - güena.jpg" [Ugly]

HtmlEncode result to download: "Esdr&_250;jula prenda &_241;ame - g&_252;ena.jpg" [Ugly]

UrlEncode result to download: "Esdrújula+prenda+ñame+-+güena.jpg" [OK]

Then, you need almost always to use the UrlEncode over the file name. Moreover, if you set the content-disposition header as direct string, then you need to ensure surround with quotes to avoid browser compatibility issues.

Response.AddHeader("Content-Disposition", $"attachment; filename=\"{HttpUtility.UrlEncode(YourFilename)}\"");

or with class aid:

var cd = new ContentDisposition("attachment") { FileName = HttpUtility.UrlEncode(resultFileName) };
Response.AddHeader("Content-Disposition", cd.ToString());

The System.Net.Mime.ContentDisposition class takes care of quotes.

Aggregate / summarize multiple variables per group (e.g. sum, mean)

Late to the party, but recently found another way to get the summary statistics.

library(psych) describe(data)

Will output: mean, min, max, standard deviation, n, standard error, kurtosis, skewness, median, and range for each variable.

How to specify multiple return types using type-hints

Python 3.10 (use |): Example for a function which takes a single argument that is either an int or str and returns either an int or str:

def func(arg: int | str) -> int | str:
              ^^^^^^^^^     ^^^^^^^^^ 
             type of arg   return type

Python 3.5 - 3.9 (use typing.Union):

from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
              ^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^ 
                type of arg         return type

For the special case of X | None you can use Optional[X].

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!

Combating AngularJS executing controller twice

I just went through this, but the issue was different from the accepted answer. I'm really leaving this here for my future self, to include the steps I went through to fix it.

  1. Remove redundant controller declarations
  2. Check trailing slashes in routes
  3. Check for ng-ifs
  4. Check for any unnecessary wrapping ng-view calls (I accidentally had left in an ng-view that was wrapping my actual ng-view. This resulted in three calls to my controllers.)
  5. If you are on Rails, you should remove the turbolinks gem from your application.js file. I wasted a whole day to discover that. Found answer here.
  6. Initializing the app twice with ng-app and with bootstrap. Combating AngularJS executing controller twice
  7. When using $compile on whole element in 'link'-function of directive that also has its own controller defined and uses callbacks of this controller in template via ng-click etc. Found answer here.

How to display svg icons(.svg files) in UI using React Component?

If you want to use SVG files as React components to perform customizations and do not use create-react-app, do the following:

  1. Install the Webpack loader called svgr
yarn add --dev @svgr/webpack
  1. Update your webpack.config.js
  ...
  module: {
    rules: [
      ...
      // SVG loader
      {
        test: /\.svg$/,
        use: ['@svgr/webpack'],
      }
    ],
  },
  ...
  1. Import SVG files as React component
import SomeImage from 'path/to/image.svg'

...

<SomeImage width={100} height={50} fill="pink" stroke="#0066ff" />

Choose folders to be ignored during search in VS Code

Make sure the 'Use Exclude Settings and Ignore Files' cog is selected enter image description here

C++ Dynamic Shared Library on Linux

On top of previous answers, I'd like to raise awareness about the fact that you should use the RAII (Resource Acquisition Is Initialisation) idiom to be safe about handler destruction.

Here is a complete working example:

Interface declaration: Interface.hpp:

class Base {
public:
    virtual ~Base() {}
    virtual void foo() const = 0;
};

using Base_creator_t = Base *(*)();

Shared library content:

#include "Interface.hpp"

class Derived: public Base {
public:
    void foo() const override {}
};

extern "C" {
Base * create() {
    return new Derived;
}
}

Dynamic shared library handler: Derived_factory.hpp:

#include "Interface.hpp"
#include <dlfcn.h>

class Derived_factory {
public:
    Derived_factory() {
        handler = dlopen("libderived.so", RTLD_NOW);
        if (! handler) {
            throw std::runtime_error(dlerror());
        }
        Reset_dlerror();
        creator = reinterpret_cast<Base_creator_t>(dlsym(handler, "create"));
        Check_dlerror();
    }

    std::unique_ptr<Base> create() const {
        return std::unique_ptr<Base>(creator());
    }

    ~Derived_factory() {
        if (handler) {
            dlclose(handler);
        }
    }

private:
    void * handler = nullptr;
    Base_creator_t creator = nullptr;

    static void Reset_dlerror() {
        dlerror();
    }

    static void Check_dlerror() {
        const char * dlsym_error = dlerror();
        if (dlsym_error) {
            throw std::runtime_error(dlsym_error);
        }
    }
};

Client code:

#include "Derived_factory.hpp"

{
    Derived_factory factory;
    std::unique_ptr<Base> base = factory.create();
    base->foo();
}

Note:

  • I put everything in header files for conciseness. In real life you should of course split your code between .hpp and .cpp files.
  • To simplify, I ignored the case where you want to handle a new/delete overload.

Two clear articles to get more details:

Reload chart data via JSON with Highcharts

You can always load a json data

here i defined Chart as namespace

 $.getJSON('data.json', function(data){
                Chart.options.series[0].data = data[0].data;
                Chart.options.series[1].data = data[1].data;
                Chart.options.series[2].data = data[2].data;

                var chart = new Highcharts.Chart(Chart.options);

            });

Creating an Instance of a Class with a variable in Python

Given your edit i assume you have the class name as a string and want to instantiate the class? Just use a dictionary as a dispatcher.

class Foo(object):
    pass

class Bar(object):
    pass

dispatch_dict = {"Foo": Foo, "Bar": Bar}
dispatch_dict["Foo"]() # returns an instance of Foo

How to clear exisiting dropdownlist items when its content changes?

just compiled your code and the only thing that is missing from it is that you have to Bind your ddl2 to an empty datasource before binding it again like this:

Protected Sub ddl1_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) //ddl2.Items.Clear()

ddl2.DataSource=New List(Of String)()
ddl2.DataSource = sql2
ddl2.DataBind() End Sub

and it worked just fine

Oracle - What TNS Names file am I using?

Oracle provides a utility called tnsping:

R:\>tnsping someconnection

TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:38:07

Copyright (c) 1997 Oracle Corporation.  All rights reserved.

Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora

TNS-03505: Failed to resolve name

R:\>


R:\>tnsping entpr01

TNS Ping Utility for 32-bit Windows: Version 9.0.1.3.1 - Production on 27-AUG-20
08 10:39:22

Copyright (c) 1997 Oracle Corporation.  All rights reserved.

Used parameter files:
C:\Oracle92\network\ADMIN\sqlnet.ora
C:\Oracle92\network\ADMIN\tnsnames.ora

Used TNSNAMES adapter to resolve the alias
Attempting to contact (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (COMMUNITY = **)
 (PROTOCOL = TCP) (Host = ****) (Port = 1521))) (CONNECT_DATA = (SID = ENTPR0
1)))
OK (40 msec)

R:\>

This should show what file you're using. The utility sits in the Oracle bin directory.

How can I check for an empty/undefined/null string in JavaScript?

I have not noticed an answer that takes into account the possibility of null characters in a string. For example, if we have a null character string:

var y = "\0"; // an empty string, but has a null character
(y === "") // false, testing against an empty string does not work
(y.length === 0) // false
(y) // true, this is also not expected
(y.match(/^[\s]*$/)) // false, again not wanted

To test its nullness one could do something like this:

String.prototype.isNull = function(){ 
  return Boolean(this.match(/^[\0]*$/)); 
}
...
"\0".isNull() // true

It works on a null string, and on an empty string and it is accessible for all strings. In addition, it could be expanded to contain other JavaScript empty or whitespace characters (i.e. nonbreaking space, byte order mark, line/paragraph separator, etc.).

Manifest merger failed : uses-sdk:minSdkVersion 14

The problem still arises with transitive dependencies. Gradle offers a way to force the usage of a specific version of a dependency.

For example you can add something like:

configurations.all {
    resolutionStrategy {
        force 'com.android.support:support-v4:20.+'
        force 'com.android.support:appcompat-v7:20.+'
    }
}

to your build.gradle.

If you want to learn more about gradle resolution strategies refer to this guide http://www.gradle.org/docs/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html

I found this while reading the corresponding issue which I will link here

HTTP Error 503. The service is unavailable. App pool stops on accessing website

In my case I checked event logs and found error was Cannot read configuration file ' trying to read configuration data from file '\\?\', line number '0'. The data field contains the error code.

The error code was 2307.

I deleted all files in C:\inetpub\temp\appPools and restarted the iis. It fixed the issue.

Auto line-wrapping in SVG text

This functionality can also be added using JavaScript. Carto.net has an example:

http://old.carto.net/papers/svg/textFlow/

Something else that also might be useful to are you are editable text areas:

http://old.carto.net/papers/svg/gui/textbox/

Right way to reverse a pandas DataFrame?

You can reverse the rows in an even simpler way:

df[::-1]

SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax — PHP — PDO

ALTER TABLE `{$installer->getTable('sales/quote_payment')}`
ADD `custom_field_one` VARCHAR( 255 ) NOT NULL,
    ADD `custom_field_two` VARCHAR( 255 ) NOT NULL;

Add backtick i.e. " ` " properly. Write your getTable name and column name between backtick.

Adding a new entry to the PATH variable in ZSH

Here, add this line to .zshrc:

export PATH=/home/david/pear/bin:$PATH

EDIT: This does work, but ony's answer below is better, as it takes advantage of the structured interface ZSH provides for variables like $PATH. This approach is standard for bash, but as far as I know, there is no reason to use it when ZSH provides better alternatives.

"Field has incomplete type" error

The problem is that your ui property uses a forward declaration of class Ui::MainWindowClass, hence the "incomplete type" error.

Including the header file in which this class is declared will fix the problem.

EDIT

Based on your comment, the following code:

namespace Ui
{
    class MainWindowClass;
}

does NOT declare a class. It's a forward declaration, meaning that the class will exist at some point, at link time.
Basically, it just tells the compiler that the type will exist, and that it shouldn't warn about it.

But the class has to be defined somewhere.

Note this can only work if you have a pointer to such a type.
You can't have a statically allocated instance of an incomplete type.

So either you actually want an incomplete type, and then you should declare your ui member as a pointer:

namespace Ui
{
    // Forward declaration - Class will have to exist at link time
    class MainWindowClass;
}

class MainWindow : public QMainWindow
{
    private:

        // Member needs to be a pointer, as it's an incomplete type
        Ui::MainWindowClass * ui;
};

Or you want a statically allocated instance of Ui::MainWindowClass, and then it needs to be declared. You can do it in another header file (usually, there's one header file per class).
But simply changing the code to:

namespace Ui
{
    // Real class declaration - May/Should be in a specific header file
    class MainWindowClass
    {};
}


class MainWindow : public QMainWindow
{
    private:

        // Member can be statically allocated, as the type is complete
        Ui::MainWindowClass ui;
};

will also work.

Note the difference between the two declarations. First uses a forward declaration, while the second one actually declares the class (here with no properties nor methods).

How to get GMT date in yyyy-mm-dd hh:mm:ss in PHP

Try this

Check this How do i get the gmt time in php

date_default_timezone_set("UTC");
echo date("Y-m-d H:i:s", time()); 

When should an IllegalArgumentException be thrown?

Throwing runtime exceptions "sparingly" isn't really a good policy -- Effective Java recommends that you use checked exceptions when the caller can reasonably be expected to recover. (Programmer error is a specific example: if a particular case indicates programmer error, then you should throw an unchecked exception; you want the programmer to have a stack trace of where the logic problem occurred, not to try to handle it yourself.)

If there's no hope of recovery, then feel free to use unchecked exceptions; there's no point in catching them, so that's perfectly fine.

It's not 100% clear from your example which case this example is in your code, though.

Easier way to debug a Windows service

I think it depends on what OS you are using, Vista is much harder to attach to Services, because of the separation between sessions.

The two options I've used in the past are:

  • Use GFlags (in the Debugging Tools for Windows) to setup a permanent debugger for a process. This exists in the "Image File Execution Options" registry key and is incredibly useful. I think you'll need to tweak the Service settings to enable "Interact with Desktop". I use this for all types of debugging, not just services.
  • The other option, is to separate the code a bit, so that the service part is interchangable with a normal app startup. That way, you can use a simple command line flag, and launch as a process (rather than a Service), which makes it much easier to debug.

Hope this helps.

What does IFormatProvider do?

Passing null as the IFormatProvider is not the correct way to do this. If the user has a custom date/time format on their PC you'll have issues in parsing and converting to string. I've just fixed a bug where somebody had passed null as the IFormatProvider when converting to string.

Instead you should be using CultureInfo.InvariantCulture

Wrong:

string output = theDate.ToString("dd/MM/yy HH:mm:ss.fff", null);

Correct:

string output = theDate.ToString("dd/MM/yy HH:mm:ss.fff", CultureInfo.InvariantCulture);

HTML form submit to PHP script

Here is what I find works

  1. Set a form name
  2. Use a default select option, for example...

    <option value="-1" selected>Please Select</option>

So that if the form is submitted, use of JavaScript to halt the submission process can be implemented and verified at the server too.

  1. Try to use HTML5 attributes now they are supported.

This input

<input type="submit">

should be

<input name="Submit" type="submit" value="Submit">

whenever I use a form that fails, it is a failure due to the difference in calling the button name submit and name as Submit.

You should also set your enctype attribute for your form as forms fail on my web host if it's not set.

How do you add an action to a button programmatically in xcode

IOS 14 SDK: you can add action with closure callback:

let button = UIButton(type: .system, primaryAction: UIAction(title: "Button Title", handler: { _ in
            print("Button tapped!")
        }))

Getting a reference to the control sender

let textField = UITextField()
textField.addAction(UIAction(title: "", handler: { action in
    let textField = action.sender as! UITextField
    print("Text is \(textField.text)")
}), for: .editingChanged)

source

Use CSS to automatically add 'required field' asterisk to form inputs

For those who end up here, but have jQuery:

// javascript / jQuery
$("label.required").append('<span class="red-star"> *</span>')

// css
.red-star { color: red; }

How to search through all Git and Mercurial commits in the repository for a certain string?

Don't know about git, but in Mercurial I'd just pipe the output of hg log to some sed/perl/whatever script to search for whatever it is you're looking for. You can customize the output of hg log using a template or a style to make it easier to search on, if you wish.

This will include all named branches in the repo. Mercurial does not have something like dangling blobs afaik.

Formatting MM/DD/YYYY dates in textbox in VBA

Private Sub txtBoxBDayHim_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
If KeyAscii >= 48 And KeyAscii <= 57 Or KeyAscii = 8 Then 'only numbers and backspace
    If KeyAscii = 8 Then 'if backspace, ignores + "/"
    Else
        If txtBoxBDayHim.TextLength = 10 Then 'limit textbox to 10 characters
        KeyAscii = 0
        Else
            If txtBoxBDayHim.TextLength = 2 Or txtBoxBDayHim.TextLength = 5 Then 'adds / automatically
            txtBoxBDayHim.Text = txtBoxBDayHim.Text + "/"
            End If
        End If
    End If
Else
KeyAscii = 0
End If
End Sub

This works for me. :)

Your code helped me a lot. Thanks!

I'm brazilian and my english is poor, sorry for any mistake.

How to catch SQLServer timeout exceptions

I am not sure but when we have execute time out or command time out The client sends an "ABORT" to SQL Server then simply abandons the query processing. No transaction is rolled back, no locks are released. to solve this problem I Remove transaction in Stored-procedure and use SQL Transaction in my .Net Code To manage sqlException

What are native methods in Java and where should they be used?

Native methods allow you to use code from other languages such as C or C++ in your java code. You use them when java doesn't provide the functionality that you need. For example, if I were writing a program to calculate some equation and create a line graph of it, I would use java, because it is the language I am best in. However, I am also proficient in C. Say in part of my program I need to calculate a really complex equation. I would use a native method for this, because I know some C++ and I know that C++ is much faster than java, so if I wrote my method in C++ it would be quicker. Also, say I want to interact with another program or device. This would also use a native method, because C++ has something called pointers, which would let me do that.

Decode Base64 data in Java

Another late answer, but my benchmarking shows that Jetty's implementation of Base64 encoder is pretty fast. Not as fast as MiGBase64 but faster than iHarder Base64.

import org.eclipse.jetty.util.B64Code;

final String decoded = B64Code.decode(encoded, "UTF-8");

I also did some benchmarks:

      library     |    encode    |    decode   
------------------+--------------+-------------
 'MiGBase64'      |  10146001.00 |  6426446.00
 'Jetty B64Code'  |   8846191.00 |  3101361.75
 'iHarder Base64' |   3259590.50 |  2505280.00
 'Commons-Codec'  |    241318.04 |   255179.96

These are runs/sec so higher is better.

jQuery - select the associated label element of a input field

You shouldn't rely on the order of elements by using prev or next. Just use the for attribute of the label, as it should correspond to the ID of the element you're currently manipulating:

var label = $("label[for='" + $(this).attr('id') + "']");

However, there are some cases where the label will not have for set, in which case the label will be the parent of its associated control. To find it in both cases, you can use a variation of the following:

var label = $('label[for="' + $(this).attr('id') + '"]');

if(label.length <= 0) {
    var parentElem = $(this).parent(),
        parentTagName = parentElem.get(0).tagName.toLowerCase();

    if(parentTagName == "label") {
        label = parentElem;
    }
}

I hope this helps!

JavaScript Object Id

No, objects don't have a built in identifier, though you can add one by modifying the object prototype. Here's an example of how you might do that:

(function() {
    var id = 0;

    function generateId() { return id++; };

    Object.prototype.id = function() {
        var newId = generateId();

        this.id = function() { return newId; };

        return newId;
    };
})();

That said, in general modifying the object prototype is considered very bad practice. I would instead recommend that you manually assign an id to objects as needed or use a touch function as others have suggested.

Eclipse shows errors but I can't find them

I just removed all the private libraries in JavaBuildPath and added the jars again.. It worked

rm: cannot remove: Permission denied

The code says everything:

max@serv$ chmod 777 .

Okay, it doesn't say everything.

In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

Timeout function if it takes too long to finish

I rewrote David's answer using the with statement, it allows you do do this:

with timeout(seconds=3):
    time.sleep(4)

Which will raise a TimeoutError.

The code is still using signal and thus UNIX only:

import signal

class timeout:
    def __init__(self, seconds=1, error_message='Timeout'):
        self.seconds = seconds
        self.error_message = error_message
    def handle_timeout(self, signum, frame):
        raise TimeoutError(self.error_message)
    def __enter__(self):
        signal.signal(signal.SIGALRM, self.handle_timeout)
        signal.alarm(self.seconds)
    def __exit__(self, type, value, traceback):
        signal.alarm(0)

How to get the full URL of a Drupal page?

You can also do it this way:

$current_url = 'http://' .$_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];

It's a bit faster.

What are best practices for multi-language database design?

I recommend the answer posted by Martin.

But you seem to be concerned about your queries getting too complex:

To create localized table for every table is making design and querying complex...

So you might be thinking, that instead of writing simple queries like this:

SELECT price, name, description FROM Products WHERE price < 100

...you would need to start writing queries like that:

SELECT
  p.price, pt.name, pt.description
FROM
  Products p JOIN ProductTranslations pt
  ON (p.id = pt.id AND pt.lang = "en")
WHERE
  price < 100

Not a very pretty perspective.

But instead of doing it manually you should develop your own database access class, that pre-parses the SQL that contains your special localization markup and converts it to the actual SQL you will need to send to the database.

Using that system might look something like this:

db.setLocale("en");
db.query("SELECT p.price, _(p.name), _(p.description)
          FROM _(Products p) WHERE price < 100");

And I'm sure you can do even better that that.

The key is to have your tables and fields named in uniform way.

How to quickly check if folder is empty (.NET)?

There is a new feature in Directory and DirectoryInfo in .NET 4 that allows them to return an IEnumerable instead of an array, and start returning results before reading all the directory contents.

public bool IsDirectoryEmpty(string path)
{
    IEnumerable<string> items = Directory.EnumerateFileSystemEntries(path);
    using (IEnumerator<string> en = items.GetEnumerator())
    {
        return !en.MoveNext();
    }
}

EDIT: seeing that answer again, I realize this code can be made much simpler...

public bool IsDirectoryEmpty(string path)
{
    return !Directory.EnumerateFileSystemEntries(path).Any();
}

ERROR 1049 (42000): Unknown database

Very simple solution. Just rename your database and configure your new database name in your project.

The problem is the when you import your database, you got any errors and then the database will be corrupted. The log files will have the corrupted database name. You can rename your database easily using phpmyadmin for mysql.

phpmyadmin -> operations -> Rename database to

MySql sum elements of a column

select
  sum(a) as atotal,
  sum(b) as btotal,
  sum(c) as ctotal
from
  yourtable t
where
  t.id in (1, 2, 3)

Using Tkinter in python to edit the title bar

For anybody who runs into the issue of having two windows open, and runs across this question. Here is how I stumbled upon a solution.

The reason the code in this question is producing two windows is because

Frame.__init__(self, parent)

is being run before

self.root = Tk()

The simple fix is to run Tk() before running Frame.__init_()

self.root = Tk()
Frame.__init__(self, parent)

Why that is the case, I'm not entirely sure.

Open application after clicking on Notification

Use below code for create notification for open activity. It works for me. For full code

 Intent myIntent = new Intent(context, DoSomething.class);
 PendingIntent pendingIntent = PendingIntent.getActivity(
        context, 
        0, 
        myIntent, 
        Intent.FLAG_ACTIVITY_NEW_TASK);

 myNotification = new NotificationCompat.Builder(context)
   .setContentTitle("Exercise of Notification!")
   .setContentText("Do Something...")
   .setTicker("Notification!")
   .setWhen(System.currentTimeMillis())
   .setContentIntent(pendingIntent)
   .setDefaults(Notification.DEFAULT_SOUND)
   .setAutoCancel(true)
   .setSmallIcon(R.drawable.ic_launcher)
   .build();

 notificationManager = 
   (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
 notificationManager.notify(MY_NOTIFICATION_ID, myNotification);

How to make a JFrame button open another JFrame class in Netbeans?

new SecondForm().setVisible(true);

You can either use setVisible(false) or dispose() method to disappear current form.

Writing to a new file if it doesn't exist, and appending to a file if it does

Just open it in 'a' mode:

a   Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file.

with open(filename, 'a') as f:
    f.write(...)

To see whether you're writing to a new file, check the stream position. If it's zero, either the file was empty or it is a new file.

with open('somefile.txt', 'a') as f:
    if f.tell() == 0:
        print('a new file or the file was empty')
        f.write('The header\n')
    else:
        print('file existed, appending')
    f.write('Some data\n')

If you're still using Python 2, to work around the bug, either add f.seek(0, os.SEEK_END) right after open or use io.open instead.

Postgresql SQL: How check boolean field with null and True,False Value?

There are 3 states for boolean in PG: true, false and unknown (null). Explained here: Postgres boolean datatype

Therefore you need only query for NOT TRUE:

SELECT * from table_name WHERE boolean_column IS NOT TRUE;

Differences between TCP sockets and web sockets, one more time

WebSocket is basically an application protocol (with reference to the ISO/OSI network stack), message-oriented, which makes use of TCP as transport layer.

The idea behind the WebSocket protocol consists of reusing the established TCP connection between a Client and Server. After the HTTP handshake the Client and Server start speaking WebSocket protocol by exchanging WebSocket envelopes. HTTP handshaking is used to overcome any barrier (e.g. firewalls) between a Client and a Server offering some services (usually port 80 is accessible from anywhere, by anyone). Client and Server can switch over speaking HTTP in any moment, making use of the same TCP connection (which is never released).

Behind the scenes WebSocket rebuilds the TCP frames in consistent envelopes/messages. The full-duplex channel is used by the Server to push updates towards the Client in an asynchronous way: the channel is open and the Client can call any futures/callbacks/promises to manage any asynchronous WebSocket received message.

To put it simply, WebSocket is a high level protocol (like HTTP itself) built on TCP (reliable transport layer, on per frame basis) that makes possible to build effective real-time application with JS Clients (previously Comet and long-polling techniques were used to pull updates from the Server before WebSockets were implemented. See Stackoverflow post: Differences between websockets and long polling for turn based game server ).

Add Favicon to Website

Simply put a file named favicon.ico in the webroot.

If you want to know more, please start reading:

I can't delete a remote master branch on git

To answer the question literally (since GitHub is not in the question title), also be aware of this post over on superuser. EDIT: Answer copied here in relevant part, slightly modified for clarity in square brackets:

You're getting rejected because you're trying to delete the branch that your origin has currently "checked out".

If you have direct access to the repo, you can just open up a shell [in the bare repo] directory and use good old git branch to see what branch origin is currently on. To change it to another branch, you have to use git symbolic-ref HEAD refs/heads/another-branch.

How to Make Laravel Eloquent "IN" Query?

Here is how you do in Eloquent

$users = User::whereIn('id', array(1, 2, 3))->get();

And if you are using Query builder then :

$users = DB::table('users')->whereIn('id', array(1, 2, 3))->get();

how to read value from string.xml in android?

getString(R.string.your_string) get the result

How to read from input until newline is found using scanf()?

#include <stdio.h>
int main()
{
    char a[5],b[10];
    scanf("%2000s %2000[^\n]s",a,b);
    printf("a=%s b=%s",a,b);
}

Just write s in place of \n :)

How can I open two pages from a single click without using JavaScript?

it is working perfectly by only using html

<p><a href="#"onclick="window.open('http://google.com');window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>

How to URL encode in Python 3?

For Python 3 you could try using quote instead of quote_plus:

import urllib.parse

print(urllib.parse.quote("http://www.sample.com/"))

Result:

http%3A%2F%2Fwww.sample.com%2F

Or:

from requests.utils import requote_uri
requote_uri("http://www.sample.com/?id=123 abc")

Result:

'https://www.sample.com/?id=123%20abc'

How to convert comma separated string into numeric array in javascript

You can use the String split method to get the single numbers as an array of strings. Then convert them to numbers with the unary plus operator, the Number function or parseInt, and add them to your array:

var arr = [1,2,3],
    strVale = "130,235,342,124 ";
var strings = strVale.split(",");
for (var i=0; i<strVale.length; i++)
    arr.push( + strings[i] );

Or, in one step, using Array map to convert them and applying them to one single push:

arr.push.apply(arr, strVale.split(",").map(Number));

Remove object from a list of objects in python

You can remove a string from an array like this:

array = ["Bob", "Same"]
array.remove("Bob")

Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

The error message proved to be true as Apache Ant isn't in the path of Mac OS X Mavericks anymore.

Bulletproof solution:

  1. Download and install Homebrew by executing following command in terminal:

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

  2. Install Apache Ant via Homebrew by executing

    brew install ant

Run the PhoneGap build again and it should successfully compile and install your Android app.

CSS selectors ul li a {...} vs ul > li > a {...}

">" is the child selector

"" is the descendant selector

The difference is that a descendant can be a child of the element, or a child of a child of the element or a child of a child of a child ad inifinitum.

A child element is simply one that is directly contained within the parent element:

<foo> <!-- parent -->
  <bar> <!-- child of foo, descendant of foo -->
    <baz> <!-- descendant of foo -->
    </baz>
  </bar>
</foo>

for this example, foo * would match <bar> and <baz>, whereas foo > * would only match <bar>.

As for your second question:

Which one is more efficient and why?

I'm not actually going to answer this question as it's completely irrelevant to development. CSS rendering engines are so fast that there is almost never* a reason to optimize CSS selectors beyond making them as short as possible.

Instead of worrying about micro-optimizations, focus on writing selectors that make sense for the case at hand. I often use > selectors when styling nested lists, because it's important to distinguish which level of the list is being styled.

* if it genuinely is an issue in rendering the page, you've probably got too many elements on the page, or too much CSS. Then you'll have to run some tests to see what the actual issue is.

How to implement class constructor in Visual Basic?

If you mean VB 6, that would be Private Sub Class_Initialize().

http://msdn.microsoft.com/en-us/library/55yzhfb2(VS.80).aspx

If you mean VB.NET it is Public Sub New() or Shared Sub New().

Updating user data - ASP.NET Identity

Based on your question and also noted in comment.

Can someone guide me on how to update User info in the database?

Yes, the code is correct for updating any ApplicationUser to the database.

IdentityResult result = await UserManager.UpdateAsync(user);

  • Check for constrains of all field's required values
  • Check for UserManager is created using ApplicationUser.

UserManager<ApplicationUser> UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));

How to negate the whole regex?

Use negative lookaround: (?!pattern)

Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.

Links to regular-expressions.info

See also

More examples

These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):

How should I declare default values for instance variables in Python?

The two snippets do different things, so it's not a matter of taste but a matter of what's the right behaviour in your context. Python documentation explains the difference, but here are some examples:

Exhibit A

class Foo:
  def __init__(self):
    self.num = 1

This binds num to the Foo instances. Change to this field is not propagated to other instances.

Thus:

>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.num = 2
>>> foo2.num
1

Exhibit B

class Bar:
  num = 1

This binds num to the Bar class. Changes are propagated!

>>> bar1 = Bar()
>>> bar2 = Bar()
>>> bar1.num = 2 #this creates an INSTANCE variable that HIDES the propagation
>>> bar2.num
1
>>> Bar.num = 3
>>> bar2.num
3
>>> bar1.num
2
>>> bar1.__class__.num
3

Actual answer

If I do not require a class variable, but only need to set a default value for my instance variables, are both methods equally good? Or one of them more 'pythonic' than the other?

The code in exhibit B is plain wrong for this: why would you want to bind a class attribute (default value on instance creation) to the single instance?

The code in exhibit A is okay.

If you want to give defaults for instance variables in your constructor I would however do this:

class Foo:
  def __init__(self, num = None):
    self.num = num if num is not None else 1

...or even:

class Foo:
  DEFAULT_NUM = 1
  def __init__(self, num = None):
    self.num = num if num is not None else DEFAULT_NUM

...or even: (preferrable, but if and only if you are dealing with immutable types!)

class Foo:
  def __init__(self, num = 1):
    self.num = num

This way you can do:

foo1 = Foo(4)
foo2 = Foo() #use default

Vue equivalent of setTimeout?

after encountering the same issue, I ended up on this thread. For future generation's sake: The current up-most voted answer, attempts to bind "this" to a variable in order to avoid changing the context when invoking the function which is defined in the setTimeout.

An alternate and more recommended approach(using Vue.JS 2.2 & ES6) is to use an arrow function in order to bind the context to the parent (Basically "addToBasket"'s "this" and the "setTimeout"'s "this" would still refer to the same object):

addToBasket: function(){
        item = this.photo;
        this.$http.post('/api/buy/addToBasket', item);
        this.basketAddSuccess = true;
        setTimeout(() => {
            this.basketAddSuccess = false;
        }, 2000);
    }

How to use a table type in a SELECT FROM statement?

Thanks for all help at this issue. I'll post here my solution:

Package Header

CREATE OR REPLACE PACKAGE X IS
  TYPE exch_row IS RECORD(
    currency_cd VARCHAR2(9),
    exch_rt_eur NUMBER,
    exch_rt_usd NUMBER);
  TYPE exch_tbl IS TABLE OF X.exch_row;

  FUNCTION GetExchangeRate RETURN X.exch_tbl PIPELINED;
END X;

Package Body

CREATE OR REPLACE PACKAGE BODY X IS
  FUNCTION GetExchangeRate RETURN X.exch_tbl
    PIPELINED AS
    exch_rt_usd NUMBER := 1.0; --todo
    rw exch_row;
  BEGIN

    FOR rw IN (SELECT c.currency_cd AS currency_cd, e.exch_rt AS exch_rt_eur, (e.exch_rt / exch_rt_usd) AS exch_rt_usd
                 FROM exch e, currency c
                WHERE c.currency_key = e.currency_key
                  ) LOOP
      PIPE ROW(rw);
    END LOOP;
  END;


  PROCEDURE DoIt IS
  BEGIN
    DECLARE
      CURSOR c0 IS
        SELECT i.DOC,
               i.doc_currency,
               i.net_value,
               i.net_value / rt.exch_rt_usd AS net_value_in_usd,
               i.net_value / rt.exch_rt_eur AS net_value_in_euro,
          FROM item i, (SELECT * FROM TABLE(X.GetExchangeRate())) rt
         WHERE i.doc_currency = rt.currency_cd;

      TYPE c0_type IS TABLE OF c0%ROWTYPE;

      items c0_type;
    BEGIN
      OPEN c0;

      LOOP
        FETCH c0 BULK COLLECT
          INTO items LIMIT batchsize;

        EXIT WHEN items.COUNT = 0;
        FORALL i IN items.FIRST .. items.LAST SAVE EXCEPTIONS
          INSERT INTO detail_items VALUES items (i);

      END LOOP;

      CLOSE c0;

      COMMIT;

    EXCEPTION
      WHEN OTHERS THEN
        RAISE;
    END;
  END;

END X;

Please review.

Can I write or modify data on an RFID tag?

We have recently started looking into RFID solutions at my work place and we found a cheap solution for testing purposes.

One of the units from here:

http://www.sdid.com/products.shtml

Plugs into any windows mobile device with an SD slot and allows reading / writing. There is also a development kit to get you on your way with your own apps.

Hope this helps

The type is defined in an assembly that is not referenced, how to find the cause?

This can also mean you use a library, which exposes (public) types that are defined in a library. Even when you do not use these specifically in your library (the one that doesn't build).

What this probably prevents is you writing code that uses a class (which in its signature has the types from a library not referenced) that you cannot use.

Inline IF Statement in C#

The literal answer is:

return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);

Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:

return (value == 1
    ? Periods.VariablePeriods
    : (value == 2
        ? Periods.FixedPeriods
        : Periods.Unknown));

If you add more values an inline if will become unreadable and a switch would be preferred:

switch (value)
{
case 1:
    return Periods.VariablePeriods;
case 2:
    return Periods.FixedPeriods;
}

The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.

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

C# Test Coverage Tool has very low overhead, handles huge systems of files, intuitive GUI showing coverage on specific files, and generated report with coverage breakdown at method, class, and package levels.

Is there a command to undo git init?

You can just delete .git. Typically:

rm -rf .git

Then, recreate as the right user.

NavigationBar bar, tint, and title text color in iOS 8

In Swift5 and Xcode 10

self.navigationItem.title = "your name"
let textAttributes = [NSAttributedStringKey.foregroundColor:UIColor.white]
navigationController?.navigationBar.titleTextAttributes = textAttributes

Python division

Specifying a float by placing a '.' after the number will also cause it to default to float.

>>> 1 / 2
0

>>> 1. / 2.
0.5

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

In my case - I had to perform below operations:

  1. Move context.xml file from src/java/package to the resource directory (IntelliJ IDE)
  2. Clean target directory.