Programs & Examples On #Gtkd

Gtkd is a D binding and OO wrapper for the GTK+ toolkit.

Eclipse doesn't stop at breakpoints

A different solution worked for me. I also faced the same problem - debug points were not being updated, though they are shown correctly in the IDE editor and in Break Points tab.

My problem and solution are: While creating the project, the 'Default Output Folder' points to different location. At a later stage, I have mavenized the project, selecting "Project Right Click - Configure - Convert to Maven Project". So there are two sets of output folders exist in my project file system. Cleaning the project multiple times did not solve my problem. In the background it was pointing to different binary files. Finally, when I removed the Maven Feature and cleaned the project, this time everything worked fine. Env: Eclipse Juno and JRE is J2SDK 1.5.

CSS3 Transparency + Gradient

The following is the one that I'm using to generate a vertical gradient from completely opaque (top) to 20% in transparency (bottom) for the same color:

background: linear-gradient(to bottom, rgba(0, 64, 122, 1) 0%,rgba(0, 64, 122, 0.8) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
background: -o-linear-gradient(top, rgba(0, 64, 122, 1) 0%, rgba(0, 64, 122, 0.8) 100%); /* Opera 11.10+ */
background: -moz-linear-gradient(top, rgba(0, 64, 122, 1) 0%, rgba(0, 64, 122, 0.8) 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(top, rgba(0, 64, 122, 1) 0%,rgba(0, 64, 122, 0.8) 100%); /* Chrome10-25,Safari5.1-6 */
background: -ms-linear-gradient(top, rgba(0, 64, 122, 1) 0%,rgba(0, 64, 122, 0.8) 100%); /* IE10+ */
-ms-filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00407a', endColorstr='#cc00407a',GradientType=0 ); /* IE8 */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00407a', endColorstr='#cc00407a',GradientType=0 ); /* IE 5.5 - 9 */

How to get first and last element in an array in java?

I think there is only one intuitive solution and it is:

int[] someArray = {1,2,3,4,5};
int first = someArray[0];
int last = someArray[someArray.length - 1];
System.out.println("First: " + first + "\n" + "Last: " + last);

Output:

First: 1
Last: 5

Avoid synchronized(this) in Java?

If you've decided that:

  • the thing you need to do is lock on the current object; and
  • you want to lock it with granularity smaller than a whole method;

then I don't see the a taboo over synchronizezd(this).

Some people deliberately use synchronized(this) (instead of marking the method synchronized) inside the whole contents of a method because they think it's "clearer to the reader" which object is actually being synchronized on. So long as people are making an informed choice (e.g. understand that by doing so they're actually inserting extra bytecodes into the method and this could have a knock-on effect on potential optimisations), I don't particularly see a problem with this. You should always document the concurrent behaviour of your program, so I don't see the "'synchronized' publishes the behaviour" argument as being so compelling.

As to the question of which object's lock you should use, I think there's nothing wrong with synchronizing on the current object if this would be expected by the logic of what you're doing and how your class would typically be used. For example, with a collection, the object that you would logically expect to lock is generally the collection itself.

Count cells that contain any text

You can pass "<>" (including the quotes) as the parameter for criteria. This basically says, as long as its not empty/blank, count it. I believe this is what you want.

=COUNTIF(A1:A10, "<>") 

Otherwise you can use CountA as Scott suggests

Google Spreadsheet, Count IF contains a string

Try using wildcards directly in the COUNTIF function :

=(COUNTIF(A2:A51,"=*iPad*")/COUNTA(A2:A51))*1

Postman - How to see request with headers and body data with variables substituted

If, like me, you are still using the browser version (which will be deprecated soon), have you tried the "Code" button?

enter image description here

This should generate a snippet which contains the entire request Postman is firing. You can even choose the language for the snippet. I find it quite handy when I need to debug stuff.

Hope this helps.

How do I create a Linked List Data Structure in Java?

The obvious solution to developers familiar to Java is to use the LinkedList class already provided in java.util. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. Enhancements to this implementation include making it a double-linked list, adding methods to insert and delete from the middle or end, and by adding get and sort methods as well.

Note: In the example, the Link object doesn't actually contain another Link object - nextLink is actually only a reference to another link.

class Link {
    public int data1;
    public double data2;
    public Link nextLink;

    //Link constructor
    public Link(int d1, double d2) {
        data1 = d1;
        data2 = d2;
    }

    //Print Link data
    public void printLink() {
        System.out.print("{" + data1 + ", " + data2 + "} ");
    }
}

class LinkList {
    private Link first;

    //LinkList constructor
    public LinkList() {
        first = null;
    }

    //Returns true if list is empty
    public boolean isEmpty() {
        return first == null;
    }

    //Inserts a new Link at the first of the list
    public void insert(int d1, double d2) {
        Link link = new Link(d1, d2);
        link.nextLink = first;
        first = link;
    }

    //Deletes the link at the first of the list
    public Link delete() {
        Link temp = first;
        if(first == null){
         return null;
         //throw new NoSuchElementException(); // this is the better way. 
        }
        first = first.nextLink;
        return temp;
    }

    //Prints list data
    public void printList() {
        Link currentLink = first;
        System.out.print("List: ");
        while(currentLink != null) {
            currentLink.printLink();
            currentLink = currentLink.nextLink;
        }
        System.out.println("");
    }
}  

class LinkListTest {
    public static void main(String[] args) {
        LinkList list = new LinkList();

        list.insert(1, 1.01);
        list.insert(2, 2.02);
        list.insert(3, 3.03);
        list.insert(4, 4.04);
        list.insert(5, 5.05);

        list.printList();

        while(!list.isEmpty()) {
            Link deletedLink = list.delete();
            System.out.print("deleted: ");
            deletedLink.printLink();
            System.out.println("");
        }
        list.printList();
    }
}

Groovy executing shell commands

I find this more idiomatic:

def proc = "ls foo.txt doesnotexist.txt".execute()
assert proc.in.text == "foo.txt\n"
assert proc.err.text == "ls: doesnotexist.txt: No such file or directory\n"

As another post mentions, these are blocking calls, but since we want to work with the output, this may be necessary.

Reading Space separated input in python

If you have it in a string, you can use .split() to separate them.

>>> for string in ('Mike 18', 'Kevin 35', 'Angel 56'):
...   l = string.split()
...   print repr(l[0]), repr(int(l[1]))
...
'Mike' 18
'Kevin' 35
'Angel' 56
>>>

SQL Server equivalent of MySQL's NOW()?

getdate() 

is the direct equivalent, but you should always use UTC datetimes

getutcdate()

whether your app operates across timezones or not - otherwise you run the risk of screwing up date math at the spring/fall transitions

Reading input files by line using read command in shell scripting skips last line

Use while loop like this:

while IFS= read -r line || [ -n "$line" ]; do
  echo "$line"
done <file

Or using grep with while loop:

while IFS= read -r line; do
  echo "$line"
done < <(grep "" file)

Using grep . instead of grep "" will skip the empty lines.

Note:

  1. Using IFS= keeps any line indentation intact.

  2. You should almost always use the -r option with read.

  3. Don't read lines with for

  4. File without a newline at the end isn't a standard unix text file.

ReactNative: how to center text?

first add in parent view flex:1, justifyContent: 'center', alignItems: 'center'

then in text add textAlign:'center'

Storyboard - refer to ViewController in AppDelegate

If you use XCode 5 you should do it in a different way.

  • Select your UIViewController in UIStoryboard
  • Go to the Identity Inspector on the right top pane
  • Check the Use Storyboard ID checkbox
  • Write a unique id to the Storyboard ID field

Then write your code.

// Override point for customization after application launch.

if (<your implementation>) {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" 
                                                             bundle: nil];
    YourViewController *yourController = (YourViewController *)[mainStoryboard 
      instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
    self.window.rootViewController = yourController;
}

return YES;

Sort an array in Java

Arrays.sort(yourArray)

will do the job perfectly

android : Error converting byte to dex

First, build -> clean project -> rebuild it again.

If its not working, then in your build.gradle, set the multiDexEnabled as true

eg:

defaultConfig {
    applicationId "com.example.myapplication"
    minSdkVersion 21
    targetSdkVersion 27
    multiDexEnabled true
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner"android.support.test.runner.AndroidJUnitRunner"
}

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

I like to do this witch i think is cleaner :

1 - Add the model to namespace:

use App\Employee;

2 - then you can do :

$employees = Employee::get();

or maybe somthing like this:

$employee = Employee::where('name', 'John')->first();

"for loop" with two variables?

Any reason you can't use a nested for loop?

for i in range(x):
   for j in range(y):
       #code that uses i and j

Artisan migrate could not find driver

For anyone trying to enable the extension inside a Docker image:

RUN docker-php-ext-install pdo pdo_mysql \
    && docker-php-ext-enable pdo_mysql

Based on this answer.

Also props to @Krishna for shedding some light on the extension issue.

How can I get all a form's values that would be submitted without submitting

You can get the form using a document.getElementById and returning the elements[] array.

Here is an example.

You can also get each field of the form and get its value using the document.getElementById function and passing in the field's id.

When do you use Java's @Override annotation and why?

Use it every time you override a method for two benefits. Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are. This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does. Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.

Additionally, in Java 1.6 you can use it to mark when a method implements an interface for the same benefits. I think it would be better to have a separate annotation (like @Implements), but it's better than nothing.

What is special about /dev/tty?

The 'c' means it's a character special file.

Executing another application from Java

The Runtime.getRuntime().exec() approach is quite troublesome, as you'll find out shortly.

Take a look at the Apache Commons Exec project. It abstracts you way of a lot of the common problems associated with using the Runtime.getRuntime().exec() and ProcessBuilder API.

It's as simple as:

String line = "myCommand.exe";
CommandLine commandLine = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
executor.setExitValue(1);
int exitValue = executor.execute(commandLine);

Git Pull While Ignoring Local Changes?

The command bellow wont work always. If you do just:

$ git checkout thebranch
Already on 'thebranch'
Your branch and 'origin/thebranch' have diverged,
and have 23 and 7 different commits each, respectively.

$ git reset --hard
HEAD is now at b05f611 Here the commit message bla, bla

$ git pull
Auto-merging thefile1.c
CONFLICT (content): Merge conflict in thefile1.c
Auto-merging README.md
CONFLICT (content): Merge conflict in README.md
Automatic merge failed; fix conflicts and then commit the result.

and so on...

To really start over, downloading thebranch and overwriting all your local changes, just do:


$ git checkout thebranch
$ git reset --hard origin/thebranch

This will work just fine.

$ git checkout thebranch
Already on 'thebranch'
Your branch and 'origin/thebranch' have diverged,
and have 23 and 7 different commits each, respectively.

$ git reset --hard origin/thebranch
HEAD is now at 7639058 Here commit message again...

$ git status
# On branch thebranch
nothing to commit (working directory clean)

$ git checkout thebranch
Already on 'thebranch'

Can I set up HTML/Email Templates with ASP.NET?

I think the easy answer is MvcMailer. It s NuGet package that lets you use your favorite view engine to generate emails. See the NuGet package here and the project documentation

Hope it helps!

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

When using $_SERVER["REMOTE_ADDR"], I get the server's IP address rather than the visitor's.

Then something is wrong, or odd, with your configuration.

  • Are you using some sort of reverse proxy? In that case, @simshaun's suggestion may work.

  • Do you have anything else out of the ordinary in your web server config?

  • Can you show the PHP code you are using?

  • Can you show what the address looks like. Is it a local one, or a Internet address?

How to convert time milliseconds to hours, min, sec format in JavaScript?

my solution

var sunriseMills = 1517573074000;         // sunrise in NewYork on Feb 3, 2018  - UTC time
var offsetCityMills = -5 * 3600 * 1000;   // NewYork delay to UTC 
var offsetDeviceMills =  new Date().getTimezoneOffset() * 60 * 1000 ;  // eg. I live in Romania (UTC+2) >> getTimezoneOffset() = 120

var textTime = new Date(sunriseMills + offsetCityMills + offsetDeviceMills) 
    .toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric' });

textTime will become '7.04 AM'

Youtube API Limitations

Apart from other answer There are calculator provided by Youtube to check your usage. It is good to identify your usage. https://developers.google.com/youtube/v3/determine_quota_cost

enter image description here

How can I set the color of a selected row in DataGrid

As an extention to @Seb Kade's answer, you can fully control the colours of the selected and unselected rows using the following Style:

<Style TargetType="{x:Type DataGridRow}">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent" />
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}" Color="Transparent" />
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightTextBrushKey}" Color="Black" />
        <SolidColorBrush x:Key="{x:Static SystemColors.ControlTextBrushKey}" Color="Black" />
    </Style.Resources>
</Style>

You can of course enter whichever colours you prefer. This Style will also work for other collection items such as ListBoxItems (if you replace TargetType="{x:Type DataGridRow}" with TargetType="{x:Type ListBoxItem}" for instance).

Send FormData with other field in AngularJS

Here is the complete solution

html code,

create the text anf file upload fields as shown below

    <div class="form-group">
        <div>
            <label for="usr">User Name:</label>
            <input type="text" id="usr" ng-model="model.username">
        </div>
        <div>
            <label for="pwd">Password:</label>
            <input type="password" id="pwd" ng-model="model.password">
        </div><hr>
        <div>
            <div class="col-lg-6">
                <input type="file" file-model="model.somefile"/>
            </div>


        </div>
        <div>
            <label for="dob">Dob:</label>
            <input type="date" id="dob" ng-model="model.dob">
        </div>
        <div>
            <label for="email">Email:</label>
            <input type="email"id="email" ng-model="model.email">
        </div>


        <button type="submit" ng-click="saveData(model)" >Submit</button>

directive code

create a filemodel directive to parse file

.directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};}]);

Service code

append the file and fields to form data and do $http.post as shown below remember to keep 'Content-Type': undefined

 .service('fileUploadService', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, username, password, dob, email, uploadUrl){
        var myFormData = new FormData();

        myFormData.append('file', file);
        myFormData.append('username', username);
        myFormData.append('password', password);
        myFormData.append('dob', dob);
        myFormData.append('email', email);


        $http.post(uploadUrl, myFormData, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
            .success(function(){

            })
            .error(function(){
            });
    }
}]);

In controller

Now in controller call the service by sending required data to be appended in parameters,

$scope.saveData  = function(model){
    var file = model.myFile;
    var uploadUrl = "/api/createUsers";
    fileUpload.uploadFileToUrl(file, model.username, model.password, model.dob, model.email, uploadUrl);
};

MySQL SELECT last few days?

SELECT DATEDIFF(NOW(),pickup_date) AS noofday 
FROM cir_order 
WHERE DATEDIFF(NOW(),pickup_date)>2;

or

SELECT * 
FROM cir_order 
WHERE cir_order.`cir_date` >= DATE_ADD( CURDATE(), INTERVAL -10 DAY )

Why can't DateTime.Parse parse UTC date

To correctly parse the string given in the question without changing it, use the following:

using System.Globalization;

string dateString = "Tue, 1 Jan 2008 00:00:00 UTC";
DateTime parsedDate = DateTime.ParseExact(dateString, "ddd, d MMM yyyy hh:mm:ss UTC", CultureInfo.CurrentCulture, DateTimeStyles.AssumeUniversal);

This implementation uses a string to specify the exact format of the date string that is being parsed. The DateTimeStyles parameter is used to specify that the given string is a coordinated universal time string.

How to get jQuery to wait until an effect is finished?

You can specify a callback function:

$(selector).fadeOut('slow', function() {
    // will be called when the element finishes fading out
    // if selector matches multiple elements it will be called once for each
});

Documentation here.

How to put Google Maps V2 on a Fragment using ViewPager

public class DemoFragment extends Fragment {


MapView mapView;
GoogleMap map;
LatLng CENTER = null;

public LocationManager locationManager;

double longitudeDouble;
double latitudeDouble;

String snippet;
String title;
Location location;
String myAddress;

String LocationId;
String CityName;
String imageURL;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View view = inflater
                .inflate(R.layout.fragment_layout, container, false);

    mapView = (MapView) view.findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);

  setMapView();


 }

 private void setMapView() {
    try {
        MapsInitializer.initialize(getActivity());

        switch (GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getActivity())) {
        case ConnectionResult.SUCCESS:
            // Toast.makeText(getActivity(), "SUCCESS", Toast.LENGTH_SHORT)
            // .show();

            // Gets to GoogleMap from the MapView and does initialization
            // stuff
            if (mapView != null) {

                locationManager = ((LocationManager) getActivity()
                        .getSystemService(Context.LOCATION_SERVICE));

                Boolean localBoolean = Boolean.valueOf(locationManager
                        .isProviderEnabled("network"));

                if (localBoolean.booleanValue()) {

                    CENTER = new LatLng(latitude, longitude);

                } else {

                }
                map = mapView.getMap();
                if (map == null) {

                    Log.d("", "Map Fragment Not Found or no Map in it!!");

                }

                map.clear();
                try {
                    map.addMarker(new MarkerOptions().position(CENTER)
                            .title(CityName).snippet(""));
                } catch (Exception e) {
                    e.printStackTrace();
                }

                map.setIndoorEnabled(true);
                map.setMyLocationEnabled(true);
                map.moveCamera(CameraUpdateFactory.zoomTo(5));
                if (CENTER != null) {
                    map.animateCamera(
                            CameraUpdateFactory.newLatLng(CENTER), 1750,
                            null);
                }
                // add circle
                CircleOptions circle = new CircleOptions();
                circle.center(CENTER).fillColor(Color.BLUE).radius(10);
                map.addCircle(circle);
                map.setMapType(GoogleMap.MAP_TYPE_NORMAL);

            }
            break;
        case ConnectionResult.SERVICE_MISSING:

            break;
        case ConnectionResult.SERVICE_VERSION_UPDATE_REQUIRED:

            break;
        default:

        }
    } catch (Exception e) {

    }

}

in fragment_layout

<com.google.android.gms.maps.MapView
                android:id="@+id/mapView"
                android:layout_width="match_parent"
                android:layout_height="160dp"                    
                android:layout_marginRight="10dp" />

Check if option is selected with jQuery, if not select a default

I found a good way to check, if option is selected and select a default when it isn't.

    if(!$('#some_select option[selected="selected"]').val()) {
        //here code if it HAS NOT selected value
        //for exaple adding the first value as "placeholder"
        $('#some_select option:first-child').before('<option disabled selected>Wybierz:</option>');
    }

If #some_select has't default selected option then .val() is undefined

Create table variable in MySQL

TO answer your question: no, MySQL does not support Table-typed variables in the same manner that SQL Server (http://msdn.microsoft.com/en-us/library/ms188927.aspx) provides. Oracle provides similar functionality but calls them Cursor types instead of table types (http://docs.oracle.com/cd/B12037_01/appdev.101/b10807/13_elems012.htm).

Depending your needs you can simulate table/cursor-typed variables in MySQL using temporary tables in a manner similar to what is provided by both Oracle and SQL Server.

However, there is an important difference between the temporary table approach and the table/cursor-typed variable approach and it has a lot of performance implications (this is the reason why Oracle and SQL Server provide this functionality over and above what is provided with temporary tables).

Specifically: table/cursor-typed variables allow the client to collate multiple rows of data on the client side and send them up to the server as input to a stored procedure or prepared statement. What this eliminates is the overhead of sending up each individual row and instead pay that overhead once for a batch of rows. This can have a significant impact on overall performance when you are trying to import larger quantities of data.

A possible work-around:

What you may want to try is creating a temporary table and then using a LOAD DATA (http://dev.mysql.com/doc/refman/5.1/en/load-data.html) command to stream the data into the temporary table. You could then pass them name of the temporary table into your stored procedure. This will still result in two calls to the database server, but if you are moving enough rows there may be a savings there. Of course, this is really only beneficial if you are doing some kind of logic inside the stored procedure as you update the target table. If not, you may just want to LOAD DATA directly into the target table.

Git clone particular version of remote repository

You can solve it like this:

git reset --hard sha

where sha e.g.: 85a108ec5d8443626c690a84bc7901195d19c446

You can get the desired sha with the command:

git log

C++ calling base class constructors

In c++, compiler always ensure that functions in object hierarchy are called successfully. These functions are constructors and destructors and object hierarchy means inheritance tree.

According to this rule we can guess compiler will call constructors and destructors for each object in inheritance hierarchy even if we don't implement it. To perform this operation compiler will synthesize the undefined constructors and destructors for us and we name them as a default constructors and destructors.Then, compiler will call default constructor of base class and then calls constructor of derived class.

In your case you don't call base class constructor but compiler does that for you by calling default constructor of base class because if compiler didn't do it your derived class which is Rectangle in your example will not be complete and it might cause disaster because maybe you will use some member function of base class in your derived class. So for the sake of safety compiler always need all constructor calls.

Detect Close windows event by jQuery

There is no specific event for capturing browser close event.

You can only capture on unload of the current page.

By this method, it will be effected while refreshing / navigating the current page.

Even calculating of X Y postion of the mouse event doesn't give you good result.

How to edit default.aspx on SharePoint site without SharePoint Designer

I was able to accomplish editing the default.aspx page by:

  • Opening the site in SharePoint Designer 2013
  • Then clicking 'All Files' to view all of the files,
  • Then right-click -> Edit file in Advanced Mode.

By doing that I was able to remove the tagprefix causing a problem on my page.

Convert int (number) to string with leading zeros? (4 digits)

Use the ToString() method - standard and custom numeric format strings. Have a look at the MSDN article How to: Pad a Number with Leading Zeros.

string text = no.ToString("0000");

Close Android Application

Yes - Why, then how(sort of):

Short answer:

System.exit(0);

This nicely and cleanly terminates the whole java machine which is dedicated to running the app. However, you should do it from the main activity, otherwise android may restart your app automatically. (Tested this on Android 7.0)

Details and explanation of why this is a good question and a programmer may have a very legitimate reason to terminate their app this way:

I really don't see the gain in speaking harshly to someone who's looking for a way to terminate their app.

Good is a friendly reminder to beginners that on Android you don't have to worry about closing your app -- but some people actually do want to terminate their app even though they know that they don't have to -- and their question of how to do so is a legitimate question with a valid answer.

Perhaps many folks live in an ideal world and don't realize that there's a real world where real people are trying to solve real problems.

The fact is that even with android, it is still a computer and that computer is still running code, and that it is perfectly understandable why someone may wish to truly exit their "app" (i.e. all of the activities and resources belonging to their app.)

It is true that the developers at Google designed a system where they believed nobody would ever need to exit their app. And maybe 99% of the time they are right!

But one of the amazing things about allowing millions of programmers to write code for a platform is that some of them will try to push the platform to its limits in order to do amazing things! -- Including things that the Android Developers never even dreamed of!

There is another need for being able to close a program, and that is for troubleshooting purposes. That is what brought me to this thread: I'm just learning how to utilize the audio input feature to do realtime DSP.

Now don't forget that I said the following: I well know that when I have everything done right, I won't need to kill my app to reset the audio interface.

BUT: Remember, perfect apps don't start out as perfect apps! They start out as just barely working apps and grow to become proper ideal apps.

So what I found was that my little audio oscilloscope test app worked great until I pressed the android Home button. When I then re-launched my oscilloscope app, there was no audio coming in anymore.

At first I would go into Settings->Applications->Manage Applications->AppName->Force Stop.

(Note that if the actual linux process is not running, the Force Stop button will be disabled. If the button is enabled, then the Linux process is still running!)

Then I could re-launch my app and it worked again.

At first, I was just using divide by zero to crash it - and that worked great. But I decided to look for a better way - which landed me here!

So here's the ways I tried and what I found out:

Background: Android runs on Linux. Linux has processes and process IDs (PIDs) just like Windows does, only better. To see what processes are running on your android (with it connected into the USB and everything) run adb shell top and you will get an updating list of all the processes running in the linux under the android.

If you have linux on your PC as well, you can type

adb shell top | egrep -i '(User|PID|MyFirstApp)' --line-buffered

to get just the results for your app named MyFirstApp. You can see how many Linux Processes are running under that name and how much of the cpu power they are consuming.

(Like the task manager / process list in Windows)

Or if you want to see just the running apps:

adb shell top | egrep -i '(User|PID|app_)' --line-buffered

You can also kill any app on your device by running adb shell kill 12345 where 12345 is it's PID number.

From what I can tell, each single-threaded app just uses a single Linux process.

So what I found out was that (of course) if I just activate the android Home option, my app continues to run. And if I use the Activity.finish(), it still leaves the process running. Divide by zero definitely terminates the linux process that is running. Killing the PID from within the app seems the nicest so far that I've found, at least for debugging purposes.

I initially solved my need to kill my app by adding a button that would cause a divide by zero, like this in my MainActivity.java:

public void exit(View view)
{
    int x;
    x=1/0;
}

Then in my layout XML file section for that button I just set the android:onClick="exit".

Of course divide by zero is messy because it always displays the "This application stopped..." or whatever.

So then I tried the finish, like this:

public void exit(View view)
{
    finish();
}

And that made the app disappear from the screen but it was still running in the background.

Then I tried:

public void exit(View view)
{
      android.os.Process.killProcess(android.os.Process.myPid());
}

So far, this is the best solution I've tried.

UPDATE: This is the same as above in that it instantly terminates the Linux process and all threads for the app:

public void exit(View view)
{
      System.exit(0);
}

It instantly does a nice full exit of the thread in question without telling the user that the app crashed.

All memory used by the app will be freed. (Note: Actually, you can set parameters in your manifest file to cause different threads to run in different Linux processes, so it gets more complicated then.)

At least for quick and dirty testing, if you absolutely need to know that the thread is actually fully exited, the kill process does it nicely. However, if you are running multiple threads you may have to kill each of those, probably from within each thread.

EDIT: Here is a great link to read on the topic: http://developer.android.com/guide/components/fundamentals.html It explains how each app runs in its own virtual machine, and each virtual machine runs under its own user ID.

Here's another great link that explains how (unless specified otherwise in manifest) an app and all of its threads runs in a single Linux process: http://developer.android.com/guide/components/processes-and-threads.html

So as a general rule, an app really is a program running on the computer and the app really can be fully killed, removing all resources from memory instantly.

(By instantly I mean ASAP -- not later whenever the ram is needed.)

PS: Ever wonder why you go to answer your android phone or launch your favorite app and it freezes for a second? Ever reboot because you get tired of it? That's probably because of all the apps you ran in the last week and thought you quit but are still hanging around using memory. Phone kills them when it needs more memory, causing a delay before whatever action you wanted to do!

Update for Android 4/Gingerbread: Same thing as above applies, except even when an app exits or crashes and its whole java virtual machine process dies, it still shows up as running in the app manager, and you still have the "force close" option or whatever it is. 4.0 must have an independent list of apps it thinks is running rather than actually checking to see if an app is really even running.

How to query nested objects?

The two query mechanism work in different ways, as suggested in the docs at the section Subdocuments:

When the field holds an embedded document (i.e, subdocument), you can either specify the entire subdocument as the value of a field, or “reach into” the subdocument using dot notation, to specify values for individual fields in the subdocument:

Equality matches within subdocuments select documents if the subdocument matches exactly the specified subdocument, including the field order.


In the following example, the query matches all documents where the value of the field producer is a subdocument that contains only the field company with the value 'ABC123' and the field address with the value '123 Street', in the exact order:

db.inventory.find( {
    producer: {
        company: 'ABC123',
        address: '123 Street'
    }
});

jQuery - Illegal invocation

Also this is a cause too: If you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().

Editing an item in a list<T>

  1. You can use the FindIndex() method to find the index of item.
  2. Create a new list item.
  3. Override indexed item with the new item.

List<Class1> list = new List<Class1>();

int index = list.FindIndex(item => item.Number == textBox6.Text);

Class1 newItem = new Class1();
newItem.Prob1 = "SomeValue";

list[index] = newItem;

Grab a segment of an array in Java without creating a new array on heap

Java references always point to an object. The object has a header that amongst other things identifies the concrete type (so casts can fail with ClassCastException). For arrays, the start of the object also includes the length, the data then follows immediately after in memory (technically an implementation is free to do what it pleases, but it would be daft to do anything else). So, you can;t have a reference that points somewhere into an array.

In C pointers point anywhere and to anything, and you can point to the middle of an array. But you can't safely cast or find out how long the array is. In D the pointer contains an offset into the memory block and length (or equivalently a pointer to the end, I can't remember what the implementation actually does). This allows D to slice arrays. In C++ you would have two iterators pointing to the start and end, but C++ is a bit odd like that.

So getting back to Java, no you can't. As mentioned, NIO ByteBuffer allows you to wrap an array and then slice it, but gives an awkward interface. You can of course copy, which is probably very much faster than you would think. You could introduce your own String-like abstraction that allows you to slice an array (the current Sun implementation of String has a char[] reference plus a start offset and length, higher performance implementation just have the char[]). byte[] is low level, but any class-based abstraction you put on that is going to make an awful mess of the syntax, until JDK7 (perhaps).

Select2() is not a function

Put config.assets.debug = false in config/environments/development.rb.

Node.js fs.readdir recursive directory search

Another simple and helpful one

function walkDir(root) {
    const stat = fs.statSync(root);

    if (stat.isDirectory()) {
        const dirs = fs.readdirSync(root).filter(item => !item.startsWith('.'));
        let results = dirs.map(sub => walkDir(`${root}/${sub}`));
        return [].concat(...results);
    } else {
        return root;
    }
}

How to display line numbers in 'less' (GNU)

You can set an enviroment variable to always have these options apply to all less'd file:

export LESS='-RS#3NM~g'

Java ArrayList replace at specific index

Lets get array list as ArrayList and new value as value all you need to do is pass the parameters to .set method. ArrayList.set(index,value)

Ex -

ArrayList.set(10,"new value or object")

Should I learn C before learning C++?

I'm going to disagree with the majority here. I think you should learn C before learning C++. It's definitely not necessary, but I think it makes learning C++ a lot easier. C is at the heart of C++. Anything you learn about C is applicable to C++, but C is a lot smaller and easier to learn.

Pick up K&R and read through that. It is short and will give you a sufficient sense of the language. Once you have the basics of pointers and function calls down, you can move on to C++ a little easier.

Python: how to capture image from webcam on click using OpenCV

i'm not too experienced with open cv but if you want the code in the for loop to be called when a key is pressed, you can use a while loop and an raw_input and a condition to prevent the loop from executing forever

import cv2

camera = cv2.VideoCapture(0)
i = 0
while i < 10:
    raw_input('Press Enter to capture')
    return_value, image = camera.read()
    cv2.imwrite('opencv'+str(i)+'.png', image)
    i += 1
del(camera)

How can I find an element by CSS class with XPath?

This selector should work but will be more efficient if you replace it with your suited markup:

//*[contains(@class, 'Test')]

Or, since we know the sought element is a div:

//div[contains(@class, 'Test')]

But since this will also match cases like class="Testvalue" or class="newTest", @Tomalak's version provided in the comments is better:

//div[contains(concat(' ', @class, ' '), ' Test ')]

If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):

//div[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]

Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.

PostgreSQL: Show tables in PostgreSQL

The most straightforward way to list all tables at command line is, for my taste :

psql -a -U <user> -p <port> -h <server> -c "\dt"

For a given database just add the database name :

psql -a -U <user> -p <port> -h <server> -c "\dt" <database_name>

It works on both Linux and Windows.

Can a foreign key be NULL and/or duplicate?

The idea of a foreign key is based on the concept of referencing a value that already exists in the main table. That is why it is called a foreign key in the other table. This concept is called referential integrity. If a foreign key is declared as a null field it will violate the the very logic of referential integrity. What will it refer to? It can only refer to something that is present in the main table. Hence, I think it would be wrong to declare a foreign key field as null.

Python: How to check if keys exists and retrieve value from Dictionary in descending priority

You can use myDict.has_key(keyname) as well to validate if the key exists.

Edit based on the comments -

This would work only on versions lower than 3.1. has_key has been removed from Python 3.1. You should use the in operator if you are using Python 3.1

How to update/upgrade a package using pip?

tl;dr script to update all installed packages

If you only want to upgrade one package, refer to @borgr's answer. I often find it necessary, or at least pleasing, to upgrade all my packages at once. Currently, pip doesn't natively support that action, but with sh scripting it is simple enough. You use pip list, awk (or cut and tail), and command substitution. My normal one-liner is:

for i in $(pip list -o | awk 'NR > 2 {print $1}'); do sudo pip install -U $i; done

This will ask for the root password. If you do not have access to that, the --user option of pip or virtualenv may be something to look into.

Creating an instance using the class name and calling constructor

If class has only one empty constructor (like Activity or Fragment etc, android classes):

Class<?> myClass = Class.forName("com.example.MyClass");    
Constructor<?> constructor = myClass.getConstructors()[0];

What are some great online database modeling tools?

You may want to look at IBExpert Personal Edition. While not open source, this is a very good tool for designing, building, and administering Firebird and InterBase databases.

The Personal Edition is free, but some of the more advanced features are not available. Still, even without the slick extras, the free version is very powerful.

chrome undo the action of "prevent this page from creating additional dialogs"

So the correct answer is: YES, there is a better way.

Right click on the tab and select "Duplicate", then close the original tab if you wish.

Alerting is re-enabled in the duplicate.

The duplicate tab seems to recreate the running state of the original tab so you can just continue where you were.

Model Binding to a List MVC 4

A clean solution could be create a generic class to handle the list, so you don't need to create a different class each time you need it.

public class ListModel<T>
{
    public List<T> Items { get; set; }

    public ListModel(List<T> list) {
        Items = list;
    }
}

and when you return the View you just need to simply do:

List<customClass> ListOfCustomClass = new List<customClass>();
//Do as needed...
return View(new ListModel<customClass>(ListOfCustomClass));

then define the list in the model:

@model ListModel<customClass>

and ready to go:

@foreach(var element in Model.Items) {
  //do as needed...
}

How to prevent XSS with HTML/PHP?

One of the most important steps is to sanitize any user input before it is processed and/or rendered back to the browser. PHP has some "filter" functions that can be used.

The form that XSS attacks usually have is to insert a link to some off-site javascript that contains malicious intent for the user. Read more about it here.

You'll also want to test your site - I can recommend the Firefox add-on XSS Me.

IndexError: index 1 is out of bounds for axis 0 with size 1/ForwardEuler

The problem is with your line

x=np.array ([x0*n])

Here you define x as a single-item array of -200.0. You could do this:

x=np.array ([x0,]*n)

or this:

x=np.zeros((n,)) + x0

Note: your imports are quite confused. You import numpy modules three times in the header, and then later import pylab (that already contains all numpy modules). If you want to go easy, with one single

from pylab import *

line in the top you could use all the modules you need.

Add padding to HTML text input field

you can solve this, taking the input tag inside a div, then put the padding property on div tag. This work's for me...

Like this:

<div class="paded">
    <input type="text" />
</div>

and css:

.paded{
    padding-right: 20px;
}

Could not resolve this reference. Could not locate the assembly

If the project is check out to different PC through team foundation server with different location of same library file, there will be no yellow icon mark in Reference but when change to Release build and build the project, it will give an error. Just like what @C.Evenhuis said, it will use back old one in previous build (eg: Debug build) so I didn't notice the mistake.

Now I know it is a bad habit to put library files in different location on different PC.

Just need to delete the reference and re-add the same reference from correct location.

How to count the number of observations in R like Stata command count

You can also use the filter function from the dplyr package which returns rows with matching conditions.

> library(dplyr)

> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2

How to enable explicit_defaults_for_timestamp?

For me it worked to add the phrase "explicit_defaults_for_timestamp = ON" without quotes into the config file my.ini.

Make sure you add this phrase right underneath the [mysqld] statement in the config file.

You will find my.ini under C:\ProgramData\MySQL\MySQL Server 5.7 if you had conducted the default installation of MySQL.

time delayed redirect?

Include this code somewhere when you slide to your 'section' called blog.

$("#myLink").click(function() {
    setTimeout(function() {
        window.navigate("the url of the page you want to navigate back to");
    }, 2000);
});

Where myLink is the id of your href.

How to add new column to an dataframe (to the front not end)?

cbind inherents order by its argument order.

User your first column(s) as your first argument

cbind(fst_col , df)

  fst_col   df_col1   df_col2
1 0             0.2      -0.1
2 0             0.2      -0.1
3 0             0.2      -0.1
4 0             0.2      -0.1
5 0             0.2      -0.1

cbind(df, last_col)

  df_col1   df_col2  last_col
1 0.2      -0.1             0
2 0.2      -0.1             0
3 0.2      -0.1             0
4 0.2      -0.1             0
5 0.2      -0.1             0

Most pythonic way to delete a file which may not exist

Something like this? Takes advantage of short-circuit evaluation. If the file does not exist, the whole conditional cannot be true, so python will not bother evaluation the second part.

os.path.exists("gogogo.php") and os.remove("gogogo.php")

Hibernate: How to set NULL query-parameter value with HQL?

This is not a Hibernate specific issue (it's just SQL nature), and YES, there IS a solution for both SQL and HQL:

@Peter Lang had the right idea, and you had the correct HQL query. I guess you just needed a new clean run to pick up the query changes ;-)

The below code absolutely works and it is great if you keep all your queries in orm.xml

from CountryDTO c where ((:status is null and c.status is null) or c.status = :status) and c.type =:type

If your parameter String is null then the query will check if the row's status is null as well. Otherwise it will resort to compare with the equals sign.

Notes:

The issue may be a specific MySql quirk. I only tested with Oracle.

The above query assumes that there are table rows where c.status is null

The where clause is prioritized so that the parameter is checked first.

The parameter name 'type' may be a reserved word in SQL but it shouldn't matter since it is replaced before the query runs.

If you needed to skip the :status where_clause altogether; you can code like so:

from CountryDTO c where (:status is null or c.status = :status) and c.type =:type

and it is equivalent to:

sql.append(" where ");
if(status != null){
  sql.append(" c.status = :status and ");
}
sql.append(" c.type =:type ");

Specify system property to Maven project

properties-maven-plugin plugin may help:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
        <execution>
            <goals>
                <goal>set-system-properties</goal>
            </goals>
            <configuration>
                <properties>
                    <property>
                        <name>my.property.name</name>
                        <value>my.property.value</value>
                    </property>
                </properties>
            </configuration>
        </execution>
    </executions>
</plugin>

How to show PIL Image in ipython notebook

A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

pil_im = Image.open('image.jpg')
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()

Entity Framework is Too Slow. What are my options?

I ran into this issue as well. I hate to dump on EF because it works so well, but it is just slow. In most cases I just want to find a record or update/insert. Even simple operations like this are slow. I pulled back 1100 records from a table into a List and that operation took 6 seconds with EF. For me this is too long, even saving takes too long.

I ended up making my own ORM. I pulled the same 1100 records from a database and my ORM took 2 seconds, much faster than EF. Everything with my ORM is almost instant. The only limitation right now is that it only works with MS SQL Server, but it could be changed to work with others like Oracle. I use MS SQL Server for everything right now.

If you would like to try my ORM here is the link and website:

https://github.com/jdemeuse1204/OR-M-Data-Entities

Or if you want to use nugget:

PM> Install-Package OR-M_DataEntities

Documentation is on there as well

How can I detect whether an iframe is loaded?

You can try onload event as well;

var createIframe = function (src) {
        var self = this;
        $('<iframe>', {
            src: src,
            id: 'iframeId',
            frameborder: 1,
            scrolling: 'no',
            onload: function () {
                self.isIframeLoaded = true;
                console.log('loaded!');
            }
        }).appendTo('#iframeContainer');

    };

Getting an Embedded YouTube Video to Auto Play and Loop

Had same experience, however what did the magic for me is not to change embed to v.

So the code will look like this...

<iframe width="560" height="315" src="https://www.youtube.com/embed/cTYuscQu-Og?Version=3&loop=1&playlist=cTYuscQu-Og" frameborder="0" allowfullscreen></iframe>

Hope it helps...

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

  • try to do the Telnet to see any firewall issue
  • perform tracert/traceroute to find number of hops

How to send parameters with jquery $.get()

If you say that it works with accessing directly manageproducts.do?option=1 in the browser then it should work with:

$.get('manageproducts.do', { option: '1' }, function(data) {
    ...
});

as it would send the same GET request.

Given an array of numbers, return array of products of all other numbers (no division)

We can exclude the nums[j] (where j != i) from list first, then get the product of the rest; The following is a python way to solve this puzzle:

from functools import reduce
def products(nums):
    return [ reduce(lambda x,y: x * y, nums[:i] + nums[i+1:]) for i in range(len(nums)) ]
print(products([1, 2, 3, 4, 5]))

[out]
[120, 60, 40, 30, 24]

Get selected option from select element

Here's a short version:

$('#ddlCodes').change(function() {
  $('#txtEntry2').text($(this).find(":selected").text());
});

karim79 made a good catch, judging by your element name txtEntry2 may be a textbox, if it's any kind of input, you'll need to use .val() instead or .text() like this:

  $('#txtEntry2').val($(this).find(":selected").text());

For the "what's wrong?" part of the question: .text() doesn't take a selector, it takes text you want it set to, or nothing to return the text already there. So you need to fetch the text you want, then put it in the .text(string) method on the object you want to set, like I have above.

Play sound file in a web-page in the background

If you don't want to show controls then try this code

<audio  autoplay>
 <source src="song.ogg"  type="audio/ogg">
Your browser does not support the audio element.
</audio>

What's the best way to dedupe a table?

Here's one I've run into, in real life.

Assume you have a table of external/3rd party logins for users, and you're going to merge two users and want to dedupe on the provider/provider key values.

    ;WITH Logins AS
    (
        SELECT [LoginId],[UserId],[Provider],[ProviderKey]
        FROM [dbo].[UserLogin] 
        WHERE [UserId]=@FromUserID -- is the user we're deleting
              OR [UserId]=@ToUserID -- is the user we're moving data to
    ), Ranked AS 
    (
        SELECT Logins.*
            , [Picker]=ROW_NUMBER() OVER (
                       PARTITION BY [Provider],[ProviderKey]
                       ORDER BY CASE WHEN [UserId]=@FromUserID THEN 1 ELSE 0 END)
        FROM Logins
    )
    MERGE Logins AS T
    USING Ranked AS S
    ON S.[LoginId]=T.[LoginID]
    WHEN MATCHED AND S.[Picker]>1 -- duplicate Provider/ProviderKey
                 AND T.[UserID]=@FromUserID -- safety check 
    THEN DELETE
    WHEN MATCHED AND S.[Picker]=1 -- the only or best one
                 AND T.[UserID]=@FromUserID
    THEN UPDATE SET T.[UserID]=@ToUserID
    OUTPUT $action, DELETED.*, INSERTED.*;

Hadoop/Hive : Loading data from .csv on a local machine

Let me work you through the following simple steps:

Steps:

First, create a table on hive using the field names in your csv file. Lets say for example, your csv file contains three fields (id, name, salary) and you want to create a table in hive called "staff". Use the below code to create the table in hive.

hive> CREATE TABLE Staff (id int, name string, salary double) row format delimited fields terminated by ',';

Second, now that your table is created in hive, let us load the data in your csv file to the "staff" table on hive.

hive>  LOAD DATA LOCAL INPATH '/home/yourcsvfile.csv' OVERWRITE INTO TABLE Staff;

Lastly, display the contents of your "Staff" table on hive to check if the data were successfully loaded

hive> SELECT * FROM Staff;

Thanks.

What is the difference between Normalize.css and Reset CSS?

Well from its description it appears it tries to make the user agent's default style consistent across all browsers rather than stripping away all the default styling as a reset would.

Preserves useful defaults, unlike many CSS resets.

How do I instantiate a Queue object in java?

Queue is an interface. You can't instantiate an interface directly except via an anonymous inner class. Typically this isn't what you want to do for a collection. Instead, choose an existing implementation. For example:

Queue<Integer> q = new LinkedList<Integer>();

or

Queue<Integer> q = new ArrayDeque<Integer>();

Typically you pick a collection implementation by the performance and concurrency characteristics you're interested in.

SQL Server Management Studio, how to get execution time down to milliseconds

To get the execution time as a variable in your proc:

DECLARE @EndTime datetime
DECLARE @StartTime datetime 
SELECT @StartTime=GETDATE() 

-- Write Your Query


SELECT @EndTime=GETDATE()

--This will return execution time of your query
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in millisecs] 

AND see this

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

How to change text color of cmd with windows batch script every 1 second

Try this script. This can write any text on any position of screen and don't use temporary files or ".com, .exe" executables. Just make shure you have the "debug.exe" executable in windows\system or windows\system32 folders.

http://pastebin.com/bzYhfLGc

@echo off
setlocal enabledelayedexpansion
set /a _er=0
set /a _n=0
set _ln=%~4
goto init


:howuse ---------------------------------------------------------------

    echo ------------------
    echo ECOL.BAT - ver 1.0
    echo ------------------
    echo Print colored text in batch script
    echo Written by BrendanLS - http://640kbworld.forum.st
    echo.
    echo Syntax:
    echo ECOL.BAT [COLOR] [X] [Y] "Insert your text"
    echo COLOR value must be a hexadecimal number
    echo.
    echo Example:
    echo ECOL.BAT F0 20 30 "The 640KB World Forum"
    echo.
    echo Enjoy ;^)
    goto quit

:error ----------------------------------------------------------------

    set /a "_er=_er | (%~1)"
    goto quit

:geth -----------------------------------------------------------------

        set return=
        set bts=%~1

:hshift ---------------------------------------------------------------

        set /a "nn = bts & 0xff"
        set return=!h%nn%!%return%
        set /a "bts = bts >> 0x8"
        if %bts% gtr 0 goto hshift
        goto quit

:init -----------------------------------------------------------------

    if "%~4"=="" call :error 0xff

    (
        set /a _cl=0x%1
        call :error !errorlevel!
        set _cl=%1
        call :error "0x!_cl! ^>^> 8"
        set /a _px=%2
        call :error !errorlevel!
        set /a _py=%3
        call :error !errorlevel!
    ) 2>nul 1>&2

    if !_er! neq 0 (
        echo.
        echo ERROR: value exception "!_er!" occurred.
        echo.
        goto howuse
    )

    set nsys=0123456789abcdef
    set /a _val=-1

        for /l %%a in (0,1,15) do (
                for /l %%b in (0,1,15) do (
                        set /a "_val += 1"
                        set byte=!nsys:~%%a,1!!nsys:~%%b,1!
                        set h!_val!=!byte!
                )
        )

    set /a cnb=0
    set /a cnl=0

:parse ----------------------------------------------------------------

    set _ch=!_ln:~%_n%,1!
    if "%_ch%"=="" goto perform

    set /a "cnb += 1"
    if %cnb% gtr 7 (
        set /a cnb=0
        set /a "cnl += 1"
    )

    set bln%cnl%=!bln%cnl%! "!_ch!" %_cl%
    set /a "_n += 1"
    goto parse

:perform --------------------------------------------------------------

    set /a "in = ((_py * 160) + (_px * 2)) & 0xffff"
    call :geth %in%
    set ntr=!return!
    set /a jmp=0xe


    @for /l %%x in (0,1,%cnl%) do (
        set bl8086%%x=eb800:!ntr! !bln%%x!
        set /a "in=!jmp! + 0x!ntr!"
        call :geth !in!
        set ntr=!return!
        set /a jmp=0x10
    )

    (
    echo.%bl80860%&echo.%bl80861%&echo.%bl80862%&echo.%bl80863%&echo.%bl80864%
    echo.q
    )|debug >nul 2>&1

:quit

How I add Headers to http.get or http.post in Typescript and angular 2?

I have used below code in Angular 9. note that it is using http class instead of normal httpClient.

  1. so import Headers from the module, otherwise Headers will be mistaken by typescript headers interface and gives error

    import {Http, Headers, RequestOptionsArgs } from "@angular/http";

  2. and in your method use following sample code and it is breaked down for easier understanding.

    let customHeaders = new Headers({ Authorization: "Bearer " + localStorage.getItem("token")});
    const requestOptions: RequestOptionsArgs = { headers: customHeaders };
    return this.http.get("/api/orders", requestOptions);
    

How to hide a <option> in a <select> menu with CSS?

I would suggest that you do not use the solutions that use a <span> wrapper because it isn't valid HTML, which could cause problems down the road. I think the preferred solution is to actually remove any options that you wish to hide, and restore them as needed. Using jQuery, you'll only need these 3 functions:

The first function will save the original contents of the select. Just to be safe, you may want to call this function when you load the page.

function setOriginalSelect ($select) {
    if ($select.data("originalHTML") == undefined) {
        $select.data("originalHTML", $select.html());
    } // If it's already there, don't re-set it
}

This next function calls the above function to ensure that the original contents have been saved, and then simply removes the options from the DOM.

function removeOptions ($select, $options) {
    setOriginalSelect($select);
    $options.remove();
 }

The last function can be used whenever you want to "reset" back to all the original options.

function restoreOptions ($select) {
    var ogHTML = $select.data("originalHTML");
    if (ogHTML != undefined) {
        $select.html(ogHTML);
    }
}

Note that all these functions expect that you're passing in jQuery elements. For example:

// in your search function...
var $s = $('select.someClass');
var $optionsThatDontMatchYourSearch= $s.find('options.someOtherClass');
restoreOptions($s); // Make sure you're working with a full deck
removeOptions($s, $optionsThatDontMatchYourSearch); // remove options not needed

Here is a working example: http://jsfiddle.net/9CYjy/23/

Swift 3: Display Image from URL

Use extension for UIImageView to Load URL Images.

let imageCache = NSCache<NSString, UIImage>()

extension UIImageView {

    func imageURLLoad(url: URL) {

        DispatchQueue.global().async { [weak self] in
            func setImage(image:UIImage?) {
                DispatchQueue.main.async {
                    self?.image = image
                }
            }
            let urlToString = url.absoluteString as NSString
            if let cachedImage = imageCache.object(forKey: urlToString) {
                setImage(image: cachedImage)
            } else if let data = try? Data(contentsOf: url), let image = UIImage(data: data) {
                DispatchQueue.main.async {
                    imageCache.setObject(image, forKey: urlToString)
                    setImage(image: image)
                }
            }else {
                setImage(image: nil)
            }
        }
    }
}

Log all queries in mysql

(Note: For mysql-5.6+ this won't work. There's a solution that applies to mysql-5.6+ if you scroll down or click here.)

If you don't want or cannot restart the MySQL server you can proceed like this on your running server:

  • Create your log tables on the mysql database
  CREATE TABLE `slow_log` (
   `start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP 
                          ON UPDATE CURRENT_TIMESTAMP,
   `user_host` mediumtext NOT NULL,
   `query_time` time NOT NULL,
   `lock_time` time NOT NULL,
   `rows_sent` int(11) NOT NULL,
   `rows_examined` int(11) NOT NULL,
   `db` varchar(512) NOT NULL,
   `last_insert_id` int(11) NOT NULL,
   `insert_id` int(11) NOT NULL,
   `server_id` int(10) unsigned NOT NULL,
   `sql_text` mediumtext NOT NULL,
   `thread_id` bigint(21) unsigned NOT NULL
  ) ENGINE=CSV DEFAULT CHARSET=utf8 COMMENT='Slow log'
  CREATE TABLE `general_log` (
   `event_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
                          ON UPDATE CURRENT_TIMESTAMP,
   `user_host` mediumtext NOT NULL,
   `thread_id` bigint(21) unsigned NOT NULL,
   `server_id` int(10) unsigned NOT NULL,
   `command_type` varchar(64) NOT NULL,
   `argument` mediumtext NOT NULL
  ) ENGINE=CSV DEFAULT CHARSET=utf8 COMMENT='General log'
  • Enable Query logging on the database
SET global general_log = 1;
SET global log_output = 'table';
  • View the log
select * from mysql.general_log
  • Disable Query logging on the database
SET global general_log = 0;

Environment variable in Jenkins Pipeline

To avoid problems of side effects after changing env, especially using multiple nodes, it is better to set a temporary context.

One safe way to alter the environment is:

 withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'
 }

This approach does not poison the env after the command execution.

How to change the color of winform DataGridview header?

The way to do this is to set the EnableHeadersVisualStyles flag for the data grid view to False, and set the background colour via the ColumnHeadersDefaultCellStyle.BackColor property. For example, to set the background colour to blue, use the following (or set in the designer if you prefer):

_dataGridView.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
_dataGridView.EnableHeadersVisualStyles = false;

If you do not set the EnableHeadersVisualStyles flag to False, then the changes you make to the style of the header will not take effect, as the grid will use the style from the current users default theme. The MSDN documentation for this property is here.

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Remove ':hover' CSS behavior from element

One method to do this is to add:

pointer-events: none;

to the element, you want to disable hover on.

(Note: this also disables javascript events on that element too, click events will actually fall through to the element behind ).

Browser Support ( 98.12% as of Jan 1, 2021 )

This seems to be much cleaner

_x000D_
_x000D_
/**
 * This allows you to disable hover events for any elements
*/
.disabled {
  pointer-events: none;  /* <----------- */
  opacity: 0.2;
}

.button {
  border-radius: 30px;
  padding: 10px 15px;
  border: 2px solid #000;
  color: #FFF;
  background: #2D2D2D;
  text-shadow: 1px 1px 0px #000;
  cursor: pointer;
  display: inline-block;
  margin: 10px;
}

.button-red:hover {
  background: red;
}

.button-green:hover {
  background:green;  
}
_x000D_
<div class="button button-red">I'm a red button hover over me</div>

<br />

<div class="button button-green">I'm a green button hover over me</div>

<br />

<div class="button button-red disabled">I'm a disabled red button</div>

<br />

<div class="button button-green disabled">I'm a disabled green button</div>
_x000D_
_x000D_
_x000D_

Return array from function

neater:

function BlockID() {
  return {
    "s":"Images/Block_01.png",
    "g":"Images/Block_02.png",
    "C":"Images/Block_03.png",
    "d":"Images/Block_04.png"
   }
}

or just

var images = {
  "s":"Images/Block_01.png",
  "g":"Images/Block_02.png",
  "C":"Images/Block_03.png",
  "d":"Images/Block_04.png"
}

JQuery: How to get selected radio button value?

This Jquery method returns the default vale 0 when page loads...

$('input[type="radio"]:checked').val();

jQuery to retrieve and set selected option value of html select element

$( "#myId option:selected" ).text(); will give you the text that you selected in the drop down element. either way you can change it to .val(); to get the value of it . check the below coding

<select id="myId">
    <option value="1">Mr</option>
    <option value="2">Mrs</option>
    <option value="3">Ms</option>`
    <option value="4">Dr</option>
    <option value="5">Prof</option>
</select>

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

you can use getopt to handle parameters in your bash script. there are not many explanations for getopt out there. here is an example:

#!/bin/sh

OPTIONS=$(getopt -o hf:gb -l help,file:,foo,bar -- "$@")

if [ $? -ne 0 ]; then
  echo "getopt error"
  exit 1
fi

eval set -- $OPTIONS

while true; do
  case "$1" in
    -h|--help) HELP=1 ;;
    -f|--file) FILE="$2" ; shift ;;
    -g|--foo)  FOO=1 ;;
    -b|--bar)  BAR=1 ;;
    --)        shift ; break ;;
    *)         echo "unknown option: $1" ; exit 1 ;;
  esac
  shift
done

if [ $# -ne 0 ]; then
  echo "unknown option(s): $@"
  exit 1
fi

echo "help: $HELP"
echo "file: $FILE"
echo "foo: $FOO"
echo "bar: $BAR"

see also:

How to set a cookie to expire in 1 hour in Javascript?

Code :

var now = new Date();
var time = now.getTime();
time += 3600 * 1000;
now.setTime(time);
document.cookie = 
'username=' + value + 
'; expires=' + now.toUTCString() + 
'; path=/';

Git fast forward VS no fast forward merge

The --no-ff option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff.

If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.

For example, the author of this article thinks that --no-ff option should be default and his reasoning is close to that I outlined above:

Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff is not used], whereas it is easily done if the --no-ff flag was used [because it's just one commit]."

Graphic showing how --no-ff groups together all commits from feature branch into one commit on master branch

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Swift Method, and supply a demo.

func topMostController() -> UIViewController {
    var topController: UIViewController = UIApplication.sharedApplication().keyWindow!.rootViewController!
    while (topController.presentedViewController != nil) {
        topController = topController.presentedViewController!
    }
    return topController
}

func demo() {
    let vc = ViewController()
    let nav = UINavigationController.init(rootViewController: vc)
    topMostController().present(nav, animated: true, completion: nil)
}

How to split a string in shell and get the last field

Using sed:

$ echo '1:2:3:4:5' | sed 's/.*://' # => 5

$ echo '' | sed 's/.*://' # => (empty)

$ echo ':' | sed 's/.*://' # => (empty)
$ echo ':b' | sed 's/.*://' # => b
$ echo '::c' | sed 's/.*://' # => c

$ echo 'a' | sed 's/.*://' # => a
$ echo 'a:' | sed 's/.*://' # => (empty)
$ echo 'a:b' | sed 's/.*://' # => b
$ echo 'a::c' | sed 's/.*://' # => c

How to read all of Inputstream in Server Socket JAVA

The problem you have is related to TCP streaming nature.

The fact that you sent 100 Bytes (for example) from the server doesn't mean you will read 100 Bytes in the client the first time you read. Maybe the bytes sent from the server arrive in several TCP segments to the client.

You need to implement a loop in which you read until the whole message was received. Let me provide an example with DataInputStream instead of BufferedinputStream. Something very simple to give you just an example.

Let's suppose you know beforehand the server is to send 100 Bytes of data.

In client you need to write:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());

    while(!end)
    {
        int bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == 100)
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

Now, typically the data size sent by one node (the server here) is not known beforehand. Then you need to define your own small protocol for the communication between server and client (or any two nodes) communicating with TCP.

The most common and simple is to define TLV: Type, Length, Value. So you define that every message sent form server to client comes with:

  • 1 Byte indicating type (For example, it could also be 2 or whatever).
  • 1 Byte (or whatever) for length of message
  • N Bytes for the value (N is indicated in length).

So you know you have to receive a minimum of 2 Bytes and with the second Byte you know how many following Bytes you need to read.

This is just a suggestion of a possible protocol. You could also get rid of "Type".

So it would be something like:

byte[] messageByte = new byte[1000];
boolean end = false;
String dataString = "";

try 
{
    DataInputStream in = new DataInputStream(clientSocket.getInputStream());
    int bytesRead = 0;

    messageByte[0] = in.readByte();
    messageByte[1] = in.readByte();

    int bytesToRead = messageByte[1];

    while(!end)
    {
        bytesRead = in.read(messageByte);
        dataString += new String(messageByte, 0, bytesRead);
        if (dataString.length == bytesToRead )
        {
            end = true;
        }
    }
    System.out.println("MESSAGE: " + dataString);
}
catch (Exception e)
{
    e.printStackTrace();
}

The following code compiles and looks better. It assumes the first two bytes providing the length arrive in binary format, in network endianship (big endian). No focus on different encoding types for the rest of the message.

import java.nio.ByteBuffer;
import java.io.DataInputStream;
import java.net.ServerSocket;
import java.net.Socket;

class Test
{
    public static void main(String[] args)
    {
        byte[] messageByte = new byte[1000];
        boolean end = false;
        String dataString = "";

        try 
        {
            Socket clientSocket;
            ServerSocket server;

            server = new ServerSocket(30501, 100);
            clientSocket = server.accept();

            DataInputStream in = new DataInputStream(clientSocket.getInputStream());
            int bytesRead = 0;

            messageByte[0] = in.readByte();
            messageByte[1] = in.readByte();
            ByteBuffer byteBuffer = ByteBuffer.wrap(messageByte, 0, 2);

            int bytesToRead = byteBuffer.getShort();
            System.out.println("About to read " + bytesToRead + " octets");

            //The following code shows in detail how to read from a TCP socket

            while(!end)
            {
                bytesRead = in.read(messageByte);
                dataString += new String(messageByte, 0, bytesRead);
                if (dataString.length() == bytesToRead )
                {
                    end = true;
                }
            }

            //All the code in the loop can be replaced by these two lines
            //in.readFully(messageByte, 0, bytesToRead);
            //dataString = new String(messageByte, 0, bytesToRead);

            System.out.println("MESSAGE: " + dataString);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Storing WPF Image Resources

If you're using Blend, to make it extra easy and not have any trouble getting the correct path for the Source attribute, just drag and drop the image from the Project panel onto the designer.

How to output oracle sql result into a file in windows?

just to make the Answer 2 much easier, you can also define the folder where you can put your saved file

    spool /home/admin/myoutputfile.txt
    select * from table_name;
    spool off;

after that only with nano or vi myoutputfile.txt, you will see all the sql track.

hope is that help :)

What is SuppressWarnings ("unchecked") in Java?

The SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.

Removing the fragment identifier from AngularJS urls (# symbol)

Guess this is reallllly late for this. But adding the below config to the app.module imports does the job:

RouterModule.forRoot(routes, { useHash: false })

lvalue required as left operand of assignment error when using C++

To assign, you should use p=p+1; instead of p+1=p;

int main()
{

   int x[3]={4,5,6};
   int *p=x;
   p=p+1; /*You just needed to switch the terms around*/
   cout<<p<<endl;
   getch();
}

How can I limit ngFor repeat to some number of items in Angular?

 <div *ngFor="let item of list;trackBy: trackByFunc" >
   {{item.value}}
 </div>

In your ts file

 trackByFunc(index, item){
    return item ? item.id : undefined;
  }

Trigger standard HTML5 validation (form) without using submit button?

After some research, I've came up with the following code that should be the answer to your question. (At least it worked for me)

Use this piece of code first. The $(document).ready makes sure the code is executed when the form is loaded into the DOM:

$(document).ready(function()
{
    $('#theIdOfMyForm').submit(function(event){
        if(!this.checkValidity())
        {
            event.preventDefault();
        }
    });
});

Then just call $('#theIdOfMyForm').submit(); in your code.

UPDATE

If you actually want to show which field the user had wrong in the form then add the following code after event.preventDefault();

$('#theIdOfMyForm :input:visible[required="required"]').each(function()
{
    if(!this.validity.valid)
    {
        $(this).focus();
        // break
        return false;
    }
});

It will give focus on the first invalid input.

How to send post request to the below post method using postman rest client

JSON:-

For POST request using json object it can be configured by selecting

Body -> raw -> application/json

POST JSON object using POSTMAN

Form Data(For Normal content POST):- multipart/form-data

For normal POST request (using multipart/form-data) it can be configured by selecting

Body -> form-data

POST multipart/form-data using POSTMAN

Truncate a SQLite table if it exists?

Unfortunately, we do not have a "TRUNCATE TABLE" command in SQLite, but you can use SQLite's DELETE command to delete the complete data from an existing table, though it is recommended to use the DROP TABLE command to drop the complete table and re-create it once again.

Spring Boot @Value Properties

I had the similar issue and the above examples doesn't help me to read properties. I have posted the complete class which will help you to read properties values from application.properties file in SpringBoot application in the below link.

Spring Boot - Environment @Autowired throws NullPointerException

C# nullable string error

You are making it complicated. string is already nullable. You don't need to make it more nullable. Take out the ? on the property type.

How to get coordinates of an svg element?

The element.getBoundingClientRect() method will return the proper coordinates of an element relative to the viewport regardless of whether the svg has been scaled and/or translated.

See this question and answer.

While getBBox() works for an untransformed space, if scale and translation have been applied to the layout then it will no longer be accurate. The getBoundingClientRect() function has worked well for me in a force layout project when pan and zoom are in effect, where I wanted to attach HTML Div elements as labels to the nodes instead of using SVG Text elements.

Calling stored procedure with return value

You need to add return parameter to the command:

using (SqlConnection conn = new SqlConnection(getConnectionString()))
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = parameterStatement.getQuery();
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("SeqName", "SeqNameValue");

    var returnParameter = cmd.Parameters.Add("@ReturnVal", SqlDbType.Int);
    returnParameter.Direction = ParameterDirection.ReturnValue;

    conn.Open();
    cmd.ExecuteNonQuery();
    var result = returnParameter.Value;
}

IE8 css selector

\9 doesn’t work with font-family, instead you’d need to use “\0/ !important” as Chris mentioned above, for example:

p { font-family: Arial \0/ !important; }

Python : Trying to POST form using requests

Send a POST request with content type = 'form-data':

import requests
files = {
    'username': (None, 'myusername'),
    'password': (None, 'mypassword'),
}
response = requests.post('https://example.com/abc', files=files)

How to use Boost in Visual Studio 2010

Also a little note: If you want to reduce the compilation-time, you can add the flag

-j2

to run two parallel builds at the same time. This might reduce it to viewing one movie ;)

How to get sp_executesql result into a variable?

Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.

In the below, @i will return 2727

DECLARE @s NVARCHAR(500)
DECLARE @i INT;
SET @s = 'USE [Blah]; UPDATE STATISTICS [dbo].[TableName] [NonExistantStatisticsName];';
EXEC @i = sys.sp_executesql @s
SELECT @i AS 'Blah'

SSMS will show this Msg 2727, Level 11, State 1, Line 1 Cannot find index 'NonExistantStaticsName'.

How to represent empty char in Java Character class

As Character is a class deriving from Object, you can assign null as "instance":

Character myChar = null;

Problem solved ;)

How do I compare two columns for equality in SQL Server?

The closest approach I can think of is NULLIF:

SELECT 
    ISNULL(NULLIF(O.ShipName, C.CompanyName), 1),
    O.ShipName,      
    C.CompanyName,
    O.OrderId
FROM [Northwind].[dbo].[Orders] O
INNER JOIN [Northwind].[dbo].[Customers] C
ON C.CustomerId = O.CustomerId

GO

NULLIF returns the first expression if the two expressions are not equal. If the expressions are equal, NULLIF returns a null value of the type of the first expression.

So, above query will return 1 for records in which that columns are equal, the first expression otherwise.

How to generate random colors in matplotlib?

When less than 9 datasets:

colors = "bgrcmykw"
color_index = 0

for X,Y in data:
    scatter(X,Y, c=colors[color_index])
    color_index += 1

How to get the height of a body element

Simply use

$(document).height() // - $('body').offset().top

and / or

$(window).height()

instead of $('body').height();

Node Express sending image files as API response

a proper solution with streams and error handling is below:

const fs = require('fs')
const stream = require('stream')

app.get('/report/:chart_id/:user_id',(req, res) => {
  const r = fs.createReadStream('path to file') // or any other way to get a readable stream
  const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
  stream.pipeline(
   r,
   ps, // <---- this makes a trick with stream error handling
   (err) => {
    if (err) {
      console.log(err) // No such file or any other kind of error
      return res.sendStatus(400); 
    }
  })
  ps.pipe(res) // <---- this makes a trick with stream error handling
})

with Node older then 10 you will need to use pump instead of pipeline.

MVC3 DropDownListFor - a simple example?

For binding Dynamic Data in a DropDownList you can do the following:

Create ViewBag in Controller like below

ViewBag.ContribTypeOptions = yourFunctionValue();

now use this value in view like below:

@Html.DropDownListFor(m => m.ContribType, 
    new SelectList(@ViewBag.ContribTypeOptions, "ContribId", 
                   "Value", Model.ContribTypeOptions.First().ContribId), 
    "Select, please")

How to npm install to a specified directory?

You can use the --prefix option:

mkdir -p ./install/here/node_modules
npm install --prefix ./install/here <package>

The package(s) will then be installed in ./install/here/node_modules. The mkdir is needed since npm might otherwise choose an already existing node_modules directory higher up in the hierarchy. (See npm documentation on folders.)

VBA (Excel) Initialize Entire Array without Looping

You can initialize the array by specifying the dimensions. For example

Dim myArray(10) As Integer
Dim myArray(1 to 10) As Integer

If you are working with arrays and if this is your first time then I would recommend visiting Chip Pearson's WEBSITE.

What does this initialize to? For example, what if I want to initialize the entire array to 13?

When you want to initailize the array of 13 elements then you can do it in two ways

Dim myArray(12) As Integer
Dim myArray(1 to 13) As Integer

In the first the lower bound of the array would start with 0 so you can store 13 elements in array. For example

myArray(0) = 1
myArray(1) = 2
'
'
'
myArray(12) = 13

In the second example you have specified the lower bounds as 1 so your array starts with 1 and can again store 13 values

myArray(1) = 1
myArray(2) = 2
'
'
'
myArray(13) = 13

Wnen you initialize an array using any of the above methods, the value of each element in the array is equal to 0. To check that try this code.

Sub Sample()
    Dim myArray(12) As Integer
    Dim i As Integer

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print myArray(i)
    Next i
End Sub

or

Sub Sample()
    Dim myArray(1 to 13) As Integer
    Dim i As Integer

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print myArray(i)
    Next i
End Sub

FOLLOWUP FROM COMMENTS

So, in this example every value would be 13. So if I had an array Dim myArray(300) As Integer, all 300 elements would hold the value 13

Like I mentioned, AFAIK, there is no direct way of achieving what you want. Having said that here is one way which uses worksheet function Rept to create a repetitive string of 13's. Once we have that string, we can use SPLIT using "," as a delimiter. But note this creates a variant array but can be used in calculations.

Note also, that in the following examples myArray will actually hold 301 values of which the last one is empty - you would have to account for that by additionally initializing this value or removing the last "," from sNum before the Split operation.

Sub Sample()
    Dim sNum As String
    Dim i As Integer
    Dim myArray

    '~~> Create a string with 13 three hundred times separated by comma
    '~~> 13,13,13,13...13,13 (300 times)
    sNum = WorksheetFunction.Rept("13,", 300)
    sNum = Left(sNum, Len(sNum) - 1)

    myArray = Split(sNum, ",")

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print myArray(i)
    Next i
End Sub

Using the variant array in calculations

Sub Sample()
    Dim sNum As String
    Dim i As Integer
    Dim myArray

    '~~> Create a string with 13 three hundred times separated by comma
    sNum = WorksheetFunction.Rept("13,", 300)
    sNum = Left(sNum, Len(sNum) - 1)

    myArray = Split(sNum, ",")

    For i = LBound(myArray) To UBound(myArray)
        Debug.Print Val(myArray(i)) + Val(myArray(i))
    Next i
End Sub

Python function pointer

eval(compile(myvar,'<str>','eval'))(myargs)

compile(...,'eval') allows only a single statement, so that there can't be arbitrary commands after a call, or there will be a SyntaxError. Then a tiny bit of validation can at least constrain the expression to something in your power, like testing for 'mypackage' to start.

How can I set an SQL Server connection string?

sa is a system administrator account which comes with SQL Server by default. As you know might already know, you can use two ways to log in to SQL Server.

screen shot of SQL Server Management Studio

Therefore there are connection strings which suitable for each scenario (such as Windows authentication, localdb, etc.). Use SQL Server Connection Strings for ASP.NET Web Applications to build your connection string. These are XML tags. You just need a value of connectionString.

Save PL/pgSQL output from PostgreSQL to a CSV file

Per the request of @skeller88, I am reposting my comment as an answer so that it doesn't get lost by people who don't read every response...

The problem with DataGrip is that it puts a grip on your wallet. It is not free. Try the community edition of DBeaver at dbeaver.io. It is a FOSS multi-platform database tool for SQL programmers, DBAs and analysts that supports all popular databases: MySQL, PostgreSQL, SQLite, Oracle, DB2, SQL Server, Sybase, MS Access, Teradata, Firebird, Hive, Presto, etc.

DBeaver Community Edition makes it trivial to connect to a database, issue queries to retrieve data, and then download the result set to save it to CSV, JSON, SQL, or other common data formats. It's a viable FOSS competitor to TOAD for Postgres, TOAD for SQL Server, or Toad for Oracle.

I have no affiliation with DBeaver. I love the price and functionality, but I wish they would open up the DBeaver/Eclipse application more and made it easy to add analytics widgets to DBeaver / Eclipse, rather than requiring users to pay for the annual subscription to create graphs and charts directly within the application. My Java coding skills are rusty and I don't feel like taking weeks to relearn how to build Eclipse widgets, only to find that DBeaver has disabled the ability to add third-party widgets to the DBeaver Community Edition.

Do DBeaver users have insight as to the steps to create analytics widgets to add into the Community Edition of DBeaver?

Navigation bar show/hide

In Swift try this,

navigationController?.isNavigationBarHidden = true  //Hide
navigationController?.isNavigationBarHidden = false //Show

or

navigationController?.setNavigationBarHidden(true, animated: true) //Hide
navigationController?.setNavigationBarHidden(false, animated: true) //Show

The name 'controlname' does not exist in the current context

I had the same error message. My code was error-free and working perfectly, then I decided to go back and rename one of my buttons and suddenly it's giving me a compile error accompanied by that blue squiggly underline saying that the control doesn't exist in current context...

Turns out Visual Studio was being dumb, as the problem was related to the backup files I had made of my aspx.cs class. I deleted those and the errors went away.

ReferenceError: $ is not defined

Though my response is late, but it can still help.

lf you are using Spring Tool Suite and you still think that the JQuery file reference path is correct, then refresh your project whenever you modify the JQuery file.

You refresh by right-clicking on the project name -> refresh.

That's what solved mine.

Rendering raw html with reactjs

I have used this in quick and dirty situations:

// react render method:

render() {
    return (
      <div>
        { this.props.textOrHtml.indexOf('</') !== -1
            ? (
                <div dangerouslySetInnerHTML={{__html: this.props.textOrHtml.replace(/(<? *script)/gi, 'illegalscript')}} >
                </div>
              )
            : this.props.textOrHtml
          }

      </div>
      )
  }

Remove a folder from git tracking

From the git documentation:

Another useful thing you may want to do is to keep the file in your working tree but remove it from your staging area. In other words, you may want to keep the file on your hard drive but not have Git track it anymore. This is particularly useful if you forgot to add something to your .gitignore file and accidentally staged it, like a large log file or a bunch of .a compiled files. To do this, use the --cached option:

$ git rm --cached readme.txt

So maybe don't include the "-r"?

How to test if string exists in file with Bash?

The @Thomas's solution didn't work for me for some reason but I had longer string with special characters and whitespaces so I just changed the parameters like this:

if grep -Fxq 'string you want to find' "/path/to/file"; then
    echo "Found"
else
    echo "Not found"
fi

Hope it helps someone

How do I change the ID of a HTML element with JavaScript?

It does work in Firefox (including 2.0.0.20). See http://jsbin.com/akili (add /edit to the url to edit):

<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>

The first click changes the id to "two", the second click errors because the element with id="one" now can't be found!

Perhaps you have another element already with id="two" (FYI you can't have more than one element with the same id).

Creating composite primary key in SQL Server

it simple, select columns want to insert primary key and click on Key icon on header and save tablesql composite key

happy coding..,

node.js remove file

2020 Answer

With the release of node v14.14.0 you can now do.

fs.rmSync("path/to/file", {
    force: true,
});

https://nodejs.org/api/fs.html#fs_fs_rmsync_path_options

What is the most efficient way to get first and last line of a text file?

Can you use unix commands? I think using head -1 and tail -n 1 are probably the most efficient methods. Alternatively, you could use a simple fid.readline() to get the first line and fid.readlines()[-1], but that may take too much memory.

Which ORM should I use for Node.js and MySQL?

One major difference between Sequelize and Persistence.js is that the former supports a STRING datatype, i.e. VARCHAR(255). I felt really uncomfortable making everything TEXT.

How can I install packages using pip according to the requirements.txt file from a local directory?

Often, you will want a fast install from local archives, without probing PyPI.

First, download the archives that fulfill your requirements:

$ pip install --download <DIR> -r requirements.txt

Then, install using –find-links and –no-index:

$ pip install --no-index --find-links=[file://]<DIR> -r requirements.txt

How do I tell CMake to link in a static library in the source directory?

If you don't want to include the full path, you can do

add_executable(main main.cpp)
target_link_libraries(main bingitup)

bingitup is the same name you'd give a target if you create the static library in a CMake project:

add_library(bingitup STATIC bingitup.cpp)

CMake automatically adds the lib to the front and the .a at the end on Linux, and .lib at the end on Windows.

If the library is external, you might want to add the path to the library using

link_directories(/path/to/libraries/)

Parsing command-line arguments in C

Try CLPP library. It's simple and flexible library for command line parameters parsing. Header-only and cross-platform. Uses ISO C++ and Boost C++ libraries only. IMHO it is easier than Boost.Program_options.

Library: http://sourceforge.net/projects/clp-parser/

26 October 2010 - new release 2.0rc. Many bugs fixed, full refactoring of the source code, documentation, examples and comments have been corrected.

How to draw a path on a map using kml file?

Thank Mathias Lin, tested and it works!

In addition, sample implementation of Mathias's method in activity can be as follows.

public class DirectionMapActivity extends MapActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.directionmap);

        MapView mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);

        // Acquire a reference to the system Location Manager
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        String locationProvider = LocationManager.NETWORK_PROVIDER;
        Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.google.com/maps?f=d&hl=en");
        urlString.append("&saddr=");//from
        urlString.append( Double.toString(lastKnownLocation.getLatitude() ));
        urlString.append(",");
        urlString.append( Double.toString(lastKnownLocation.getLongitude() ));
        urlString.append("&daddr=");//to
        urlString.append( Double.toString((double)dest[0]/1.0E6 ));
        urlString.append(",");
        urlString.append( Double.toString((double)dest[1]/1.0E6 ));
        urlString.append("&ie=UTF8&0&om=0&output=kml");

        try{
            // setup the url
            URL url = new URL(urlString.toString());
            // create the factory
            SAXParserFactory factory = SAXParserFactory.newInstance();
            // create a parser
            SAXParser parser = factory.newSAXParser();
            // create the reader (scanner)
            XMLReader xmlreader = parser.getXMLReader();
            // instantiate our handler
            NavigationSaxHandler navSaxHandler = new NavigationSaxHandler();
            // assign our handler
            xmlreader.setContentHandler(navSaxHandler);
            // get our data via the url class
            InputSource is = new InputSource(url.openStream());
            // perform the synchronous parse           
            xmlreader.parse(is);
            // get the results - should be a fully populated RSSFeed instance, or null on error
            NavigationDataSet ds = navSaxHandler.getParsedData();

            // draw path
            drawPath(ds, Color.parseColor("#add331"), mapView );

            // find boundary by using itemized overlay
            GeoPoint destPoint = new GeoPoint(dest[0],dest[1]);
            GeoPoint currentPoint = new GeoPoint( new Double(lastKnownLocation.getLatitude()*1E6).intValue()
                                                ,new Double(lastKnownLocation.getLongitude()*1E6).intValue() );

            Drawable dot = this.getResources().getDrawable(R.drawable.pixel);
            MapItemizedOverlay bgItemizedOverlay = new MapItemizedOverlay(dot,this);
            OverlayItem currentPixel = new OverlayItem(destPoint, null, null );
            OverlayItem destPixel = new OverlayItem(currentPoint, null, null );
            bgItemizedOverlay.addOverlay(currentPixel);
            bgItemizedOverlay.addOverlay(destPixel);

            // center and zoom in the map
            MapController mc = mapView.getController();
            mc.zoomToSpan(bgItemizedOverlay.getLatSpanE6()*2,bgItemizedOverlay.getLonSpanE6()*2);
            mc.animateTo(new GeoPoint(
                    (currentPoint.getLatitudeE6() + destPoint.getLatitudeE6()) / 2
                    , (currentPoint.getLongitudeE6() + destPoint.getLongitudeE6()) / 2));

        } catch(Exception e) {
            Log.d("DirectionMap","Exception parsing kml.");
        }

    }
    // and the rest of the methods in activity, e.g. drawPath() etc...

MapItemizedOverlay.java

public class MapItemizedOverlay extends ItemizedOverlay{
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    private Context mContext;

    public MapItemizedOverlay(Drawable defaultMarker, Context context) {
          super(boundCenterBottom(defaultMarker));
          mContext = context;
    }

    public void addOverlay(OverlayItem overlay) {
        mOverlays.add(overlay);
        populate();
    }

    @Override
    protected OverlayItem createItem(int i) {
      return mOverlays.get(i);
    }

    @Override
    public int size() {
      return mOverlays.size();
    }

}

Virtual Serial Port for Linux

Using the links posted in the previous answers, I coded a little example in C++ using a Virtual Serial Port. I pushed the code into GitHub: https://github.com/cymait/virtual-serial-port-example .

The code is pretty self explanatory. First, you create the master process by running ./main master and it will print to stderr the device is using. After that, you invoke ./main slave device, where device is the device printed in the first command.

And that's it. You have a bidirectional link between the two process.

Using this example you can test you the application by sending all kind of data, and see if it works correctly.

Also, you can always symlink the device, so you don't need to re-compile the application you are testing.

What are all the possible values for HTTP "Content-Type" header?

I would aim at covering a subset of possible "Content-type" values, you question seems to focus on identifying known content types.

@Jeroen RFC 1341 reference is great, but for an fairly exhaustive list IANA keeps a web page of officially registered media types here.

Should I use JSLint or JSHint JavaScript validation?

[EDIT]
This answer has been edited. I'm leaving the original answer below for context (otherwise the comments wouldn't make sense).

When this question was originally asked, JSLint was the main linting tool for JavaScript. JSHint was a new fork of JSLint, but had not yet diverged much from the original.

Since then, JSLint has remained pretty much static, while JSHint has changed a great deal - it has thrown away many of JSLint's more antagonistic rules, has added a whole load of new rules, and has generally become more flexible. Also, another tool ESLint is now available, which is even more flexible and has more rule options.

In my original answer, I said that you should not force yourself to stick to JSLint's rules; as long as you understood why it was throwing a warning, you could make a judgement for yourself about whether to change the code to resolve the warning or not.

With the ultra-strict ruleset of JSLint from 2011, this was reasonable advice -- I've seen very few JavaScript codesets that could pass a JSLint test. However with the more pragmatic rules available in today's JSHint and ESLint tools, it is a much more realistic proposition to try to get your code passing through them with zero warnings.

There may still occasionally be cases where a linter will complain about something that you've done intentionally -- for example, you know that you should always use === but just this one time you have a good reason to use ==. But even then, with ESLint you have the option to specify eslint-disable around the line in question so you can still have a passing lint test with zero warnings, with the rest of your code obeying the rule. (just don't do that kind of thing too often!)


[ORIGINAL ANSWER FOLLOWS]

By all means use JSLint. But don't get hung up on the results and on fixing everything that it warns about. It will help you improve your code, and it will help you find potential bugs, but not everything that JSLint complains about turns out to be a real problem, so don't feel like you have to complete the process with zero warnings.

Pretty much any Javascript code with any significant length or complexity will produce warnings in JSLint, no matter how well written it is. If you don't believe me, try running some popular libraries like JQuery through it.

Some JSLint warnings are more valuable than others: learn which ones to watch out for, and which ones are less important. Every warning should be considered, but don't feel obliged to fix your code to clear any given warning; it's perfectly okay to look at the code and decide you're happy with it; there are times when things that JSlint doesn't like are actually the right thing to do.

How to add "Maven Managed Dependencies" library in build path eclipse?

You can install M2Eclipse and open the project as maven project in Eclipse. It will create the necessary configuration and entries.

This is also useful for subsequent updates to the pom. With maven eclipse plugin, you will need to manually regenerate the eclipse configuration for each changes.

MySQL skip first 10 results

From the manual:

To retrieve all rows from a certain offset up to the end of the result set, you can use some large number for the second parameter. This statement retrieves all rows from the 96th row to the last:

SELECT * FROM tbl LIMIT 95,18446744073709551615;

Obviously, you should replace 95 by 10. The large number they use is 2^64 - 1, by the way.

Mapping object to dictionary and vice versa

    public Dictionary<string, object> ToDictionary<T>(string key, T value)
    {
        try
        {
            var payload = new Dictionary<string, object>
            {
                { key, value }
            }; 
        } catch (Exception e)
        {
            return null;
        }
    }

    public T FromDictionary<T>(Dictionary<string, object> payload, string key)
    {
        try
        {
            JObject jObject = (JObject) payload[key];
            T t = jObject.ToObject<T>();
            return (t);
        }
        catch(Exception e) {
            return default(T);
        }
    }

Create a pointer to two-dimensional array

G'day,

The declaration

static uint8_t l_matrix[10][20];

has set aside storage for 10 rows of 20 unit8_t locations, i.e. 200 uint8_t sized locations, with each element being found by calculating 20 x row + column.

So doesn't

uint8_t (*matrix_ptr)[20] = l_matrix;

give you what you need and point to the column zero element of the first row of the array?

Edit: Thinking about this a bit further, isn't an array name, by definition, a pointer? That is, the name of an array is a synonym for the location of the first element, i.e. l_matrix[0][0]?

Edit2: As mentioned by others, the comment space is a bit too small for further discussion. Anyway:

typedef uint8_t array_of_20_uint8_t[20];
array_of_20_uint8_t *matrix_ptr = l_matrix;

does not provide any allocation of storage for the array in question.

As mentioned above, and as defined by the standard, the statement:

static uint8_t l_matrix[10][20];

has set aside 200 sequential locations of type uint8_t.

Referring to l_matrix using statements of the form:

(*l_matrix + (20 * rowno) + colno)

will give you the contents of the colno'th element found in row rowno.

All pointer manipulations automatically take into account the size of the object pointed to. - K&R Section 5.4, p.103

This is also the case if any padding or byte alignment shifting is involved in the storage of the object at hand. The compiler will automatically adjust for these. By definition of the C ANSI standard.

HTH

cheers,

'setInterval' vs 'setTimeout'

setTimeout(expression, timeout); runs the code/function once after the timeout.

setInterval(expression, timeout); runs the code/function in intervals, with the length of the timeout between them.

Example:

var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.

setTimeout(alert, 1000); // Will alert once, after a second.

CSS: fixed position on x-axis but not y?

Very easy solution is:

window.onscroll = function (){
  document.getElementById('header').style.left= 15 - (document.documentElement.scrollLeft + document.body.scrollLeft)+"px";
}

Show hide divs on click in HTML and CSS without jQuery

You can use a checkbox to simulate onClick with CSS:

input[type=checkbox]:checked + p {
    display: none;
}

JSFiddle

Adjacent sibling selectors

Refused to apply inline style because it violates the following Content Security Policy directive

Another method is to use the CSSOM (CSS Object Model), via the style property on a DOM node.

var myElem = document.querySelector('.my-selector');
myElem.style.color = 'blue';

More details on CSSOM: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style

As mentioned by others, enabling unsafe-line for css is another method to solve this.

How to change already compiled .class file without decompile?

Use a bytecode editor, like:

http://set.ee/jbe/

Be careful because you need a very good knowledge of the Java bytecode.

You can also change the class at runtime with bytecode weaving (like AspectJ).

How to open a different activity on recyclerView item onclick

_x000D_
_x000D_
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {_x000D_
    private LayoutInflater inflater;_x000D_
    private Context context;_x000D_
List<Information>data= Collections.emptyList();_x000D_
    public AdapterClass(Context context,List<Information>data){_x000D_
        this.context=context;_x000D_
_x000D_
        inflater= LayoutInflater.from(context);_x000D_
        this.data=data;_x000D_
    }_x000D_
    @Override_x000D_
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {_x000D_
       View view= inflater.inflate(R.layout.custom_row,parent,false);_x000D_
        MyViewHolder holder=new MyViewHolder(view);_x000D_
        return holder;_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public void onBindViewHolder(MyViewHolder holder, int position) {_x000D_
        Information current=data.get(position);_x000D_
        holder.title.setText(current.title);_x000D_
        holder.icon.setImageResource(current.iconId);_x000D_
_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public int getItemCount() {_x000D_
        return data.size();_x000D_
    }_x000D_
    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{_x000D_
        TextView title;_x000D_
        ImageView icon;_x000D_
_x000D_
        public MyViewHolder(View itemView) {_x000D_
            super(itemView);_x000D_
            title=(TextView)itemView.findViewById(R.id.listText);_x000D_
           icon=(ImageView)itemView.findViewById(R.id.listIcon);_x000D_
            itemView.setClickable(true);_x000D_
            itemView.setOnClickListener(this);_x000D_
        }_x000D_
_x000D_
        @Override_x000D_
        public void onClick(View v) {_x000D_
_x000D_
            Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();_x000D_
        }_x000D_
    };_x000D_
}
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {_x000D_
    private LayoutInflater inflater;_x000D_
    private Context context;_x000D_
List<Information>data= Collections.emptyList();_x000D_
    public AdapterClass(Context context,List<Information>data){_x000D_
        this.context=context;_x000D_
_x000D_
        inflater= LayoutInflater.from(context);_x000D_
        this.data=data;_x000D_
    }_x000D_
    @Override_x000D_
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {_x000D_
       View view= inflater.inflate(R.layout.custom_row,parent,false);_x000D_
        MyViewHolder holder=new MyViewHolder(view);_x000D_
        return holder;_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public void onBindViewHolder(MyViewHolder holder, int position) {_x000D_
        Information current=data.get(position);_x000D_
        holder.title.setText(current.title);_x000D_
        holder.icon.setImageResource(current.iconId);_x000D_
_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public int getItemCount() {_x000D_
        return data.size();_x000D_
    }_x000D_
    class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{_x000D_
        TextView title;_x000D_
        ImageView icon;_x000D_
_x000D_
        public MyViewHolder(View itemView) {_x000D_
            super(itemView);_x000D_
            title=(TextView)itemView.findViewById(R.id.listText);_x000D_
           icon=(ImageView)itemView.findViewById(R.id.listIcon);_x000D_
            itemView.setClickable(true);_x000D_
            itemView.setOnClickListener(this);_x000D_
        }_x000D_
_x000D_
        @Override_x000D_
        public void onClick(View v) {_x000D_
_x000D_
            Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();_x000D_
        }_x000D_
    };_x000D_
}
_x000D_
_x000D_
_x000D_

Maven2 property that indicates the parent directory

Try setting a property in each pom to find the main project directory.

In the parent:

<properties>
    <main.basedir>${project.basedir}</main.basedir>
</properties>

In the children:

<properties>
    <main.basedir>${project.parent.basedir}</main.basedir>
</properties>

In the grandchildren:

<properties>
    <main.basedir>${project.parent.parent.basedir}</main.basedir>
</properties>

There was no endpoint listening at (url) that could accept the message

Short answer but did you have Skype open? This interferes specifically with ASP.NET by default (and localhosts in general) using port:80.

In Windows: Go to Tools -> Options -> Advanced -> Connection and uncheck the box "use port 80 and 443 as alternatives for incoming connections".

How to create a printable Twitter-Bootstrap page

In case someone is looking for a solution for Bootstrap v2.X.X here. I am leaving the solution I was using. This is not fully tested on all browsers however it could be a good start.

1) make sure the media attribute of bootstrap-responsive.css is screen.

<link href="/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen" />

2) create a print.css and make sure its media attribute print

<link href="/css/print.css" rel="stylesheet" media="print" />

3) inside print.css, add the "width" of your website in html & body

html, 
body {
    width: 1200px !important;
}

4.) reproduce the necessary media query classes in print.css because they were inside bootstrap-responsive.css and we have disabled it when printing.

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

Here is full version of print.css:

html, 
body {
    width: 1200px !important;
}

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

What's the effect of adding 'return false' to a click event listener?

The return false prevents the page from being navigated and unwanted scrolling of a window to the top or bottom.

onclick="return false"

Selecting last element in JavaScript array

In case you are using ES6 you can do:

const arr = [ 1, 2, 3 ];
[ ...arr ].pop(); // 3
arr; // [ 1, 2, 3 ] (wasn't changed)

Convenient way to parse incoming multipart/form-data parameters in a Servlet

Solutions:

Solution A:

  1. Download http://www.servlets.com/cos/index.html
  2. Invoke getParameters() on com.oreilly.servlet.MultipartRequest

Solution B:

  1. Download http://jakarta.Apache.org/commons/fileupload/
  2. Invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

Solution C:

  1. Download http://users.boone.net/wbrameld/multipartformdata/
  2. Invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:

Use Struts. Struts 1.1 handles this automatically.

Reference: http://www.jguru.com/faq/view.jsp?EID=1045507

Textarea that can do syntax highlighting on the fly?

You can't actually render markup inside a textarea.

But, you can fake it by carefully positioning a div behind the textarea and adding your highlight markup there.

JavaScript takes care of syncing the content and scroll position.

_x000D_
_x000D_
var $container = $('.container');
var $backdrop = $('.backdrop');
var $highlights = $('.highlights');
var $textarea = $('textarea');
var $toggle = $('button');


var ua = window.navigator.userAgent.toLowerCase();
var isIE = !!ua.match(/msie|trident\/7|edge/);
var isWinPhone = ua.indexOf('windows phone') !== -1;
var isIOS = !isWinPhone && !!ua.match(/ipad|iphone|ipod/);

function applyHighlights(text) {
  text = text
    .replace(/\n$/g, '\n\n')
    .replace(/[A-Z].*?\b/g, '<mark>$&</mark>');

  if (isIE) {
    // IE wraps whitespace differently in a div vs textarea, this fixes it
    text = text.replace(/ /g, ' <wbr>');
  }

  return text;
}

function handleInput() {
  var text = $textarea.val();
  var highlightedText = applyHighlights(text);
  $highlights.html(highlightedText);
}

function handleScroll() {
  var scrollTop = $textarea.scrollTop();
  $backdrop.scrollTop(scrollTop);

  var scrollLeft = $textarea.scrollLeft();
  $backdrop.scrollLeft(scrollLeft);
}

function fixIOS() {
  $highlights.css({
    'padding-left': '+=3px',
    'padding-right': '+=3px'
  });
}

function bindEvents() {
  $textarea.on({
    'input': handleInput,
    'scroll': handleScroll
  });
}

if (isIOS) {
  fixIOS();
}

bindEvents();
handleInput();
_x000D_
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
*,
*::before,
*::after {
  box-sizing: border-box;
}

body {
  margin: 30px;
  background-color: #fff;
  caret-color: #000;
}

.container,
.backdrop,
textarea {
  width: 460px;
  height: 180px;
}

.highlights,
textarea {
  padding: 10px;
  font: 20px/28px 'Open Sans', sans-serif;
  letter-spacing: 1px;
}

.container {
  display: block;
  margin: 0 auto;
  transform: translateZ(0);
  -webkit-text-size-adjust: none;
}

.backdrop {
  position: absolute;
  z-index: 1;
  border: 2px solid #685972;
  background-color: #fff;
  overflow: auto;
  pointer-events: none;
  transition: transform 1s;
}

.highlights {
  white-space: pre-wrap;
  word-wrap: break-word;
  color: #000;
}

textarea {
  display: block;
  position: absolute;
  z-index: 2;
  margin: 0;
  border: 2px solid #74637f;
  border-radius: 0;
  color: transparent;
  background-color: transparent;
  overflow: auto;
  resize: none;
  transition: transform 1s;
}

mark {
  border-radius: 3px;
  color: red;
  background-color: transparent;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div class="backdrop">
    <div class="highlights"></div>
  </div>
  <textarea>All capitalized Words will be highlighted. Try Typing to see how it Works</textarea>
</div>
_x000D_
_x000D_
_x000D_

Original Pen: https://codepen.io/lonekorean/pen/gaLEMR

When to use: Java 8+ interface default method, vs. abstract method

As mentioned in other answers, the ability to add implementation to an interface was added in order to provide backward compatibility in the Collections framework. I would argue that providing backward compatibility is potentially the only good reason for adding implementation to an interface.

Otherwise, if you add implementation to an interface, you are breaking the fundamental law for why interfaces were added in the first place. Java is a single inheritance language, unlike C++ which allows for multiple inheritance. Interfaces provide the typing benefits that come with a language that supports multiple inheritance without introducing the problems that come with multiple inheritance.

More specifically, Java only allows single inheritance of an implementation, but it does allow multiple inheritance of interfaces. For example, the following is valid Java code:

class MyObject extends String implements Runnable, Comparable { ... }

MyObject inherits only one implementation, but it inherits three contracts.

Java passed on multiple inheritance of implementation because multiple inheritance of implementation comes with a host of thorny problems, which are outside the scope of this answer. Interfaces were added to allow multiple inheritance of contracts (aka interfaces) without the problems of multiple inheritance of implementation.

To support my point, here is a quote from Ken Arnold and James Gosling from the book The Java Programming Language, 4th edition:

Single inheritance precludes some useful and correct designs. The problems of multiple inheritance arise from multiple inheritance of implementation, but in many cases multiple inheritance is used to inherit a number of abstract contracts and perhaps one concrete implementation. Providing a means to inherit an abstract contract without inheriting an implementation allows the typing benefits of multiple inheritance without the problems of multiple implementation inheritance. The inheritance of an abstract contract is termed interface inheritance. The Java programming language supports interface inheritance by allowing you to declare an interface type

How does Spring autowire by name when more than one matching bean is found?

One more solution with resolving by name:

@Resource(name="country")

It uses javax.annotation package, so it's not Spring specific, but Spring supports it.

Switch statement multiple cases in JavaScript

Here's different approach avoiding the switch statement altogether:

var cases = {
  afshin: function() { alert('hey'); },
  _default: function() { alert('default'); }
};
cases.larry = cases.saeed = cases.afshin;

cases[ varName ] ? cases[ varName ]() : cases._default();

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

I regularly use IntelliJ, PHPStorm and WebStorm. Would love to only use IntelliJ. As pointed out by the vendor the "Open Directory" functionality not being in IntelliJ is painful.

Now for the rub part; I have tried using IntelliJ as my single IDE and have found performance to be terrible compared to the lighter weight versions. Intellisense is almost useless in IntelliJ compared to WebStorm.

MS Access: how to compact current database in VBA

If you want to compact/repair an external mdb file (not the one you are working in just now):

Application.compactRepair sourecFile, destinationFile

If you want to compact the database you are working with:

Application.SetOption "Auto compact", True

In this last case, your app will be compacted when closing the file.

My opinion: writting a few lines of code in an extra MDB "compacter" file that you can call when you want to compact/repair an mdb file is very usefull: in most situations the file that needs to be compacted cannot be opened normally anymore, so you need to call the method from outside the file.

Otherwise, the autocompact shall by default be set to true in each main module of an Access app.

In case of a disaster, create a new mdb file and import all objects from the buggy file. You will usually find a faulty object (form, module, etc) that you will not be able to import.

Single-threaded apartment - cannot instantiate ActiveX control

If you used [STAThread] to the main entry of your application and still get the error you may need to make a Thread-Safe call to the control... something like below. In my case with the same problem the following solution worked!

Private void YourFunc(..)
{
    if (this.InvokeRequired)
    {
        Invoke(new MethodInvoker(delegate()
        {
           // Call your method YourFunc(..);
        }));
    }
    else
    {
        ///
    }

Convert URL to File or Blob for FileReader.readAsDataURL

Add cors mode to prevent files cors blocked

fetch(url,{mode:"cors"})
                    .then(res => res.blob())
                    .then(blob => {
                        const file = new File([blob], 'dot.png', {type:'image/png'});
                        console.log(file);
                    });

how to split the ng-repeat data with three columns using bootstrap

The most reliable and technically correct approach is to transform the data in the controller. Here's a simple chunk function and usage.

function chunk(arr, size) {
  var newArr = [];
  for (var i=0; i<arr.length; i+=size) {
    newArr.push(arr.slice(i, i+size));
  }
  return newArr;
}

$scope.chunkedData = chunk(myData, 3);

Then your view would look like this:

<div class="row" ng-repeat="rows in chunkedData">
  <div class="span4" ng-repeat="item in rows">{{item}}</div>
</div>

If you have any inputs within the ng-repeat, you will probably want to unchunk/rejoin the arrays as the data is modified or on submission. Here's how this would look in a $watch, so that the data is always available in the original, merged format:

$scope.$watch('chunkedData', function(val) {
  $scope.data = [].concat.apply([], val);
}, true); // deep watch

Many people prefer to accomplish this in the view with a filter. This is possible, but should only be used for display purposes! If you add inputs within this filtered view, it will cause problems that can be solved, but are not pretty or reliable.

The problem with this filter is that it returns new nested arrays each time. Angular is watching the return value from the filter. The first time the filter runs, Angular knows the value, then runs it again to ensure it is done changing. If both values are the same, the cycle is ended. If not, the filter will fire again and again until they are the same, or Angular realizes an infinite digest loop is occurring and shuts down. Because new nested arrays/objects were not previously tracked by Angular, it always sees the return value as different from the previous. To fix these "unstable" filters, you must wrap the filter in a memoize function. lodash has a memoize function and the latest version of lodash also includes a chunk function, so we can create this filter very simply using npm modules and compiling the script with browserify or webpack.

Remember: display only! Filter in the controller if you're using inputs!

Install lodash:

npm install lodash-node

Create the filter:

var chunk = require('lodash-node/modern/array/chunk');
var memoize = require('lodash-node/modern/function/memoize');

angular.module('myModule', [])
.filter('chunk', function() {
  return memoize(chunk);
});

And here's a sample with this filter:

<div ng-repeat="row in ['a','b','c','d','e','f'] | chunk:3">
  <div class="column" ng-repeat="item in row">
    {{($parent.$index*row.length)+$index+1}}. {{item}}
  </div>
</div>

Order items vertically

1  4
2  5
3  6

Regarding vertical columns (list top to bottom) rather than horizontal (left to right), the exact implementation depends on the desired semantics. Lists that divide up unevenly can be distributed different ways. Here's one way:

<div ng-repeat="row in columns">
  <div class="column" ng-repeat="item in row">
    {{item}}
  </div>
</div>
var data = ['a','b','c','d','e','f','g'];
$scope.columns = columnize(data, 3);
function columnize(input, cols) {
  var arr = [];
  for(i = 0; i < input.length; i++) {
    var colIdx = i % cols;
    arr[colIdx] = arr[colIdx] || [];
    arr[colIdx].push(input[i]);
  }
  return arr;
}

However, the most direct and just plainly simple way to get columns is to use CSS columns:

.columns {
  columns: 3;
}
<div class="columns">
  <div ng-repeat="item in ['a','b','c','d','e','f','g']">
    {{item}}
  </div>
</div>

How to change the timeout on a .NET WebClient object

As Sohnee says, using System.Net.HttpWebRequest and set the Timeout property instead of using System.Net.WebClient.

You can't however set an infinite timeout value (it's not supported and attempting to do so will throw an ArgumentOutOfRangeException).

I'd recommend first performing a HEAD HTTP request and examining the Content-Length header value returned to determine the number of bytes in the file you're downloading and then setting the timeout value accordingly for subsequent GET request or simply specifying a very long timeout value that you would never expect to exceed.

Modify the legend of pandas bar plot

This is slightly an edge case but I think it can add some value to the other answers.

If you add more details to the graph (say an annotation or a line) you'll soon discover that it is relevant when you call legend on the axis: if you call it at the bottom of the script it will capture different handles for the legend elements, messing everything.

For instance the following script:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))

ax.legend(["AAA", "BBB"]); #quickfix: move this at the third line

Will give you this figure, which is wrong: enter image description here

While this a toy example which can be easily fixed by changing the order of the commands, sometimes you'll need to modify the legend after several operations and hence the next method will give you more flexibility. Here for instance I've also changed the fontsize and position of the legend:

df = pd.DataFrame({'A':26, 'B':20}, index=['N'])
ax = df.plot(kind='bar')
ax.hlines(23, -.5,.5, linestyles='dashed')
ax.annotate('average',(-0.4,23.5))
ax.legend(["AAA", "BBB"]);

# do potentially more stuff here

h,l = ax.get_legend_handles_labels()
ax.legend(h[:2],["AAA", "BBB"], loc=3, fontsize=12)

This is what you'll get:

enter image description here

T-SQL Cast versus Convert

CAST uses ANSI standard. In case of portability, this will work on other platforms. CONVERT is specific to sql server. But is very strong function. You can specify different styles for dates

git revert back to certain commit

git reset --hard 4a155e5 Will move the HEAD back to where you want to be. There may be other references ahead of that time that you would need to remove if you don't want anything to point to the history you just deleted.

hash keys / values as array

In ES5 supported (or shimmed) browsers...

var keys = Object.keys(myHash);

var values = keys.map(function(v) { return myHash[v]; });

Shims from MDN...

Eclipse C++ : "Program "g++" not found in PATH"

The PATH is locate at Project Properties > C/C++ Build > Environment (see screenshot below).

enter image description here

For your reference, I am using MinGW, I got the same error before I got the MSYS install. Later I found out that I also need MSYS to be install because the make.exe wasn't come with MinGW. (I don't this error was cause be MSYS.)

After MSYS is installed, add MSYS and MinGW path into environment variable, restart Eclipse. Remember to rebuild your project in order to rectify the error. If error still persist after restart, recreate the workspace. At least this has solved the problem on my site, hopes this help on you too.

Good luck!

shell script. how to extract string using regular expressions

Using bash regular expressions:

re="http://([^/]+)/"
if [[ $name =~ $re ]]; then echo ${BASH_REMATCH[1]}; fi

Edit - OP asked for explanation of syntax. Regular expression syntax is a large topic which I can't explain in full here, but I will attempt to explain enough to understand the example.

re="http://([^/]+)/"

This is the regular expression stored in a bash variable, re - i.e. what you want your input string to match, and hopefully extract a substring. Breaking it down:

  • http:// is just a string - the input string must contain this substring for the regular expression to match
  • [] Normally square brackets are used say "match any character within the brackets". So c[ao]t would match both "cat" and "cot". The ^ character within the [] modifies this to say "match any character except those within the square brackets. So in this case [^/] will match any character apart from "/".
  • The square bracket expression will only match one character. Adding a + to the end of it says "match 1 or more of the preceding sub-expression". So [^/]+ matches 1 or more of the set of all characters, excluding "/".
  • Putting () parentheses around a subexpression says that you want to save whatever matched that subexpression for later processing. If the language you are using supports this, it will provide some mechanism to retrieve these submatches. For bash, it is the BASH_REMATCH array.
  • Finally we do an exact match on "/" to make sure we match all the way to end of the fully qualified domain name and the following "/"

Next, we have to test the input string against the regular expression to see if it matches. We can use a bash conditional to do that:

if [[ $name =~ $re ]]; then
    echo ${BASH_REMATCH[1]}
fi

In bash, the [[ ]] specify an extended conditional test, and may contain the =~ bash regular expression operator. In this case we test whether the input string $name matches the regular expression $re. If it does match, then due to the construction of the regular expression, we are guaranteed that we will have a submatch (from the parentheses ()), and we can access it using the BASH_REMATCH array:

  • Element 0 of this array ${BASH_REMATCH[0]} will be the entire string matched by the regular expression, i.e. "http://www.google.com/".
  • Subsequent elements of this array will be subsequent results of submatches. Note you can have multiple submatch () within a regular expression - The BASH_REMATCH elements will correspond to these in order. So in this case ${BASH_REMATCH[1]} will contain "www.google.com", which I think is the string you want.

Note that the contents of the BASH_REMATCH array only apply to the last time the regular expression =~ operator was used. So if you go on to do more regular expression matches, you must save the contents you need from this array each time.

This may seem like a lengthy description, but I have really glossed over several of the intricacies of regular expressions. They can be quite powerful, and I believe with decent performance, but the regular expression syntax is complex. Also regular expression implementations vary, so different languages will support different features and may have subtle differences in syntax. In particular escaping of characters within a regular expression can be a thorny issue, especially when those characters would have an otherwise different meaning in the given language.


Note that instead of setting the $re variable on a separate line and referring to this variable in the condition, you can put the regular expression directly into the condition. However in bash 3.2, the rules were changed regarding whether quotes around such literal regular expressions are required or not. Putting the regular expression in a separate variable is a straightforward way around this, so that the condition works as expected in all bash versions that support the =~ match operator.

AngularJS ui router passing data between states without URL

The params object is included in $stateParams, but won't be part of the url.

1) In the route configuration:

$stateProvider.state('edit_user', {
    url: '/users/:user_id/edit',
    templateUrl: 'views/editUser.html',
    controller: 'editUserCtrl',
    params: {
        paramOne: { objectProperty: "defaultValueOne" },  //default value
        paramTwo: "defaultValueTwo"
    }
});

2) In the controller:

.controller('editUserCtrl', function ($stateParams, $scope) {       
    $scope.paramOne = $stateParams.paramOne;
    $scope.paramTwo = $stateParams.paramTwo;
});

3A) Changing the State from a controller

$state.go("edit_user", {
    user_id: 1,                
    paramOne: { objectProperty: "test_not_default1" },
    paramTwo: "from controller"
});

3B) Changing the State in html

<div ui-sref="edit_user({ user_id: 3, paramOne: { objectProperty: 'from_html1' }, paramTwo: 'fromhtml2' })"></div>

Example Plunker

Ruby combining an array into one string

Here's my solution:

@arr = ['<p>Hello World</p>', '<p>This is a test</p>']
@arr.reduce(:+)
=> <p>Hello World</p><p>This is a test</p>

Jasmine JavaScript Testing - toBe vs toEqual

For primitive types (e.g. numbers, booleans, strings, etc.), there is no difference between toBe and toEqual; either one will work for 5, true, or "the cake is a lie".

To understand the difference between toBe and toEqual, let's imagine three objects.

var a = { bar: 'baz' },
    b = { foo: a },
    c = { foo: a };

Using a strict comparison (===), some things are "the same":

> b.foo.bar === c.foo.bar
true

> b.foo.bar === a.bar
true

> c.foo === b.foo
true

But some things, even though they are "equal", are not "the same", since they represent objects that live in different locations in memory.

> b === c
false

Jasmine's toBe matcher is nothing more than a wrapper for a strict equality comparison

expect(c.foo).toBe(b.foo)

is the same thing as

expect(c.foo === b.foo).toBe(true)

Don't just take my word for it; see the source code for toBe.

But b and c represent functionally equivalent objects; they both look like

{ foo: { bar: 'baz' } }

Wouldn't it be great if we could say that b and c are "equal" even if they don't represent the same object?

Enter toEqual, which checks "deep equality" (i.e. does a recursive search through the objects to determine whether the values for their keys are equivalent). Both of the following tests will pass:

expect(b).not.toBe(c);
expect(b).toEqual(c);

Hope that helps clarify some things.

How to stretch children to fill cross-axis?

  • The children of a row-flexbox container automatically fill the container's vertical space.

  • Specify flex: 1; for a child if you want it to fill the remaining horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
  flex: 1; _x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

  • Specify flex: 1; for both children if you want them to fill equal amounts of the horizontal space:

_x000D_
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
  flex-direction: row;_x000D_
  align-items: stretch;_x000D_
  width: 100%;_x000D_
  height: 5em;_x000D_
  background: #ccc;_x000D_
}_x000D_
.wrapper > div _x000D_
{_x000D_
  flex: 1; _x000D_
}_x000D_
.wrapper > .left_x000D_
{_x000D_
  background: #fcc;_x000D_
}_x000D_
.wrapper > .right_x000D_
{_x000D_
  background: #ccf;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="left">Left</div>_x000D_
  <div class="right">Right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

If you are facing this issue in case of Sqlite then

. I think this is the problem with version of Sqlite,I had the same problem when I was using this versions of SqLite

Version 2.2.4:

enter image description here

After checking version here enter image description here I changed the version then it worked.

enter image description here

No error after using this

Version 2.1.2:

enter image description here

Looking for simple Java in-memory cache

If you're needing something simple, would this fit the bill?

Map<K, V> myCache = Collections.synchronizedMap(new WeakHashMap<K, V>());

It wont save to disk, but you said you wanted simple...

Links:

(As Adam commented, synchronising a map has a performance hit. Not saying the idea doesn't have hairs on it, but would suffice as a quick and dirty solution.)

DateTimePicker: pick both date and time

Set the Format to Custom and then specify the format:

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss";  

or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)

Don't know about the picker for date and time together. Sounds like a custom control to me.

Refused to load the font 'data:font/woff.....'it violates the following Content Security Policy directive: "default-src 'self'". Note that 'font-src'

For me it was because of the Chrome extension 'Grammarly'. After disabling that, I did not get the error.

QLabel: set color of text and background

This one is working perfect

QColorDialog *dialog = new QColorDialog(this);
QColor color=  dialog->getColor();
QVariant variant= color;
QString colcode = variant.toString();
ui->label->setStyleSheet("QLabel { background-color :"+colcode+" ; color : blue; }");

getColor() method returns the selected color. You can change label color using stylesheet