Programs & Examples On #Selector

A selector can be a string identifying a method name in the Objective-C or Smalltalk programming language or a special kind of switch used in computers to connect multiple lines (I/O) to a single line. Please do not use this tag for jQuery/CSS selectors.

android button selector

Create custom_selector.xml in drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:drawable="@drawable/unselected" android:state_pressed="true" />
   <item android:drawable="@drawable/selected" />
</selector>

Create selected.xml shape in drawable folder

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="90dp">
   <solid android:color="@color/selected"/>
   <padding />
   <stroke android:color="#000" android:width="1dp"/>
   <corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>
</shape>

Create unselected.xml shape in drawable folder

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" android:padding="90dp">
   <solid android:color="@color/unselected"/>
   <padding />
   <stroke android:color="#000" android:width="1dp"/>
   <corners android:bottomRightRadius="15dp" android:bottomLeftRadius="15dp" android:topLeftRadius="15dp" android:topRightRadius="15dp"/>
</shape>

Add following colors for selected/unselected state in color.xml of values folder

<color name="selected">#a8cf45</color>
<color name="unselected">#ff8cae3b</color>

you can check complete solution from here

@selector() in Swift?

Create Refresh control using Selector method.   
    var refreshCntrl : UIRefreshControl!
    refreshCntrl = UIRefreshControl()
    refreshCntrl.tintColor = UIColor.whiteColor()
    refreshCntrl.attributedTitle = NSAttributedString(string: "Please Wait...")
    refreshCntrl.addTarget(self, action:"refreshControlValueChanged", forControlEvents: UIControlEvents.ValueChanged)
    atableView.addSubview(refreshCntrl)

//Refresh Control Method

func refreshControlValueChanged(){
    atableView.reloadData()
    refreshCntrl.endRefreshing()

}

Passing parameters on button action:@selector

I have another solution in some cases.

store your parameter in a hidden UILabel. then add this UILabel as subview of UIButton.

when button is clicked, we can have a check on UIButton's all subviews. normally only 2 UILabel in it.

one is UIButton's title, the other is the one you just added. read that UILabel's text property, you will get the parameter.

This only apply for text parameter.

Trying to handle "back" navigation button action in iOS

The problem with didMoveToParentViewController it's that it gets called once the parent view is fully visible again so if you need to perform some tasks before that, it won't work.

And it doesn't work with the driven animation gesture. Using willMoveToParentViewController works better.

Objective-c

- (void)willMoveToParentViewController:(UIViewController *)parent{
    if (parent == NULL) {
        // ...
    }
}

Swift

override func willMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        // ...  
    }
}

Selectors in Objective-C?

From my understanding of the Apple documentation, a selector represents the name of the method that you want to call. The nice thing about selectors is you can use them in cases where the exact method to be called varies. As a simple example, you can do something like:

SEL selec;
if (a == b) {
selec = @selector(method1)
}
else
{
selec = @selector(method2)
};
[self performSelector:selec];

How to use addTarget method in swift 3

  let button: UIButton = UIButton()
    button.setImage(UIImage(named:"imagename"), for: .normal)
    button.addTarget(self, action:#selector(YourClassName.backAction(_sender:)), for: .touchUpInside)

    button.frame = CGRect.init(x: 5, y: 100, width: 45, height: 45)
    view.addSubview(button)

    @objc public func backAction(_sender: UIButton) {

    }

"unrecognized selector sent to instance" error in Objective-C

I had the same issue. The problem for me was that one button had two Action methods. What I did was create a first action method for my button and then deleted it in the view controller, but forgot to disconnect the connection in the main storyboard in the connection inspector. So when I added a second action method, there were now two action methods for one button, which caused the error.

Objective-C: Calling selectors with multiple arguments

iOS users also expect autocapitalization: In a standard text field, the first letter of a sentence in a case-sensitive language is automatically capitalized.

You can decide whether or not to implement such features; there is no dedicated API for any of the features just listed, so providing them is a competitive advantage.

Apple document is saying there is no API available for this feature and some other expected feature in a customkeyboard. so you need to find out your own logic to implement this.

jQuery select child element by class with unknown path

This should do the trick:

$('#thisElement').find('.classToSelect')

How do I select a sibling element using jQuery?

Use jQuery .siblings() to select the matching sibling.

$(this).siblings('.bidbutton');

What is the Swift equivalent of respondsToSelector?

It seems you need to define your protocol as as subprotocol of NSObjectProtocol ... then you'll get respondsToSelector method

@objc protocol YourDelegate : NSObjectProtocol
{
    func yourDelegateMethod(passObject: SomeObject)
}

note that only specifying @objc was not enough. You should be also careful that the actual delegate is a subclass of NSObject - which in Swift might not be.

Creating a selector from a method name with parameters

Beyond what's been said already about selectors, you may want to look at the NSInvocation class.

An NSInvocation is an Objective-C message rendered static, that is, it is an action turned into an object. NSInvocation objects are used to store and forward messages between objects and between applications, primarily by NSTimer objects and the distributed objects system.

An NSInvocation object contains all the elements of an Objective-C message: a target, a selector, arguments, and the return value. Each of these elements can be set directly, and the return value is set automatically when the NSInvocation object is dispatched.

Keep in mind that while it's useful in certain situations, you don't use NSInvocation in a normal day of coding. If you're just trying to get two objects to talk to each other, consider defining an informal or formal delegate protocol, or passing a selector and target object as has already been mentioned.

Java - creating a new thread

You are calling the one.start() method in the run method of your Thread. But the run method will only be called when a thread is already started. Do this instead:

one = new Thread() {
    public void run() {
        try {
            System.out.println("Does it work?");

            Thread.sleep(1000);

            System.out.println("Nope, it doesnt...again.");
        } catch(InterruptedException v) {
            System.out.println(v);
        }
    }  
};

one.start();

How to get numeric position of alphabets in java?

just logic I can suggest take two arrays.

one is Char array

and another is int array.

convert ur input string to char array,get the position of char from char and int array.

dont expect source code here

Heroku 'Permission denied (publickey) fatal: Could not read from remote repository' woes

I'd like to add another solution since I didn't see it here. My problem was that heroku was linking to the wrong url (since I kept playing around with url names). Editing the remote url solved my problem:

git remote set-url heroku <heroku-url-here>

Merging dataframes on index with pandas

You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

>>> df1.join(df2, how='outer')
            V1  V2
A 1/1/2012  12  15
  2/1/2012  14 NaN
  3/1/2012 NaN  21
B 1/1/2012  15  24
  2/1/2012   8   9
C 1/1/2012  17 NaN
  2/1/2012   9 NaN
D 1/1/2012 NaN   7
  2/1/2012 NaN  16

Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

passing 2 $index values within nested ng-repeat

Just use ng-repeat="(sectionIndex, section) in sections"

and that will be useable on the next level ng-repeat down.

<ul ng-repeat="(sectionIndex, section) in sections">
    <li  class="section_title {{section.active}}" >
        {{section.name}}
    </li>
    <ul>
        <li ng-repeat="tutorial in section.tutorials">
            {{tutorial.name}}, Your section index is {{sectionIndex}}
        </li>
    </ul>
</ul>

What's the idiomatic syntax for prepending to a short python list?

If you can go the functional way, the following is pretty clear

new_list = [x] + your_list

Of course you haven't inserted x into your_list, rather you have created a new list with x preprended to it.

display Java.util.Date in a specific format

How about:

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
System.out.println(dateFormat.format(dateFormat.parse("31/05/2011")));

> 31/05/2011

jQuery: How to capture the TAB keypress within a Textbox

Try this:

$('#contra').focusout(function (){
    $('#btnPassword').focus();
});

What is Inversion of Control?

  1. Inversion of control is a pattern used for decoupling components and layers in the system. The pattern is implemented through injecting dependencies into a component when it is constructed. These dependences are usually provided as interfaces for further decoupling and to support testability. IoC / DI containers such as Castle Windsor, Unity are tools (libraries) which can be used for providing IoC. These tools provide extended features above and beyond simple dependency management, including lifetime, AOP / Interception, policy, etc.

  2. a. Alleviates a component from being responsible for managing it's dependencies.
    b. Provides the ability to swap dependency implementations in different environments.
    c. Allows a component be tested through mocking of dependencies.
    d. Provides a mechanism for sharing resources throughout an application.

  3. a. Critical when doing test-driven development. Without IoC it can be difficult to test, because the components under test are highly coupled to the rest of the system.
    b. Critical when developing modular systems. A modular system is a system whose components can be replaced without requiring recompilation.
    c. Critical if there are many cross-cutting concerns which need to addressed, partilarly in an enterprise application.

Split string with string as delimiter

@ECHO OFF
SETLOCAL
SET "string=string1 by string2.txt"
SET "string=%string:* by =%"
ECHO +%string%+

GOTO :EOF

The above SET command will remove the unwanted data. Result shown between + to demonstrate absence of spaces.

Formula: set var=%somevar:*string1=string2%

will assign to var the value of somevar with all characters up to string1 replaced by string2. The enclosing quotes in a set command ensure that any stray trailing spaces on the line are not included in the value assigned.

replace anchor text with jquery

To reference an element by id, you need to use the # qualifier.

Try:

alert($("#link1").text());

To replace it, you could use:

$("#link1").text('New text');

The .html() function would work in this case too.

Laravel: PDOException: could not find driver

I had a similar issue in Ubuntu 16.04 and what help me was that i installed php-mysql for php 7.2. I would recommend you run the following command if you have php 7.2 or install php mysql depending on your version of PHP. Make sure that you have installed the DBAL packege

apt-get install php7.2-mysql

systemctl restart apache2

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

From here.

For IIS7 and above, you also need to add the lines below:

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

Android getActivity() is undefined

This is because you're using getActivity() inside an inner class. Try using:

SherlockFragmentActivity.this.getActivity()

instead, though there's really no need for the getActivity() part. In your case, SherlockFragmentActivity .this should suffice.

List of lists into numpy array

Again, after searching for the problem of converting nested lists with N levels into an N-dimensional array I found nothing, so here's my way around it:

import numpy as np

new_array=np.array([[[coord for coord in xk] for xk in xj] for xj in xi], ndmin=3) #this case for N=3

How to execute a program or call a system command from Python

Here's a summary of the ways to call external programs and the advantages and disadvantages of each:

  1. os.system("some_command with args") passes the command and arguments to your system's shell. This is nice because you can actually run multiple commands at once in this manner and set up pipes and input/output redirection. For example:

    os.system("some_command < input_file | another_command > output_file")  
    

However, while this is convenient, you have to manually handle the escaping of shell characters such as spaces, etc. On the other hand, this also lets you run commands which are simply shell commands and not actually external programs. See the documentation.

  1. stream = os.popen("some_command with args") will do the same thing as os.system except that it gives you a file-like object that you can use to access standard input/output for that process. There are 3 other variants of popen that all handle the i/o slightly differently. If you pass everything as a string, then your command is passed to the shell; if you pass them as a list then you don't need to worry about escaping anything. See the documentation.

  2. The Popen class of the subprocess module. This is intended as a replacement for os.popen but has the downside of being slightly more complicated by virtue of being so comprehensive. For example, you'd say:

    print subprocess.Popen("echo Hello World", shell=True, stdout=subprocess.PIPE).stdout.read()
    

    instead of:

    print os.popen("echo Hello World").read()
    

    but it is nice to have all of the options there in one unified class instead of 4 different popen functions. See the documentation.

  3. The call function from the subprocess module. This is basically just like the Popen class and takes all of the same arguments, but it simply waits until the command completes and gives you the return code. For example:

    return_code = subprocess.call("echo Hello World", shell=True)  
    

    See the documentation.

  4. If you're on Python 3.5 or later, you can use the new subprocess.run function, which is a lot like the above but even more flexible and returns a CompletedProcess object when the command finishes executing.

  5. The os module also has all of the fork/exec/spawn functions that you'd have in a C program, but I don't recommend using them directly.

The subprocess module should probably be what you use.

Finally please be aware that for all methods where you pass the final command to be executed by the shell as a string and you are responsible for escaping it. There are serious security implications if any part of the string that you pass can not be fully trusted. For example, if a user is entering some/any part of the string. If you are unsure, only use these methods with constants. To give you a hint of the implications consider this code:

print subprocess.Popen("echo %s " % user_input, stdout=PIPE).stdout.read()

and imagine that the user enters something "my mama didnt love me && rm -rf /" which could erase the whole filesystem.

mysqli::query(): Couldn't fetch mysqli

I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.

$db_connection = new mysqli("127.0.0.1","root","","db_name");

Hope it helps.

How to get the GL library/headers?

What operating system?

Here on Ubuntu, I have

$ dpkg -S /usr/include/GL/gl.h 
mesa-common-dev: /usr/include/GL/gl.h
$ 

but not the difference in a) capitalization and b) forward/backward slashes. Your example is likely to be wrong in its use of backslashes.

Jquery Open in new Tab (_blank)

you cannot set target attribute to div, becacuse div does not know how to handle http requests. instead of you set target attribute for link tag.

$(this).find("a").target = "_blank";
window.location= $(this).find("a").attr("href")

base 64 encode and decode a string in angular (2+)

Use btoa("yourstring")

more info: https://developer.mozilla.org/en/docs/Web/API/WindowBase64/Base64_encoding_and_decoding

TypeScript is a superset of Javascript, it can use existing Javascript libraries and web APIs

How to open mail app from Swift

In Swift 3 you make sure to add import MessageUI and needs conform to the MFMailComposeViewControllerDelegate protocol.

func sendEmail() {
  if MFMailComposeViewController.canSendMail() {
    let mail = MFMailComposeViewController()
    mail.mailComposeDelegate = self
    mail.setToRecipients(["[email protected]"])
    mail.setMessageBody("<p>You're so awesome!</p>", isHTML: true)

    present(mail, animated: true)
  } else {
    // show failure alert
  }
}

Protocol:

func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
  controller.dismiss(animated: true)
}

What is the "right" way to iterate through an array in Ruby?

This will iterate through all the elements:

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }

Prints:

1
2
3
4
5
6

This will iterate through all the elements giving you the value and the index:

array = ["A", "B", "C"]
array.each_with_index {|val, index| puts "#{val} => #{index}" }

Prints:

A => 0
B => 1
C => 2

I'm not quite sure from your question which one you are looking for.

Why declare unicode by string in python?

That doesn't set the format of the string; it sets the format of the file. Even with that header, "hello" is a byte string, not a Unicode string. To make it Unicode, you're going to have to use u"hello" everywhere. The header is just a hint of what format to use when reading the .py file.

Get class labels from Keras functional model

In addition to @Emilia Apostolova answer to get the ground truth labels, from

generator = train_datagen.flow_from_directory("train", batch_size=batch_size)

just call

y_true_labels = generator.classes

How can I disable all views inside the layout?

The easiest way is creating a <View in your xml, with match_parent for height and width, make sure the view is above every other views, then when you want to prevent clicks, make it visible add an onClickListener to that view with null as parameter.

Example:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
        android:layout_height="fill_parent">
     <Button 
        android:id="@+id/backbutton"
        android:text="Back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    <LinearLayout
        android:id="@+id/my_layout"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
        <TextView
            android:id="@+id/my_text_view"
            android:text="First Name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <EditText
            android:id="@+id/my_edit_view"
            android:width="100px"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" /> 
        
        <View
            android:id="@+id/disable_layout_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="gone"/>
    </LinearLayout>

</LinearLayout>

Then in your code:

val disableLayoutView = rootView.find<View>(R.id.disable_layout_view)
disableLayoutView.visibility = View.VISIBLE
disableLayoutView.setOnClickListener(null)

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

How to negate the whole regex?

\b(?=\w)(?!(ma|(t){1}))\b(\w*)

this is for the given regex.
the \b is to find word boundary.
the positive look ahead (?=\w) is here to avoid spaces.
the negative look ahead over the original regex is to prevent matches of it.
and finally the (\w*) is to catch all the words that are left.
the group that will hold the words is group 3.
the simple (?!pattern) will not work as any sub-string will match
the simple ^(?!(?:m{2}|t)$).*$ will not work as it's granularity is full lines

How can I get the current time in C#?

DateTime.Now.ToShortTimeString().ToString()

This Will give you DateTime as 10:50PM

alert() not working in Chrome

I had the same issue recently on my test server. After searching for reasons this might be happening and testing the solutions I found here, I recalled that I had clicked the "Stop this page from creating pop-ups" option a few hours before when the script I was working on was wildly popping up alerts.

The solution was as simple as closing the tab and opening a fresh one!

Upload files with HTTPWebrequest (multipart/form-data)

My ASP.NET Upload FAQ has an article on this, with example code: Upload files using an RFC 1867 POST request with HttpWebRequest/WebClient. This code doesn't load files into memory (as opposed to the code above), supports multiple files, and supports form values, setting credentials and cookies, etc.

Edit: looks like Axosoft took down the page. Thanks guys.

It's still accessible via archive.org.

SQL exclude a column using SELECT * [except columnA] FROM tableA?

Depending on the size of your table, you can export it into Excel and transpose it to have a new table in which the columns of original table will be the rows in new table. Then take it back into your SQL database and select the rows according to the condition and insert them into another new table. Finally export this newer table to Excel and do another transpose to have your desired table and take it back to your SQL database.

Not sure if tranpose can be done within SQL database, if yes then it will be even easier.

Jeff

Insert Unicode character into JavaScript

The answer is correct, but you don't need to declare a variable. A string can contain your character:

"This string contains omega, that looks like this: \u03A9"

Unfortunately still those codes in ASCII are needed for displaying UTF-8, but I am still waiting (since too many years...) the day when UTF-8 will be same as ASCII was, and ASCII will be just a remembrance of the past.

Allow a div to cover the whole page instead of the area within the container

#dimScreen{
 position:fixed;
 top:0px;
 left:0px;
 width:100%;
 height:100%;
}

Null vs. False vs. 0 in PHP

False and 0 are conceptually similar, i.e. they are isomorphic. 0 is the initial value for the algebra of natural numbers, and False is the initial value for the Boolean algebra.

In other words, 0 can be defined as the number which, when added to some natural number, yields that same number:

x + 0 = x

Similarly, False is a value such that a disjunction of it and any other value is that same value:

x || False = x

Null is conceptually something totally different. Depending on the language, there are different semantics for it, but none of them describe an "initial value" as False and 0 are. There is no algebra for Null. It pertains to variables, usually to denote that the variable has no specific value in the current context. In most languages, there are no operations defined on Null, and it's an error to use Null as an operand. In some languages, there is a special value called "bottom" rather than "null", which is a placeholder for the value of a computation that does not terminate.

I've written more extensively about the implications of NULL elsewhere.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysql.sock' (2)

Firstly, please confirm mysql-server is installed. I have the same error when mysql-server is installed but corrupted somehow. I do the trick by uninstall mysql completely and reinstall it.

sudo apt-get remove --purge mysql*
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get install mysql-server mysql-client

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

You can use

value.ToString(CultureInfo.InvariantCulture)

to get exact double value without putting precision.

Python module os.chmod(file, 664) does not change the permission to rw-rw-r-- but -w--wx----

Use permission symbols instead of numbers

Your problem would have been avoided if you had used the more semantically named permission symbols rather than raw magic numbers, e.g. for 664:

#!/usr/bin/env python3

import os
import stat

os.chmod(
    'myfile',
    stat.S_IRUSR |
    stat.S_IWUSR |
    stat.S_IRGRP |
    stat.S_IWGRP |
    stat.S_IROTH
)

This is documented at https://docs.python.org/3/library/os.html#os.chmod and the names are the same as the POSIX C API values documented at man 2 stat.

Another advantage is the greater portability as mentioned in the docs:

Note: Although Windows supports chmod(), you can only set the file’s read-only flag with it (via the stat.S_IWRITE and stat.S_IREAD constants or a corresponding integer value). All other bits are ignored.

chmod +x is demonstrated at: How do you do a simple "chmod +x" from within python?

Tested in Ubuntu 16.04, Python 3.5.2.

Apache won't follow symlinks (403 Forbidden)

Related to this question, I just figured out why my vhost was giving me that 403.

I had tested ALL possibilities on this question and others without luck. It almost drives me mad.

I am setting up a server with releases deployment similar to Capistrano way through symlinks and when I tried to access the DocRoot folder (which is now a symlink to current release folder) it gave me the 403.

My vhost is:

DocumentRoot /var/www/site.com/html
<Directory /var/www/site.com/html>
        AllowOverride All
        Options +FollowSymLinks
        Require all granted
</Directory>

and my main httpd.conf file was (default Apache 2.4 install):

DocumentRoot "/var/www"
<Directory "/var/www">
    Options -Indexes -FollowSymLinks -Includes
(...)

It turns out that the main Options definition was taking precedence over my vhosts fiel (for me that is counter intuitive). So I've changed it to:

DocumentRoot "/var/www"
<Directory "/var/www">
    Options -Indexes +FollowSymLinks -Includes
(...)

and Eureka! (note the plus sign before FollowSymLinks in MAIN httpd.conf file. Hope this help some other lost soul.

How can I get file extensions with JavaScript?

function file_get_ext(filename)
    {
    return typeof filename != "undefined" ? filename.substring(filename.lastIndexOf(".")+1, filename.length).toLowerCase() : false;
    }

How to insert close button in popover for Bootstrap

Sticky on hover, HTML:

<a href="javascript:;" data-toggle="popover" data-content="Vivamus sagittis lacus vel augue laoreet rutrum faucibus." title="Lorem Ipsum">...</a>

Javascript:

$('[data-toggle=popover]').hover(function(e) {
  if( !$(".popover").is(':visible') ) {
      var el = this;
      $(el).popover('show');
      $(".popover > h3").append('<span class="close icon icon-remove"></span>')
                        .find('.close').on('click', function(e) {
                            e.preventDefault();
                            $(el).popover('hide');
                        }
      );
  }
});

How to access site running apache server over lan without internet connection

You might also want to check your server configuration - sometimes the default for development type servers is to only accept connections from localhost.

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

Xcode error: Code signing is required for product type 'Application' in SDK 'iOS 10.0'

To run your app on a real device, you need to have an Apple ID, and have registered your device with that ID. That is why you are getting this error.

Here's how you do it.

  1. Go to the project Navigator. Cmd-1 if you can't find it.

  2. Click the project target dropdown and pick Target. enter image description here

  3. Click on the Team dropdown and pick add an account. enter image description here

  4. Sign in with your Apple ID that is linked to your developer account, or just your Apple if you don't have a dev account.

  5. If you haven't registered your device with that account yet, a button will appear, something like 'Register device'. Click that and Apple will register the device and do the certificates and code signing. (Oh my unicorns certificates and signing is so much easier than it used to be) enter image description here

Pick your physical device and hit run and it should load onto your device without error.

How to disable phone number linking in Mobile Safari?

My experience is the same as some others mentioned. The meta tag...

<meta name = "format-detection" content = "telephone=no">

...works when the website is running in Mobile Safari (i.e., with chrome) but stops working when run as a webapp (i.e., is saved to home screen and runs without chrome).

My less-than-ideal solution is to insert the values into input fields...

<input type="text" readonly="readonly" style="border:none;" value="3105551212">

It's less than ideal because, despite the border being set to none, iOS renders a multi-pixel gray bar above the field. But, it's better than seeing the number as a link.

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

How to get the title of HTML page with JavaScript?

Put in the URL bar and then click enter:

javascript:alert(document.title);

You can select and copy the text from the alert depending on the website and the web browser you are using.

How to debug a bash script?

Install VSCode, then add bash debug extension and you are ready to debug in visual mode. see Here in action.

enter image description here

Is there a way to reduce the size of the git folder?

Don't know if it will shrink it, but after I run git clean, I often do git repack -ad as well, which reduces the number of pack files.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

select convert(varchar(8), getdate(), 3)

simply use this for dd/mm/yy and this

select convert(varchar(8), getdate(), 1) 

for mm/dd/yy

git checkout master error: the following untracked working tree files would be overwritten by checkout

With Git 2.23 (August 2019), that would be, using git switch -f:

git switch -f master

That avoids the confusion with git checkout (which deals with files or branches).

And that will proceeds, even if the index or the working tree differs from HEAD.
Both the index and working tree are restored to match the switching target.
If --recurse-submodules is specified, submodule content is also restored to match the switching target.
This is used to throw away local changes.

Two onClick actions one button

Additional attributes (in this case, the second onClick) will be ignored. So, instead of onclick calling both fbLikeDump(); and WriteCookie();, it will only call fbLikeDump();. To fix, simply define a single onclick attribute and call both functions within it:

<input type="button" value="Don't show this again! " onclick="fbLikeDump();WriteCookie();" />

How to retrieve value from elements in array using jQuery?

Use: http://jsfiddle.net/xH79d/

var n = $("input[name^='card']").length;
var array = $("input[name^='card']");

for(i=0; i < n; i++) {

   // use .eq() within a jQuery object to navigate it by Index

   card_value = array.eq(i).attr('name'); // I'm assuming you wanted -name-
   // otherwise it'd be .eq(i).val(); (if you wanted the text value)
   alert(card_value);
}

?

Open page in new window without popup blocking

PS> I posted this answer on a related question. Here's how I got round the issue of my async ajax request losing the trusted context:

I opened the popup directly on the users click, directed the url to about:blank and got a handle on that window. You could probably direct the popup to a 'loading' url while your ajax request is made

var myWindow = window.open("about:blank",'name','height=500,width=550');

Then, when my request is successful, I open my callback url in the window

function showWindow(win, url) {
     win.open(url,'name','height=500,width=550');
}

What is the best method to merge two PHP objects?

To merge any number of raw objects

function merge_obj(){
    foreach(func_get_args() as $a){
        $objects[]=(array)$a;
    }
    return (object)call_user_func_array('array_merge', $objects);
}

How to get absolute path to file in /resources folder of your project

Create the classLoader instance of the class you need, then you can access the files or resources easily. now you access path using getPath() method of that class.

 ClassLoader classLoader = getClass().getClassLoader();
 String path  = classLoader.getResource("chromedriver.exe").getPath();
 System.out.println(path);

How to emulate a do-while loop in Python?

My code below might be a useful implementation, highlighting the main difference between vs as I understand it.

So in this one case, you always go through the loop at least once.

first_pass = True
while first_pass or condition:
    first_pass = False
    do_stuff()

python: creating list from string

I know this is old but here's a one liner list comprehension:

data = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']

[[int(item) if item.isdigit() else item for item in items.split(', ')] for items in data]

or

[int(item) if item.isdigit() else item for items in data for item in items.split(', ')]

What is the correct value for the disabled attribute?

HTML5 spec:

http://www.w3.org/TR/html5/forms.html#enabling-and-disabling-form-controls:-the-disabled-attribute :

The checked content attribute is a boolean attribute

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion:

The following are valid, equivalent and true:

<input type="text" disabled />
<input type="text" disabled="" />
<input type="text" disabled="disabled" />
<input type="text" disabled="DiSaBlEd" />

The following are invalid:

<input type="text" disabled="0" />
<input type="text" disabled="1" />
<input type="text" disabled="false" />
<input type="text" disabled="true" />

The absence of the attribute is the only valid syntax for false:

<input type="text" />

Recommendation

If you care about writing valid XHTML, use disabled="disabled", since <input disabled> is invalid and other alternatives are less readable. Else, just use <input disabled> as it is shorter.

How to stop C++ console application from exiting immediately?

Just add the following at the end of your program. It will try to capture some form of user input thus it stops the console from closing automatically.

cin.get();

Rails select helper - Default selected value, how?

Try this:

    <%= f.select :project_id, @project_select, :selected => f.object.project_id %>

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

You may try this, Following are few examples on how files are generated. Tool -- https://sourceforge.net/projects/csvtohive/?source=directory

  1. Select a CSV file using Browse and set hadoop root directory ex: /user/bigdataproject/

  2. Tool Generates Hadoop script with all csv files and following is a sample of generated Hadoop script to insert csv into Hadoop

    #!/bin/bash -v
    hadoop fs -put ./AllstarFull.csv /user/bigdataproject/AllstarFull.csv hive -f ./AllstarFull.hive

    hadoop fs -put ./Appearances.csv /user/bigdataproject/Appearances.csv hive -f ./Appearances.hive

    hadoop fs -put ./AwardsManagers.csv /user/bigdataproject/AwardsManagers.csv hive -f ./AwardsManagers.hive

  3. Sample of generated Hive scripts

    CREATE DATABASE IF NOT EXISTS lahman;
    USE lahman;
    CREATE TABLE AllstarFull (playerID string,yearID string,gameNum string,gameID string,teamID string,lgID string,GP string,startingPos string) row format delimited fields terminated by ',' stored as textfile;
    LOAD DATA INPATH '/user/bigdataproject/AllstarFull.csv' OVERWRITE INTO TABLE AllstarFull;
    SELECT * FROM AllstarFull;

Thanks Vijay

Naming Conventions: What to name a boolean variable?

Personally more than anything I would change the logic, or look at the business rules to see if they dictate any potential naming.

Since, the actual condition that toggles the boolean is actually the act of being "last". I would say that switching the logic, and naming it "IsLastItem" or similar would be a more preferred method.

Get each line from textarea

Use PHP DOM to parse and add <br/> in it. Like this:

$html = '<textarea> put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
quote by placing > at start of line
</textarea>';

//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('textarea');

//get text and add <br/> then remove last <br/>
$lines = $nodes->item(0)->nodeValue;

//split it by newlines
$lines = explode("\n", $lines);

//add <br/> at end of each line
foreach($lines as $line)
    $output .= $line . "<br/>";

//remove last <br/>
$output = rtrim($output, "<br/>");

//display it
var_dump($output);

This outputs:

string ' put returns between paragraphs
<br/>for linebreak add 2 spaces at end
<br/>indent code by 4 spaces
<br/>quote by placing > at start of line
' (length=141)

Using Alert in Response.Write Function in ASP.NET

string str = "Error mEssage";
Response.Write("<script language=javascript>alert('"+str+"');</script>");

SyntaxError: Unexpected Identifier in Chrome's Javascript console

copy this line and replace in your project

var myNewString = myOldString.replace ("username", visitorName);

there is a simple problem with coma (,)

Does C# support multiple inheritance?

Multiple inheritance allows programmers to create classes that combine aspects of multiple classes and their corresponding hierarchies. For ex. the C++ allows you to inherit from more than one class

In C#, the classes are only allowed to inherit from a single parent class, which is called single inheritance. But you can use interfaces or a combination of one class and interface(s), where interface(s) should be followed by class name in the signature.

Ex:

Class FirstClass { }
Class SecondClass { }

interface X { }
interface Y { }

You can inherit like the following:

class NewClass : X, Y { } In the above code, the class "NewClass" is created from multiple interfaces.

class NewClass : FirstClass, X { } In the above code, the class "NewClass" is created from interface X and class "FirstClass".

Matplotlib: ValueError: x and y must have same first dimension

You should make x and y numpy arrays, not lists:

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
              0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
              0.478,0.335,0.365,0.424,0.390,0.585,0.511])

With this change, it produces the expect plot. If they are lists, m * x will not produce the result you expect, but an empty list. Note that m is anumpy.float64 scalar, not a standard Python float.

I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:

In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]

while multiplying a list with a float gives an error (as I think it should):

In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'

The weird thing is that multiplying a Python list with a Numpy scalar apparently works:

In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []

In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]

In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]

So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:

In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123,  2.123,  3.123])

How to drop a PostgreSQL database if there are active connections to it?

In my case i had to execute a command to drop all connections including my active administrator connection

SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE datname = current_database()

which terminated all connections and show me a fatal ''error'' message :

FATAL: terminating connection due to administrator command SQL state: 57P01

After that it was possible to drop the database

How to get the absolute path to the public_html folder?

Out of curiosity, why don't you just use the url for the said folder?

http://www.mysite.com/images

Assuming that the folder never changes location, that would be the easiest way to do it.

Bootstrap 3: Scroll bars

You need to use the overflow option, but with the following parameters:

.nav {
    max-height:300px;
    overflow-y:auto;  
}

Use overflow-y:auto; so the scrollbar only appears when the content exceeds the maximum height.

If you use overflow-y:scroll, the scrollbar will always be visible - on all .nav - regardless if the content exceeds the maximum heigh or not.

Presumably you want something that adapts itself to the content rather then the the opposite.

Hope it may helpful

How to pass List<String> in post method using Spring MVC?

You can pass input as ["apple","orange"]if you want to leave the method as it is.

It worked for me with a similar method signature.

Automatically add all files in a folder to a target using CMake?

Extension for @Kleist answer:

Since CMake 3.12 additional option CONFIGURE_DEPENDS is supported by commands file(GLOB) and file(GLOB_RECURSE). With this option there is no needs to manually re-run CMake after addition/deletion of a source file in the directory - CMake will be re-run automatically on next building the project.

However, the option CONFIGURE_DEPENDS implies that corresponding directory will be re-checked every time building is requested, so build process would consume more time than without CONFIGURE_DEPENDS.

Even with CONFIGURE_DEPENDS option available CMake documentation still does not recommend using file(GLOB) or file(GLOB_RECURSE) for collect the sources.

fatal error LNK1104: cannot open file 'kernel32.lib'

I had a differnt problem on Windows 10 with Visual Studio 2017 but with the same effects. I think my problems came down to VS being installed onto a drive other than "C:\". I solved the problem by Reinstalling Windows 10 SDK

First I had to uninstall the Windows SDK (there were two versions installed). Then ran the executable. Once installed, ran visual studio and it worked fine.

Why do I need to override the equals and hashCode methods in Java?

1) The common mistake is shown in the example below.

public class Car {

    private String color;

    public Car(String color) {
        this.color = color;
    }

    public boolean equals(Object obj) {
        if(obj==null) return false;
        if (!(obj instanceof Car))
            return false;   
        if (obj == this)
            return true;
        return this.color.equals(((Car) obj).color);
    }

    public static void main(String[] args) {
        Car a1 = new Car("green");
        Car a2 = new Car("red");

        //hashMap stores Car type and its quantity
        HashMap<Car, Integer> m = new HashMap<Car, Integer>();
        m.put(a1, 10);
        m.put(a2, 20);
        System.out.println(m.get(new Car("green")));
    }
}

the green Car is not found

2. Problem caused by hashCode()

The problem is caused by the un-overridden method hashCode(). The contract between equals() and hashCode() is:

  1. If two objects are equal, then they must have the same hash code.
  2. If two objects have the same hash code, they may or may not be equal.

    public int hashCode(){  
      return this.color.hashCode(); 
    }
    

Android - Spacing between CheckBox and text

<CheckBox android:drawablePadding="16dip" - The padding between the drawables and the text.

Chaining multiple filter() in Django, is this a bug?

The way I understand it is that they are subtly different by design (and I am certainly open for correction): filter(A, B) will first filter according to A and then subfilter according to B, while filter(A).filter(B) will return a row that matches A 'and' a potentially different row that matches B.

Look at the example here:

https://docs.djangoproject.com/en/dev/topics/db/queries/#spanning-multi-valued-relationships

particularly:

Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects

...

In this second example (filter(A).filter(B)), the first filter restricted the queryset to (A). The second filter restricted the set of blogs further to those that are also (B). The entries select by the second filter may or may not be the same as the entries in the first filter.`

How do I add an active class to a Link from React Router?

As of [email protected], we can just easily use the NavLink with activeClassName instead of Link. Example:

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

class NavBar extends Component {
  render() {
    return (
      <div className="navbar">
        <ul>
          <li><NavLink to='/1' activeClassName="active">1</NavLink></li>
          <li><NavLink to='/2' activeClassName="active">2</NavLink></li>
          <li><NavLink to='/3' activeClassName="active">3</NavLink></li>
        </ul>
      </div>
    );
  }
}

Then in your CSS file:

.navbar li>.active {
  font-weight: bold;
}

The NavLink will add your custom styling attributes to the rendered element based on the current URL.

Document is here

How do I remove blank elements from an array?

 cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].delete_if {|c| c.empty? } 

How to convert enum value to int?

Sometime some C# approach makes the life easier in Java world..:

class XLINK {
static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
}
//Now is trivial to use it like a C# enum:
int rcv = XLINK.ACK;

PowerShell script to check the status of a URL

Below is the PowerShell code that I use for basic web URL testing. It includes the ability to accept invalid certs and get detailed information about the results of checking the certificate.

$CertificateValidatorClass = @'
using System;
using System.Collections.Concurrent;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace CertificateValidation
{
    public class CertificateValidationResult
    {
        public string Subject { get; internal set; }
        public string Thumbprint { get; internal set; }
        public DateTime Expiration { get; internal set; }
        public DateTime ValidationTime { get; internal set; }
        public bool IsValid { get; internal set; }
        public bool Accepted { get; internal set; }
        public string Message { get; internal set; }

        public CertificateValidationResult()
        {
            ValidationTime = DateTime.UtcNow;
        }
    }

    public static class CertificateValidator
    {
        private static ConcurrentStack<CertificateValidationResult> certificateValidationResults = new ConcurrentStack<CertificateValidationResult>();

        public static CertificateValidationResult[] CertificateValidationResults
        {
            get
            {
                return certificateValidationResults.ToArray();
            }
        }

        public static CertificateValidationResult LastCertificateValidationResult
        {
            get
            {
                CertificateValidationResult lastCertificateValidationResult = null;
                certificateValidationResults.TryPeek(out lastCertificateValidationResult);

                return lastCertificateValidationResult;
            }
        }

        public static bool ServicePointManager_ServerCertificateValidationCallback(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certificate, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {
            StringBuilder certificateValidationMessage = new StringBuilder();
            bool allowCertificate = true;

            if (sslPolicyErrors != System.Net.Security.SslPolicyErrors.None)
            {
                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch) == System.Net.Security.SslPolicyErrors.RemoteCertificateNameMismatch)
                {
                    certificateValidationMessage.AppendFormat("The remote certificate name does not match.\r\n", certificate.Subject);
                }

                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors) == System.Net.Security.SslPolicyErrors.RemoteCertificateChainErrors)
                {
                    certificateValidationMessage.AppendLine("The certificate chain has the following errors:");
                    foreach (System.Security.Cryptography.X509Certificates.X509ChainStatus chainStatus in chain.ChainStatus)
                    {
                        certificateValidationMessage.AppendFormat("\t{0}", chainStatus.StatusInformation);

                        if (chainStatus.Status == System.Security.Cryptography.X509Certificates.X509ChainStatusFlags.Revoked)
                        {
                            allowCertificate = false;
                        }
                    }
                }

                if ((sslPolicyErrors & System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable) == System.Net.Security.SslPolicyErrors.RemoteCertificateNotAvailable)
                {
                    certificateValidationMessage.AppendLine("The remote certificate was not available.");
                    allowCertificate = false;
                }

                System.Console.WriteLine();
            }
            else
            {
                certificateValidationMessage.AppendLine("The remote certificate is valid.");
            }

            CertificateValidationResult certificateValidationResult = new CertificateValidationResult
                {
                    Subject = certificate.Subject,
                    Thumbprint = certificate.GetCertHashString(),
                    Expiration = DateTime.Parse(certificate.GetExpirationDateString()),
                    IsValid = (sslPolicyErrors == System.Net.Security.SslPolicyErrors.None),
                    Accepted = allowCertificate,
                    Message = certificateValidationMessage.ToString()
                };

            certificateValidationResults.Push(certificateValidationResult);
            return allowCertificate;
        }

        public static void SetDebugCertificateValidation()
        {
            ServicePointManager.ServerCertificateValidationCallback = ServicePointManager_ServerCertificateValidationCallback;
        }

        public static void SetDefaultCertificateValidation()
        {
            ServicePointManager.ServerCertificateValidationCallback = null;
        }

        public static void ClearCertificateValidationResults()
        {
            certificateValidationResults.Clear();
        }
    }
}
'@

function Set-CertificateValidationMode
{
    <#
    .SYNOPSIS
    Sets the certificate validation mode.
    .DESCRIPTION
    Set the certificate validation mode to one of three modes with the following behaviors:
        Default -- Performs the .NET default validation of certificates. Certificates are not checked for revocation and will be rejected if invalid.
        CheckRevocationList -- Cerftificate Revocation Lists are checked and certificate will be rejected if revoked or invalid.
        Debug -- Certificate Revocation Lists are checked and revocation will result in rejection. Invalid certificates will be accepted. Certificate validation
                 information is logged and can be retrieved from the certificate handler.
    .EXAMPLE
    Set-CertificateValidationMode Debug
    .PARAMETER Mode
    The mode for certificate validation.
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param
    (
        [Parameter()]
        [ValidateSet('Default', 'CheckRevocationList', 'Debug')]
        [string] $Mode
    )

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        switch ($Mode)
        {
            'Debug'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
                [CertificateValidation.CertificateValidator]::SetDebugCertificateValidation()
            }
            'CheckRevocationList'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $true
                [CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
            }
            'Default'
            {
                [System.Net.ServicePointManager]::CheckCertificateRevocationList = $false
                [CertificateValidation.CertificateValidator]::SetDefaultCertificateValidation()
            }
        }
    }
}

function Clear-CertificateValidationResults
{
    <#
    .SYNOPSIS
    Clears the collection of certificate validation results.
    .DESCRIPTION
    Clears the collection of certificate validation results.
    .EXAMPLE
    Get-CertificateValidationResults
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param()

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        [CertificateValidation.CertificateValidator]::ClearCertificateValidationResults()
        Sleep -Milliseconds 20
    }
}

function Get-CertificateValidationResults
{
    <#
    .SYNOPSIS
    Gets the certificate validation results for all operations performed in the PowerShell session since the Debug cerificate validation mode was enabled.
    .DESCRIPTION
    Gets the certificate validation results for all operations performed in the PowerShell session since the Debug certificate validation mode was enabled in reverse chronological order.
    .EXAMPLE
    Get-CertificateValidationResults
    #>
    [CmdletBinding(SupportsShouldProcess = $false)]
    param()

    begin
    {
        $isValidatorClassLoaded = (([System.AppDomain]::CurrentDomain.GetAssemblies() | ?{ $_.GlobalAssemblyCache -eq $false }) | ?{ $_.DefinedTypes.FullName -contains 'CertificateValidation.CertificateValidator' }) -ne $null

        if ($isValidatorClassLoaded -eq $false)
        {
            Add-Type -TypeDefinition $CertificateValidatorClass
        }
    }

    process
    {
        return [CertificateValidation.CertificateValidator]::CertificateValidationResults
    }
}

function Test-WebUrl
{
    <#
    .SYNOPSIS
    Tests and reports information about the provided web URL.
    .DESCRIPTION
    Tests a web URL and reports the time taken to get and process the request and response, the HTTP status, and the error message if an error occurred.
    .EXAMPLE
    Test-WebUrl 'http://websitetotest.com/'
    .EXAMPLE
    'https://websitetotest.com/' | Test-WebUrl
    .PARAMETER HostName
    The Hostname to add to the back connection hostnames list.
    .PARAMETER UseDefaultCredentials
    If present the default Windows credential will be used to attempt to authenticate to the URL; otherwise, no credentials will be presented.
    #>
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [Uri] $Url,
        [Parameter()]
        [Microsoft.PowerShell.Commands.WebRequestMethod] $Method = 'Get',
        [Parameter()]
        [switch] $UseDefaultCredentials
    )

    process
    {
        [bool] $succeeded = $false
        [string] $statusCode = $null
        [string] $statusDescription = $null
        [string] $message = $null
        [int] $bytesReceived = 0
        [Timespan] $timeTaken = [Timespan]::Zero 

        $timeTaken = Measure-Command `
            {
                try
                {
                    [Microsoft.PowerShell.Commands.HtmlWebResponseObject] $response = Invoke-WebRequest -UseDefaultCredentials:$UseDefaultCredentials -Method $Method -Uri $Url
                    $succeeded = $true
                    $statusCode = $response.StatusCode.ToString('D')
                    $statusDescription = $response.StatusDescription
                    $bytesReceived = $response.RawContent.Length

                    Write-Verbose "$($Url.ToString()): $($statusCode) $($statusDescription) $($message)"
                }
                catch [System.Net.WebException]
                {
                    $message = $Error[0].Exception.Message
                    [System.Net.HttpWebResponse] $exceptionResponse = $Error[0].Exception.GetBaseException().Response

                    if ($exceptionResponse -ne $null)
                    {
                        $statusCode = $exceptionResponse.StatusCode.ToString('D')
                        $statusDescription = $exceptionResponse.StatusDescription
                        $bytesReceived = $exceptionResponse.ContentLength

                        if ($statusCode -in '401', '403', '404')
                        {
                            $succeeded = $true
                        }
                    }
                    else
                    {
                        Write-Warning "$($Url.ToString()): $($message)"
                    }
                }
            }

        return [PSCustomObject] @{ Url = $Url; Succeeded = $succeeded; BytesReceived = $bytesReceived; TimeTaken = $timeTaken.TotalMilliseconds; StatusCode = $statusCode; StatusDescription = $statusDescription; Message = $message; }
    }
}

Set-CertificateValidationMode Debug
Clear-CertificateValidationResults

Write-Host 'Testing web sites:'
'https://expired.badssl.com/', 'https://wrong.host.badssl.com/', 'https://self-signed.badssl.com/', 'https://untrusted-root.badssl.com/', 'https://revoked.badssl.com/', 'https://pinning-test.badssl.com/', 'https://sha1-intermediate.badssl.com/' | Test-WebUrl | ft -AutoSize

Write-Host 'Certificate validation results (most recent first):'
Get-CertificateValidationResults | ft -AutoSize

Rotating and spacing axis labels in ggplot2

ggplot 3.3.0 fixes this by providing guide_axis(angle = 90) (as guide argument to scale_.. or as x argument to guides):

library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))

ggplot(diamonds, aes(cut, carat)) +
  geom_boxplot() +
  scale_x_discrete(guide = guide_axis(angle = 90)) +
  # ... or, equivalently:
  # guides(x =  guide_axis(angle = 90)) +
  NULL

From the documentation of the angle argument:

Compared to setting the angle in theme() / element_text(), this also uses some heuristics to automatically pick the hjust and vjust that you probably want.


Alternatively, it also provides guide_axis(n.dodge = 2) (as guide argument to scale_.. or as x argument to guides) to overcome the over-plotting problem by dodging the labels vertically. It works quite well in this case:

library(ggplot2)
data(diamonds)
diamonds$cut <- paste("Super Dee-Duper",as.character(diamonds$cut))

ggplot(diamonds, aes(cut, carat)) + 
  geom_boxplot() +
  scale_x_discrete(guide = guide_axis(n.dodge = 2)) +
  NULL

Defining arrays in Google Scripts

This may be of help to a few who are struggling like I was:

var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];

Read a text file line by line in Qt

QFile inputFile(QString("/path/to/file"));
inputFile.open(QIODevice::ReadOnly);
if (!inputFile.isOpen())
    return;

QTextStream stream(&inputFile);
QString line = stream.readLine();
while (!line.isNull()) {
    /* process information */

    line = stream.readLine();
};

Java Generics With a Class & an Interface - Together

Here's how you would do it in Kotlin

fun <T> myMethod(item: T) where T : ClassA, T : InterfaceB {
    //your code here
}

Go to Matching Brace in Visual Studio?

Note: It also works for #if / #elif / #endif matching. The caret must be on the #.

Checkout multiple git repos into same Jenkins workspace

Since Multiple SCMs Plugin is deprecated.

With Jenkins Pipeline its possible to checkout multiple git repos and after building it using gradle

node {   
def gradleHome

stage('Prepare/Checkout') { // for display purposes
    git branch: 'develop', url: 'https://github.com/WtfJoke/Any.git'

    dir('a-child-repo') {
       git branch: 'develop', url: 'https://github.com/WtfJoke/AnyChild.git'
    }

    env.JAVA_HOME="${tool 'JDK8'}"
    env.PATH="${env.JAVA_HOME}/bin:${env.PATH}" // set java home in jdk environment
    gradleHome = tool '3.4.1' 
}

stage('Build') {
  // Run the gradle build
  if (isUnix()) {
     sh "'${gradleHome}/bin/gradle' clean build"
  } else {
     bat(/"${gradleHome}\bin\gradle" clean build/)
  }
}
}

You might want to consider using git submodules instead of a custom pipeline like this.

PowerShell Connect to FTP server and get files

Here is the full working code to download all files (with wildcard or file extension) from the FTP site to local directory. Set the variable values.

    #FTP Server Information - SET VARIABLES
    $ftp = "ftp://XXX.com/" 
    $user = 'UserName' 
    $pass = 'Password'
    $folder = 'FTP_Folder'
    $target = "C:\Folder\Folder1\"

    #SET CREDENTIALS
    $credentials = new-object System.Net.NetworkCredential($user, $pass)

    function Get-FtpDir ($url,$credentials) {
        $request = [Net.WebRequest]::Create($url)
        $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
        if ($credentials) { $request.Credentials = $credentials }
        $response = $request.GetResponse()
        $reader = New-Object IO.StreamReader $response.GetResponseStream() 
        while(-not $reader.EndOfStream) {
            $reader.ReadLine()
        }
        #$reader.ReadToEnd()
        $reader.Close()
        $response.Close()
    }

    #SET FOLDER PATH
    $folderPath= $ftp + "/" + $folder + "/"

    $files = Get-FTPDir -url $folderPath -credentials $credentials

    $files 

    $webclient = New-Object System.Net.WebClient 
    $webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass) 
    $counter = 0
    foreach ($file in ($files | where {$_ -like "*.txt"})){
        $source=$folderPath + $file  
        $destination = $target + $file 
        $webclient.DownloadFile($source, $target+$file)

        #PRINT FILE NAME AND COUNTER
        $counter++
        $counter
        $source
    }

How can I manually generate a .pyc file from a .py file

There is two way to do this

  1. Command line
  2. Using python program

If you are using command line use python -m compileall <argument> to compile python code to python binary code. Ex: python -m compileall -x ./*

Or, You can use this code to compile your library into byte-code.

import compileall
import os

lib_path = "your_lib_path"
build_path = "your-dest_path"

compileall.compile_dir(lib_path, force=True, legacy=True)

def moveToNewLocation(cu_path):
    for file in os.listdir(cu_path):
        if os.path.isdir(os.path.join(cu_path, file)):
            compile(os.path.join(cu_path, file))
        elif file.endswith(".pyc"):
            dest = os.path.join(build_path, cu_path ,file)
            os.makedirs(os.path.dirname(dest), exist_ok=True)
            os.rename(os.path.join(cu_path, file), dest)

moveToNewLocation(lib_path)

look at ? docs.python.org for detailed documentation

Refresh Page C# ASP.NET

Use:

Response.Redirect(Request.RawUrl, true);

how to convert binary string to decimal?

Another implementation just for functional JS practicing could be

_x000D_
_x000D_
var bin2int = s => Array.prototype.reduce.call(s, (p,c) => p*2 + +c)_x000D_
console.log(bin2int("101010"));
_x000D_
_x000D_
_x000D_ where +c coerces String type c to a Number type value for proper addition.

How to put a div in center of browser using CSS?

<html>
<head>
<style>
*
{
    margin:0;
    padding:0;
}

html, body
{
    height:100%;
}

#distance
{
    width:1px;
    height:50%;
    margin-bottom:-300px;
    float:left;
}


#something
{
    position:relative;
    margin:0 auto;
    text-align:left;
    clear:left;
    width:800px;
    min-height:600px;
    height:auto;
    border: solid 1px #993333;
    z-index: 0;
}

/* for Internet Explorer */
* html #something{
height: 600px;
}
</style>

</head>
<body>

<div id="distance"></div>

<div id="something">
</div>
</body>

</html>

Tested in FF2-3, IE6-7, Opera and works well!

Printing object properties in Powershell

Tip #1

Never use Write-Host.

Tip #12

The correct way to output information from a PowerShell cmdlet or function is to create an object that contains your data, and then to write that object to the pipeline by using Write-Output.

-Don Jones: PowerShell Master

Ideally your script would create your objects ($obj = New-Object -TypeName psobject -Property @{'SomeProperty'='Test'}) then just do a Write-Output $objects. You would pipe the output to Format-Table.

PS C:\> Run-MyScript.ps1 | Format-Table

They should really call PowerShell PowerObjectandPipingShell.

"SMTP Error: Could not authenticate" in PHPMailer

I received the same error and in mycase it was the password. My password has special characters for and if you supply the password without escaping the special characters the error will continue to show. E.g $mail->Password = " por$ch3"; is valid but will not work using the code above . The solution should be as follows: $mail->Password = "por\$ch3"; Note the Backslash I placed before the dollar character within my password. That should work if you have a password using special characters

Is it possible to opt-out of dark mode on iOS 13?

If you are not using Xcode 11 or later (i,e iOS 13 or later SDK), your app has not automatically opted to support dark mode. So, there's no need to opt out of dark mode.

If you are using Xcode 11 or later, the system has automatically enabled dark mode for your app. There are two approaches to disable dark mode depending on your preference. You can disable it entirely or disable it for any specific window, view, or view controller.

Disable Dark Mode Entirely for your App

You can disable dark mode by including the UIUserInterfaceStyle key with a value as Light in your app’s Info.plist file.
UIUserInterfaceStyle as Light
This ignores the user's preference and always applies a light appearance to your app.

Disable dark mode for Window, View, or View Controller

You can force your interface to always appear in a light or dark style by setting the overrideUserInterfaceStyle property of the appropriate window, view, or view controller.

View controllers:

override func viewDidLoad() {
    super.viewDidLoad()
    /* view controller’s views and child view controllers 
     always adopt a light interface style. */
    overrideUserInterfaceStyle = .light
}

Views:

// The view and all of its subviews always adopt light style.
youView.overrideUserInterfaceStyle = .light

Window:

/* Everything in the window adopts the style, 
 including the root view controller and all presentation controllers that 
 display content in that window.*/
window.overrideUserInterfaceStyle = .light

Note: Apple strongly encourages to support dark mode in your app. So, you can only disable dark mode temporarily.

Read more here: Choosing a Specific Interface Style for Your iOS App

What is ToString("N0") format?

It is a sort of format specifier for formatting numeric results. There are additional specifiers on the link.

What N does is that it separates numbers into thousand decimal places according to your CultureInfo and represents only 2 decimal digits in floating part as is N2 by rounding right-most digit if necessary.

N0 does not represent any decimal place but rounding is applied to it.

Let's exemplify.

using System;
using System.Globalization;


namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            double x = 567892.98789;
            CultureInfo someCulture = new CultureInfo("da-DK", false);

            // 10 means left-padded = right-alignment
            Console.WriteLine(String.Format(someCulture, "{0:N} denmark", x));
            Console.WriteLine("{0,10:N} us", x); 

            // watch out rounding 567,893
            Console.WriteLine(String.Format(someCulture, "{0,10:N0}", x)); 
            Console.WriteLine("{0,10:N0}", x);

            Console.WriteLine(String.Format(someCulture, "{0,10:N5}", x));
            Console.WriteLine("{0,10:N5}", x);


            Console.ReadKey();

        }
    }
}

It yields,

567.892,99 denmark
567,892.99 us
   567.893
   567,893
567.892,98789
567,892.98789

database attached is read only

You need to change permission for your database folder: properties -> security tab -> edit... -> add... -> username "NT Service\MSSQL$SQLEXPRESS" or "NT Service\MSSQLSERVER". Close the windows, open Advanced..., double click the user and set as follows: Type: Allow Applies to: This folder, subfolder and files Basic permissions: all Make sure the owner is set too.

How can I find out if I have Xcode commandline tools installed?

/usr/bin/xcodebuild -version

will give you the xcode version, run it via Terminal command

How to find whether a ResultSet is empty or not in Java?

if (rs == null || !rs.first()) {
    //empty
} else {
    //not empty
}

Note that after this method call, if the resultset is not empty, it is at the beginning.

How to clear the text of all textBoxes in the form?

private void CleanForm(Control ctrl)
{
    foreach (var c in ctrl.Controls)
    {
        if (c is TextBox)
        {
            ((TextBox)c).Text = String.Empty;
        }

        if( c.Controls.Count > 0)
        {
           CleanForm(c);
        }
    }
}

When you initially call ClearForm, pass in this, or Page (I assume that is what 'this' is).

Parsing a YAML file in Python, and accessing the data?

Since PyYAML's yaml.load() function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:

import yaml
with open('tree.yaml', 'r') as f:
    doc = yaml.load(f)

To access branch1 text you would use:

txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"

because, in your YAML document, the value of the branch1 key is under the treeroot key.

Get only records created today in laravel

$records = User::where('created_at' = CURDATE())->GET()); print($records);

How to convert an array of strings to an array of floats in numpy?

If you have (or create) a single string, you can use np.fromstring:

import numpy as np
x = ["1.1", "2.2", "3.2"]
x = ','.join(x)
x = np.fromstring( x, dtype=np.float, sep=',' )

Note, x = ','.join(x) transforms the x array to string '1.1, 2.2, 3.2'. If you read a line from a txt file, each line will be already a string.

jquery clear input default value

Try that:

  var defaultEmailNews = "Email address";
  $('input[name=email]').focus(function() {
    if($(this).val() == defaultEmailNews) $(this).val("");
  });

  $('input[name=email]').focusout(function() {
    if($(this).val() == "") $(this).val(defaultEmailNews);
  });

Count distinct values

I think this link is pretty good.

Sample output from that link:

mysql> SELECT cate_id,COUNT(DISTINCT(pub_lang)), ROUND(AVG(no_page),2)
    -> FROM book_mast
    -> GROUP BY cate_id;
+---------+---------------------------+-----------------------+
| cate_id | COUNT(DISTINCT(pub_lang)) | ROUND(AVG(no_page),2) |
+---------+---------------------------+-----------------------+
| CA001   |                         2 |                264.33 | 
| CA002   |                         1 |                433.33 | 
| CA003   |                         2 |                256.67 | 
| CA004   |                         3 |                246.67 | 
| CA005   |                         3 |                245.75 | 
+---------+---------------------------+-----------------------+
5 rows in set (0.00 sec)

System.Data.OracleClient requires Oracle client software version 8.1.7

When we first moved over to Vista with Oracle 10g, we experienced this issue when we installed the Oracle client on our Vista boxes, even when we were running with admin privileges during install.

Oracle brought out a new version of the 10g client (10.2.0.3) that was Vista compatible.

I do believe that this was after 11g was released, so it is possible that there is a 'Vista compatible' version for 11g also.

TypeScript: Creating an empty typed container array

I know this is an old question but I recently faced a similar issue which couldn't be solved by this way, as I had to return an empty array of a specific type.

I had

return [];

where [] was Criminal[] type.

Neither return: Criminal[] []; nor return []: Criminal[]; worked for me.

At first glance I solved it by creating a typed variable (as you correctly reported) just before returning it, but (I don't know how JavaScript engines work) it may create overhead and it's less readable.

For thoroughness I'll report this solution in my answer too:

let temp: Criminal[] = [];
return temp;

Eventually I found TypeScript type casting, which allowed me to solve the problem in a more concise and readable (and maybe efficient) way:

return <Criminal[]>[];

Hope this will help future readers!

Returning first x items from array

array_splice — Remove a portion of the array and replace it with something else:

$input = array(1, 2, 3, 4, 5, 6);
array_splice($input, 5); // $input is now array(1, 2, 3, 4, 5)

From PHP manual:

array array_splice ( array &$input , int $offset [, int $length = 0 [, mixed $replacement]])

If length is omitted, removes everything from offset to the end of the array. If length is specified and is positive, then that many elements will be removed. If length is specified and is negative then the end of the removed portion will be that many elements from the end of the array. Tip: to remove everything from offset to the end of the array when replacement is also specified, use count($input) for length .

How to sort an array in descending order in Ruby

It's always enlightening to do a benchmark on the various suggested answers. Here's what I found out:

#!/usr/bin/ruby

require 'benchmark'

ary = []
1000.times { 
  ary << {:bar => rand(1000)} 
}

n = 500
Benchmark.bm(20) do |x|
  x.report("sort")               { n.times { ary.sort{ |a,b| b[:bar] <=> a[:bar] } } }
  x.report("sort reverse")       { n.times { ary.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } }
  x.report("sort_by -a[:bar]")   { n.times { ary.sort_by{ |a| -a[:bar] } } }
  x.report("sort_by a[:bar]*-1") { n.times { ary.sort_by{ |a| a[:bar]*-1 } } }
  x.report("sort_by.reverse!")   { n.times { ary.sort_by{ |a| a[:bar] }.reverse } }
end

                          user     system      total        real
sort                  3.960000   0.010000   3.970000 (  3.990886)
sort reverse          4.040000   0.000000   4.040000 (  4.038849)
sort_by -a[:bar]      0.690000   0.000000   0.690000 (  0.692080)
sort_by a[:bar]*-1    0.700000   0.000000   0.700000 (  0.699735)
sort_by.reverse!      0.650000   0.000000   0.650000 (  0.654447)

I think it's interesting that @Pablo's sort_by{...}.reverse! is fastest. Before running the test I thought it would be slower than "-a[:bar]" but negating the value turns out to take longer than it does to reverse the entire array in one pass. It's not much of a difference, but every little speed-up helps.


Please note that these results are different in Ruby 1.9

Here are results for Ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin10.8.0]:

                           user     system      total        real
sort                   1.340000   0.010000   1.350000 (  1.346331)
sort reverse           1.300000   0.000000   1.300000 (  1.310446)
sort_by -a[:bar]       0.430000   0.000000   0.430000 (  0.429606)
sort_by a[:bar]*-1     0.420000   0.000000   0.420000 (  0.414383)
sort_by.reverse!       0.400000   0.000000   0.400000 (  0.401275)

These are on an old MacBook Pro. Newer, or faster machines, will have lower values, but the relative differences will remain.


Here's a bit updated version on newer hardware and the 2.1.1 version of Ruby:

#!/usr/bin/ruby

require 'benchmark'

puts "Running Ruby #{RUBY_VERSION}"

ary = []
1000.times {
  ary << {:bar => rand(1000)}
}

n = 500

puts "n=#{n}"
Benchmark.bm(20) do |x|
  x.report("sort")               { n.times { ary.dup.sort{ |a,b| b[:bar] <=> a[:bar] } } }
  x.report("sort reverse")       { n.times { ary.dup.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } }
  x.report("sort_by -a[:bar]")   { n.times { ary.dup.sort_by{ |a| -a[:bar] } } }
  x.report("sort_by a[:bar]*-1") { n.times { ary.dup.sort_by{ |a| a[:bar]*-1 } } }
  x.report("sort_by.reverse")    { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse } }
  x.report("sort_by.reverse!")   { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse! } }
end

# >> Running Ruby 2.1.1
# >> n=500
# >>                            user     system      total        real
# >> sort                   0.670000   0.000000   0.670000 (  0.667754)
# >> sort reverse           0.650000   0.000000   0.650000 (  0.655582)
# >> sort_by -a[:bar]       0.260000   0.010000   0.270000 (  0.255919)
# >> sort_by a[:bar]*-1     0.250000   0.000000   0.250000 (  0.258924)
# >> sort_by.reverse        0.250000   0.000000   0.250000 (  0.245179)
# >> sort_by.reverse!       0.240000   0.000000   0.240000 (  0.242340)

New results running the above code using Ruby 2.2.1 on a more recent Macbook Pro. Again, the exact numbers aren't important, it's their relationships:

Running Ruby 2.2.1
n=500
                           user     system      total        real
sort                   0.650000   0.000000   0.650000 (  0.653191)
sort reverse           0.650000   0.000000   0.650000 (  0.648761)
sort_by -a[:bar]       0.240000   0.010000   0.250000 (  0.245193)
sort_by a[:bar]*-1     0.240000   0.000000   0.240000 (  0.240541)
sort_by.reverse        0.230000   0.000000   0.230000 (  0.228571)
sort_by.reverse!       0.230000   0.000000   0.230000 (  0.230040)

Updated for Ruby 2.7.1 on a Mid-2015 MacBook Pro:

Running Ruby 2.7.1
n=500     
                           user     system      total        real
sort                   0.494707   0.003662   0.498369 (  0.501064)
sort reverse           0.480181   0.005186   0.485367 (  0.487972)
sort_by -a[:bar]       0.121521   0.003781   0.125302 (  0.126557)
sort_by a[:bar]*-1     0.115097   0.003931   0.119028 (  0.122991)
sort_by.reverse        0.110459   0.003414   0.113873 (  0.114443)
sort_by.reverse!       0.108997   0.001631   0.110628 (  0.111532)

...the reverse method doesn't actually return a reversed array - it returns an enumerator that just starts at the end and works backwards.

The source for Array#reverse is:

               static VALUE
rb_ary_reverse_m(VALUE ary)
{
    long len = RARRAY_LEN(ary);
    VALUE dup = rb_ary_new2(len);

    if (len > 0) {
        const VALUE *p1 = RARRAY_CONST_PTR_TRANSIENT(ary);
        VALUE *p2 = (VALUE *)RARRAY_CONST_PTR_TRANSIENT(dup) + len - 1;
        do *p2-- = *p1++; while (--len > 0);
    }
    ARY_SET_LEN(dup, RARRAY_LEN(ary));
    return dup;
}

do *p2-- = *p1++; while (--len > 0); is copying the pointers to the elements in reverse order if I remember my C correctly, so the array is reversed.

Send JavaScript variable to PHP variable

It depends on the way your page behaves. If you want this to happens asynchronously, you have to use AJAX. Try out "jQuery post()" on Google to find some tuts.

In other case, if this will happen when a user submits a form, you can send the variable in an hidden field or append ?variableName=someValue" to then end of the URL you are opening. :

http://www.somesite.com/send.php?variableName=someValue

or

http://www.somesite.com/send.php?variableName=someValue&anotherVariable=anotherValue

This way, from PHP you can access this value as:

$phpVariableName = $_POST["variableName"];

for forms using POST method or:

$phpVariableName = $_GET["variableName"];

for forms using GET method or the append to url method I've mentioned above (querystring).

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

What are Unwind segues for and how do you use them?

As far as how to use unwind segues in StoryBoard...

Step 1)

Go to the code for the view controller that you wish to unwind to and add this:

Objective-C

- (IBAction)unwindToViewControllerNameHere:(UIStoryboardSegue *)segue {
    //nothing goes here
}

Be sure to also declare this method in your .h file in Obj-C

Swift

@IBAction func unwindToViewControllerNameHere(segue: UIStoryboardSegue) {
    //nothing goes here
}

Step 2)

In storyboard, go to the view that you want to unwind from and simply drag a segue from your button or whatever up to the little orange "EXIT" icon at the top right of your source view.

enter image description here

There should now be an option to connect to "- unwindToViewControllerNameHere"

That's it, your segue will unwind when your button is tapped.

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

Dictionaries are specifically designed to do super fast key lookups. They are implemented as hashtables and the more entries the faster they are relative to other methods. Using the exception engine is only supposed to be done when your method has failed to do what you designed it to do because it is a large set of object that give you a lot of functionality for handling errors. I built an entire library class once with everything surrounded by try catch blocks once and was appalled to see the debug output which contained a seperate line for every single one of over 600 exceptions!

How to hide Bootstrap previous modal when you opening new one?

You hide Bootstrap modals with:

$('#modal').modal('hide');

Saying $().hide() makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.

How do I get the name of the rows from the index of a data frame?

If you want to pull out only the index values for certain integer-based row-indices, you can do something like the following using the iloc method:

In [28]: temp
Out[28]:
       index                 time  complete
row_0      2  2014-10-22 01:00:00         0
row_1      3  2014-10-23 14:00:00         0
row_2      4  2014-10-26 08:00:00         0
row_3      5  2014-10-26 10:00:00         0
row_4      6  2014-10-26 11:00:00         0

In [29]: temp.iloc[[0,1,4]].index
Out[29]: Index([u'row_0', u'row_1', u'row_4'], dtype='object')

In [30]: temp.iloc[[0,1,4]].index.tolist()
Out[30]: ['row_0', 'row_1', 'row_4']

how to get value of selected item in autocomplete

I wanted something pretty close to this - the moment a user picks an item, even by just hitting the arrow keys to one (focus), I want that data item attached to the tag in question. When they type again without picking another item, I want that data cleared.

(function() {
    var lastText = '';

    $('#MyTextBox'), {
        source: MyData
    })
    .on('autocompleteselect autocompletefocus', function(ev, ui) {
        lastText = ui.item.label;
        jqTag.data('autocomplete-item', ui.item);
    })
    .keyup(function(ev) {
        if (lastText != jqTag.val()) {
            // Clear when they stop typing
            jqTag.data('autocomplete-item', null);

            // Pass the event on as autocompleteclear so callers can listen for select/clear
            var clearEv = $.extend({}, ev, { type: 'autocompleteclear' });
            return jqTag.trigger(clearEv);
    });
})();

With this in place, 'autocompleteselect' and 'autocompletefocus' still fire right when you expect, but the full data item that was selected is always available right on the tag as a result. 'autocompleteclear' now fires when that selection is cleared, generally by typing something else.

ArrayList of String Arrays

You can't force the String arrays to have a specific size. You can do this:

private List<String[]> addresses = new ArrayList<String[]>();

but an array of any size can be added to this list.

However, as others have mentioned, the correct thing to do here is to create a separate class representing addresses. Then you would have something like:

private List<Address> addresses = new ArrayList<Address>();

SQL Server: Is it possible to insert into two tables at the same time?

You still need two INSERT statements, but it sounds like you want to get the IDENTITY from the first insert and use it in the second, in which case, you might want to look into OUTPUT or OUTPUT INTO: http://msdn.microsoft.com/en-us/library/ms177564.aspx

Sum up a column from a specific row down

=Sum(C:C)-Sum(C1:C5)

Sum everything then remove the sum of the values in the cells you don't want, no Volatile Offset's, Indirect's, or Array's needed.

Just for fun if you don't like that method you could also use:

=SUM($C$6:INDEX($C:$C,MATCH(9.99999999999999E+307,$C:$C))

The above formula will Sum only from C6 through the last cell in C:C where a match of a number is found. This is also non-volatile, but I believe more costly and sloppy. Just added it in case you'd prefer this anyways.

If you would like to do function like CountA for text using the last text value in a column you could use.

=COUNTIF(C6:INDEX($C:$C,MATCH(REPT("Z",255),$C:$C)),"T")

you could also use other combinations like:

=Sum($C$6:$C$65536) 

or

=CountIF($C$6:$C$65536,"T") 

The above would do what you ask in Excel 2003 and lower

=Sum($C$6:$C$1048576) 

or

=CountIF($C$6:$C$1048576,"T")

Would both work for Excel 2007+

All above functions would simply ignore all the blank values under the last value.

client denied by server configuration

I have servers with proper lists of hosts and IPs. None of that allow all stuff. My fix was to put the hostname of my new workstation into the list. So the advise is:

Make sure the computer you're using is ACTUALLY on the list of allowed IPs. Look at IPs from logmessages, resolve names, check ifconfig / ipconfig etc.

*Google sent me due to the error-message.

How to convert UTC timestamp to device local time in android

This may help some one with same requirement

private String getDate(long time){
        SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
        String dateString = formatter.format(new Date(time));
        String date = ""+dateString;
        return date;
    }

How do I determine whether an array contains a particular value in Java?

One possible solution:

import java.util.Arrays;
import java.util.List;

public class ArrayContainsElement {
  public static final List<String> VALUES = Arrays.asList("AB", "BC", "CD", "AE");

  public static void main(String args[]) {

      if (VALUES.contains("AB")) {
          System.out.println("Contains");
      } else {
          System.out.println("Not contains");
      }
  }
}

ArrayList - How to modify a member of an object?

Try this.This works while traversing the code and modifying the fields at once of all the elements of Arraylist.

public Employee(String name,String email){
this.name=name;
this.email=email;
}

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

public String getName() {
return name;
}

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

public String getEmail() {
return email;
}

for(int i=0;i++){
List.get(i).setName("Anonymous");
List.get(i).setEmail("[email protected]");
}

JavaScript equivalent of PHP's in_array()

I found a great jQuery solution here on SO.

var success = $.grep(array_a, function(v,i) {
    return $.inArray(v, array_b) !== -1;
}).length === array_a.length;

I wish someone would post an example of how to do this in underscore.

Get checkbox list values with jQuery

Since nobody has mentioned this..

If all you want is an array of values, an easier alternative would be to use the .map() method. Just remember to call .get() to convert the jQuery object to an array:

Example Here

var names = $('.parent input:checked').map(function () {
    return this.name;
}).get();

console.log(names);

_x000D_
_x000D_
var names = $('.parent input:checked').map(function () {_x000D_
    return this.name;_x000D_
}).get();_x000D_
_x000D_
console.log(names);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="parent">_x000D_
    <input type="checkbox" name="name1" />_x000D_
    <input type="checkbox" name="name2" />_x000D_
    <input type="checkbox" name="name3" checked="checked" />_x000D_
    <input type="checkbox" name="name4" checked="checked" />_x000D_
    <input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Pure JavaScript:

Example Here

var elements = document.querySelectorAll('.parent input:checked');
var names = Array.prototype.map.call(elements, function(el, i) {
    return el.name;
});

console.log(names);

_x000D_
_x000D_
var elements = document.querySelectorAll('.parent input:checked');_x000D_
var names = Array.prototype.map.call(elements, function(el, i){_x000D_
    return el.name;_x000D_
});_x000D_
_x000D_
console.log(names);
_x000D_
<div class="parent">_x000D_
    <input type="checkbox" name="name1" />_x000D_
    <input type="checkbox" name="name2" />_x000D_
    <input type="checkbox" name="name3" checked="checked" />_x000D_
    <input type="checkbox" name="name4" checked="checked" />_x000D_
    <input type="checkbox" name="name5" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

HTTP Error 403.14 - Forbidden - The Web server is configured to not list the contents of this directory

Go to cmd and type this:

for x64 O.S: %windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -ir

for x32 O.S: %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

This will install the right version and IIS will understand the MVC directory browsing

Convert a double to a QString

Use QString's number method (docs are here):

double valueAsDouble = 1.2;
QString valueAsString = QString::number(valueAsDouble);

Change Toolbar color in Appcompat 21

UPDATE 12/11/2019: Material Components Library

With the Material Components and Androidx libraries you can use:

  • the android:background attribute in the layout:

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
    
  • apply the default style: style="@style/Widget.MaterialComponents.Toolbar.Primary" or customize the style inheriting from it:

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
    
  • override the default color using the android:theme attribute:

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/MyThemeOverlay_Toolbar"
    

with:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <item name="android:textColorPrimary">....</item>
    <item name="colorPrimary">@color/.....
    <item name="colorOnPrimary">@color/....</item>
  </style>

OLD: Support libraries:
You can use a app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" theme as suggested in other answers, but you can also use a solution like this:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    style="@style/HeaderBar"
    app:theme="@style/ActionBarThemeOverlay"
    app:popupTheme="@style/ActionBarPopupThemeOverlay"/>

And you can have the full control of your ui elements with these styles:

<style name="ActionBarThemeOverlay" parent="">
    <item name="android:textColorPrimary">#fff</item>
    <item name="colorControlNormal">#fff</item>
    <item name="colorControlHighlight">#3fff</item>
</style>

<style name="HeaderBar">
    <item name="android:background">?colorPrimary</item>
</style>

<style name="ActionBarPopupThemeOverlay" parent="ThemeOverlay.AppCompat.Light" >
    <item name="android:background">@android:color/white</item>
    <item name="android:textColor">#000</item>
</style>

Open a workbook using FileDialog and manipulate it in Excel VBA

Unless I misunderstand your question, you can just open a file read only. Here is a simply example, without any checks.

To get the file path from the user use this function:

Private Function get_user_specified_filepath() As String
    'or use the other code example here.
    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogFilePicker)
    fd.AllowMultiSelect = False
    fd.Title = "Please select the file."
    get_user_specified_filepath = fd.SelectedItems(1)
End Function

Then just open the file read only and assign it to a variable:

dim wb as workbook
set wb = Workbooks.Open(get_user_specified_filepath(), ReadOnly:=True)

How to retrieve checkboxes values in jQuery

Anyway, you probably need something like this:

 var val = $('#c_b :checkbox').is(':checked').val();
 $('#t').val( val );

This will get the value of the first checked checkbox on the page and insert that in the textarea with id='textarea'.

Note that in your example code you should put the checkboxes in a form.

Regular expression for matching HH:MM time format

A slight modification to Manish M Demblani's contribution above handles 4am (I got rid of the seconds section as I don't need it in my application)

^(([0-1]{0,1}[0-9]( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[1-9]|1[0-2])(:|\.)[0-5][0-9]( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]))$

handles: 4am 4 am 4:00 4:00am 4:00 pm 4.30 am etc..

How to embed a PDF?

<iframe src="http://docs.google.com/gview?url=http://domain.com/pdf.pdf&embedded=true" 
style="width:600px; height:500px;" frameborder="0"></iframe>

Google docs allows you to embed PDFs, Microsoft Office Docs, and other applications by just linking to their services with an iframe. Its user-friendly, versatile, and attractive.

pythonw.exe or python.exe?

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

Where is the Docker daemon log?

Add ways to find docker daemon log in windows:

try

When using docker machine on Windows and Mac OSX, the daemon runs inside a virtual machine.

First, find your active Docker machine.

docker-machine ls Find the name of the active docker machine under the NAME column in the output.

You can copy the docker daemon log file to your local directory for analysis:

docker-machine scp default:/var/log/docker.log ./ Where default is the name of active your docker machine.

How do I delete NuGet packages that are not referenced by any project in my solution?

I've found a workaround for this.

  1. Enable package restore and automatic checking (Options / Package Manager / General)
  2. Delete entire contents of the packages folder (to Recycle Bin if you're nervous!)
  3. Manage Nuget Packages For Solution
  4. Click the restore button.

NuGet will restore only the packages used in your solution. You end up with a nice, streamlined set of packages.

Run bash script from Windows PowerShell

If you add the extension .SH to the environment variable PATHEXT, you will be able to run shell scripts from PowerShell by only using the script name with arguments:

PS> .\script.sh args

If you store your scripts in a directory that is included in your PATH environment variable, you can run it from anywhere, and omit the extension and path:

PS> script args

Note: sh.exe or another *nix shell must be associated with the .sh extension.

Trying to check if username already exists in MySQL database using PHP

PHP 7 improved query.........

$sql = mysqli_query($conn, "SELECT * from users WHERE user_uid = '$uid'"); if (mysqli_num_rows($sql) > 0) { echo 'Username taken.'; }

Determine if Python is running inside virtualenv

This is an improvement of the accepted answer by Carl Meyer. It works with virtualenv for Python 3 and 2 and also for the venv module in Python 3:

import sys


def is_venv():
    return (hasattr(sys, 'real_prefix') or
            (hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix))

The check for sys.real_prefix covers virtualenv, the equality of non-empty sys.base_prefix with sys.prefix covers venv.

Consider a script that uses the function like this:

if is_venv():
    print('inside virtualenv or venv')
else:
    print('outside virtualenv or venv')

And the following invocation:

$ python2 test.py 
outside virtualenv or venv

$ python3 test.py 
outside virtualenv or venv

$ python2 -m virtualenv virtualenv2
...
$ . virtualenv2/bin/activate
(virtualenv2) $ python test.py 
inside virtualenv or venv
(virtualenv2) $ deactivate

$ python3 -m virtualenv virtualenv3
...
$ . virtualenv3/bin/activate
(virtualenv3) $ python test.py 
inside virtualenv or venv
(virtualenv3) $ deactivate 

$ python3 -m venv venv3
$ . venv3/bin/activate
(venv3) $ python test.py 
inside virtualenv or venv
(venv3) $ deactivate 

Mockito: Mock private field initialization

Pretty late to the party, but I was struck here and got help from a friend. The thing was not to use PowerMock. This works with the latest version of Mockito.

Mockito comes with this org.mockito.internal.util.reflection.FieldSetter.

What it basically does is helps you modify private fields using reflection.

This is how you use it:

@Mock
private Person mockedPerson;
private Test underTest;

// ...

@Test
public void testMethod() {
    FieldSetter.setField(underTest, underTest.getClass().getDeclaredField("person"), mockedPerson);
    // ...
    verify(mockedPerson).someMethod();
}

This way you can pass a mock object and then verify it later.

Here is the reference.

Programmatically scroll a UIScrollView

scrollView.setContentOffset(CGPoint(x: y, y: x), animated: true)

How does Python return multiple values from a function?

Here It is actually returning tuple.

If you execute this code in Python 3:

def get():
    a = 3
    b = 5
    return a,b
number = get()
print(type(number))
print(number)

Output :

<class 'tuple'>
(3, 5)

But if you change the code line return [a,b] instead of return a,b and execute :

def get():
    a = 3
    b = 5
    return [a,b]
number = get()
print(type(number))
print(number)

Output :

<class 'list'>
[3, 5]

It is only returning single object which contains multiple values.

There is another alternative to return statement for returning multiple values, use yield( to check in details see this What does the "yield" keyword do in Python?)

Sample Example :

def get():
    for i in range(5):
        yield i
number = get()
print(type(number))
print(number)
for i in number:
    print(i)

Output :

<class 'generator'>
<generator object get at 0x7fbe5a1698b8>
0
1
2
3
4

What does `return` keyword mean inside `forEach` function?

From the Mozilla Developer Network:

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Early termination may be accomplished with:

The other Array methods: every(), some(), find(), and findIndex() test the array elements with a predicate returning a truthy value to determine if further iteration is required.

Running JAR file on Windows 10

How do I run an executable JAR file? If you have a jar file called Example.jar, follow these rules:

Open a notepad.exe.
Write : java -jar Example.jar.
Save it with the extension .bat.
Copy it to the directory which has the .jar file.
Double click it to run your .jar file.

How to detect pressing Enter on keyboard using jQuery?

$(document).keydown(function (event) {
      //proper indentiation of keycode and which to be equal to 13.
    if ( (event.keyCode || event.which) === 13) {
        // Cancel the default action, if needed
        event.preventDefault();
        //call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
        $("#btnsearch").trigger('click');
    }
});

Java 8 Stream API to find Unique Object matching a property value

Guava API provides MoreCollectors.onlyElement() which is a collector that takes a stream containing exactly one element and returns that element.

The returned collector throws an IllegalArgumentException if the stream consists of two or more elements, and a NoSuchElementException if the stream is empty.

Refer the below code for usage:

import static com.google.common.collect.MoreCollectors.onlyElement;

Person matchingPerson = objects.stream
                        .filter(p -> p.email().equals("testemail"))
                        .collect(onlyElement());

Receiving login prompt using integrated windows authentication

I got the same issue and it was resolved by changing the Application pool identity of the application pool under which the web application is running to NetworkService enter image description here

Get string character by index - Java

CodePointAt instead of charAt is safer to use. charAt may break when there are emojis in the strtng.

How do I run a command on an already existing Docker container?

Assuming the image is using the default entrypoint /bin/sh -c, running /bin/bash will exit immediately in daemon mode (-d). If you want this container to run an interactive shell, use -it instead of -d. If you want to execute arbitrary commands in a container usually executing another process, you might want to try nsenter or nsinit. Have a look at https://blog.codecentric.de/en/2014/07/enter-docker-container/ for the details.

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

XML Schema minOccurs / maxOccurs default values

The default values for minOccurs and maxOccurs are 1. Thus:

<xsd:element minOccurs="1" name="asdf"/>

cardinality is [1-1] Note: if you specify only minOccurs attribute, it can't be greater than 1, because the default value for maxOccurs is 1.

<xsd:element minOccurs="5" maxOccurs="2" name="asdf"/>

invalid

<xsd:element maxOccurs="2" name="asdf"/>

cardinality is [1-2] Note: if you specify only maxOccurs attribute, it can't be smaller than 1, because the default value for minOccurs is 1.

<xsd:element minOccurs="0" maxOccurs="0"/>

is a valid combination which makes the element prohibited.

For more info see http://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints

SOAP-UI - How to pass xml inside parameter

NOTE: This one is just an alternative for the previous provided .NET framework 3.5 and above

You can send it as raw xml

<test>or like this</test>

If you declare the paramater2 as XElement data type

Passing base64 encoded strings in URL

No, you would need to url-encode it, since base64 strings can contain the "+", "=" and "/" characters which could alter the meaning of your data - look like a sub-folder.

Valid base64 characters are below.

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=

Moving matplotlib legend outside of the axis makes it cutoff by the figure box

Sorry EMS, but I actually just got another response from the matplotlib mailling list (Thanks goes out to Benjamin Root).

The code I am looking for is adjusting the savefig call to:

fig.savefig('samplefigure', bbox_extra_artists=(lgd,), bbox_inches='tight')
#Note that the bbox_extra_artists must be an iterable

This is apparently similar to calling tight_layout, but instead you allow savefig to consider extra artists in the calculation. This did in fact resize the figure box as desired.

import matplotlib.pyplot as plt
import numpy as np

plt.gcf().clear()
x = np.arange(-2*np.pi, 2*np.pi, 0.1)
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot(x, np.sin(x), label='Sine')
ax.plot(x, np.cos(x), label='Cosine')
ax.plot(x, np.arctan(x), label='Inverse tan')
handles, labels = ax.get_legend_handles_labels()
lgd = ax.legend(handles, labels, loc='upper center', bbox_to_anchor=(0.5,-0.1))
text = ax.text(-0.2,1.05, "Aribitrary text", transform=ax.transAxes)
ax.set_title("Trigonometry")
ax.grid('on')
fig.savefig('samplefigure', bbox_extra_artists=(lgd,text), bbox_inches='tight')

This produces:

[edit] The intent of this question was to completely avoid the use of arbitrary coordinate placements of arbitrary text as was the traditional solution to these problems. Despite this, numerous edits recently have insisted on putting these in, often in ways that led to the code raising an error. I have now fixed the issues and tidied the arbitrary text to show how these are also considered within the bbox_extra_artists algorithm.

How can I capitalize the first letter of each word in a string?

I really like this answer:

Copy-paste-ready version of @jibberia anwser:

def capitalize(line):
    return ' '.join([s[0].upper() + s[1:] for s in line.split(' ')])

But some of the lines that I was sending split off some blank '' characters that caused errors when trying to do s[1:]. There is probably a better way to do this, but I had to add in a if len(s)>0, as in

return ' '.join([s[0].upper() + s[1:] for s in line.split(' ') if len(s)>0])

How to add a custom button to the toolbar that calls a JavaScript function?

Also there is a nice way allowing one to add the button without creating plugin.

html:

<textarea id="container">How are you!</textarea>

javascript:

editor = CKEDITOR.replace('container'); // bind editor

editor.addCommand("mySimpleCommand", { // create named command
    exec: function(edt) {
        alert(edt.getData());
    }
});

editor.ui.addButton('SuperButton', { // add new button and bind our command
    label: "Click me",
    command: 'mySimpleCommand',
    toolbar: 'insert',
    icon: 'https://avatars1.githubusercontent.com/u/5500999?v=2&s=16'
});

Check out how it works here: DEMO

How to output MySQL query results in CSV format?

The following bash script works for me. It optionally also gets the schema for the requested tables.

#!/bin/bash
#
# export mysql data to CSV
#https://stackoverflow.com/questions/356578/how-to-output-mysql-query-results-in-csv-format
#

#ansi colors
#http://www.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html
blue='\033[0;34m'
red='\033[0;31m'
green='\033[0;32m' # '\e[1;32m' is too bright for white bg.
endColor='\033[0m'

#
# a colored message 
#   params:
#     1: l_color - the color of the message
#     2: l_msg - the message to display
#
color_msg() {
  local l_color="$1"
  local l_msg="$2"
  echo -e "${l_color}$l_msg${endColor}"
}


#
# error
#
# show the given error message on stderr and exit
#
#   params:
#     1: l_msg - the error message to display
#
error() {
  local l_msg="$1"
  # use ansi red for error
  color_msg $red "Error:" 1>&2
  color_msg $red "\t$l_msg" 1>&2
  usage
}

#
# display usage 
#
usage() {
  echo "usage: $0 [-h|--help]" 1>&2
  echo "               -o  | --output      csvdirectory"    1>&2
  echo "               -d  | --database    database"   1>&2
  echo "               -t  | --tables      tables"     1>&2
  echo "               -p  | --password    password"   1>&2
  echo "               -u  | --user        user"       1>&2
  echo "               -hs | --host        host"       1>&2
  echo "               -gs | --get-schema"             1>&2
  echo "" 1>&2
  echo "     output: output csv directory to export mysql data into" 1>&2
  echo "" 1>&2
  echo "         user: mysql user" 1>&2
  echo "     password: mysql password" 1>&2
  echo "" 1>&2
  echo "     database: target database" 1>&2
  echo "       tables: tables to export" 1>&2
  echo "         host: host of target database" 1>&2
  echo "" 1>&2
  echo "  -h|--help: show help" 1>&2
  exit 1
}

#
# show help 
#
help() {
  echo "$0 Help" 1>&2
  echo "===========" 1>&2
  echo "$0 exports a csv file from a mysql database optionally limiting to a list of tables" 1>&2
  echo "   example: $0 --database=cms --user=scott --password=tiger  --tables=person --output person.csv" 1>&2
  echo "" 1>&2
  usage
}

domysql() {
  mysql --host $host -u$user --password=$password $database
}

getcolumns() {
  local l_table="$1"
  echo "describe $l_table" | domysql | cut -f1 | grep -v "Field" | grep -v "Warning" | paste -sd "," - 2>/dev/null
}

host="localhost"
mysqlfiles="/var/lib/mysql-files/"

# parse command line options
while true; do
  #echo "option $1"
  case "$1" in
    # options without arguments
    -h|--help) usage;;
    -d|--database)     database="$2" ; shift ;;
    -t|--tables)       tables="$2" ; shift ;;
    -o|--output)       csvoutput="$2" ; shift ;;
    -u|--user)         user="$2" ; shift ;;
    -hs|--host)        host="$2" ; shift ;;
    -p|--password)     password="$2" ; shift ;;
    -gs|--get-schema)  option="getschema";; 
    (--) shift; break;;
    (-*) echo "$0: error - unrecognized option $1" 1>&2; usage;;
    (*) break;;
  esac
  shift
done

# checks
if [ "$csvoutput" == "" ]
then
  error "ouput csv directory not set"
fi
if [ "$database" == "" ]
then
  error "mysql database not set"
fi
if [ "$user" == "" ]
then
  error "mysql user not set"
fi
if [ "$password" == "" ]
then
  error "mysql password not set"
fi

color_msg $blue "exporting tables of database $database"
if [ "$tables" = "" ]
then
tables=$(echo "show tables" | domysql)
fi

case $option in
  getschema) 
   rm $csvoutput$database.schema
   for table in $tables
   do
     color_msg $blue "getting schema for $table"
     echo -n "$table:" >> $csvoutput$database.schema
     getcolumns $table >> $csvoutput$database.schema
   done  
   ;;
  *)
for table in $tables
do
  color_msg $blue "exporting table $table"
  cols=$(grep "$table:" $csvoutput$database.schema | cut -f2 -d:)
  if [  "$cols" = "" ]
  then
    cols=$(getcolumns $table)
  fi
  ssh $host rm $mysqlfiles/$table.csv
cat <<EOF | mysql --host $host -u$user --password=$password $database 
SELECT $cols FROM $table INTO OUTFILE '$mysqlfiles$table.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n';
EOF
  scp $host:$mysqlfiles/$table.csv $csvoutput$table.csv.raw
  (echo "$cols"; cat $csvoutput$table.csv.raw) > $csvoutput$table.csv
  rm $csvoutput$table.csv.raw
done
  ;;
esac

Java String to SHA1

SHA-1 (and all other hashing algorithms) return binary data. That means that (in Java) they produce a byte[]. That byte array does not represent any specific characters, which means you can't simply turn it into a String like you did.

If you need a String, then you have to format that byte[] in a way that can be represented as a String (otherwise, just keep the byte[] around).

Two common ways of representing arbitrary byte[] as printable characters are BASE64 or simple hex-Strings (i.e. representing each byte by two hexadecimal digits). It looks like you're trying to produce a hex-String.

There's also another pitfall: if you want to get the SHA-1 of a Java String, then you need to convert that String to a byte[] first (as the input of SHA-1 is a byte[] as well). If you simply use myString.getBytes() as you showed, then it will use the platform default encoding and as such will be dependent on the environment you run it in (for example it could return different data based on the language/locale setting of your OS).

A better solution is to specify the encoding to use for the String-to-byte[] conversion like this: myString.getBytes("UTF-8"). Choosing UTF-8 (or another encoding that can represent every Unicode character) is the safest choice here.

Cannot create SSPI context

In case you are running a code not written in your computer, that runs in a computer used by your work peer, but not in yours, check the web.config. Maybe there is your colleague's name as userPrincipalName at some place that should be in blank. That happens automatically when we create a service reference to the project in VS.

C# - using List<T>.Find() with custom objects

http://msdn.microsoft.com/en-us/library/x0b5b5bc.aspx

        // Find a book by its ID.
        Book result = Books.Find(
        delegate(Book bk)
        {
            return bk.ID == IDtoFind;
        }
        );
        if (result != null)
        {
            DisplayResult(result, "Find by ID: " + IDtoFind);   
        }
        else
        {
            Console.WriteLine("\nNot found: {0}", IDtoFind);
        }

PHP code to convert a MySQL query to CSV

SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;

(the documentation for this is here: http://dev.mysql.com/doc/refman/5.0/en/select.html)

or:

$select = "SELECT * FROM table_name";

$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );

$fields = mysql_num_fields ( $export );

for ( $i = 0; $i < $fields; $i++ )
{
    $header .= mysql_field_name( $export , $i ) . "\t";
}

while( $row = mysql_fetch_row( $export ) )
{
    $line = '';
    foreach( $row as $value )
    {                                            
        if ( ( !isset( $value ) ) || ( $value == "" ) )
        {
            $value = "\t";
        }
        else
        {
            $value = str_replace( '"' , '""' , $value );
            $value = '"' . $value . '"' . "\t";
        }
        $line .= $value;
    }
    $data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );

if ( $data == "" )
{
    $data = "\n(0) Records Found!\n";                        
}

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";

Checking for a null int value from a Java ResultSet

The default for ResultSet.getInt when the field value is NULL is to return 0, which is also the default value for your iVal declaration. In which case your test is completely redundant.

If you actually want to do something different if the field value is NULL, I suggest:

int iVal = 0;
ResultSet rs = magicallyAppearingStmt.executeQuery(query);
if (rs.next()) {
    iVal = rs.getInt("ID_PARENT");
    if (rs.wasNull()) {
        // handle NULL field value
    }
}

(Edited as @martin comments below; the OP code as written would not compile because iVal is not initialised)

SELECT only rows that contain only alphanumeric characters in MySQL

Your statement matches any string that contains a letter or digit anywhere, even if it contains other non-alphanumeric characters. Try this:

SELECT * FROM table WHERE column REGEXP '^[A-Za-z0-9]+$';

^ and $ require the entire string to match rather than just any portion of it, and + looks for 1 or more alphanumberic characters.

You could also use a named character class if you prefer:

SELECT * FROM table WHERE column REGEXP '^[[:alnum:]]+$';

How to make PyCharm always show line numbers

For version 4.0, 4.5 on Windows

File -> Settings

Then,

Editor -> General -> Appearance -> Show line numbers

For version 4.0 on Mac OSX

PyCharm-->Preferences

Then,

Editor-->General-->Appearance-->checkbox: "Show line numbers"

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I've experienced the same problem. The thing is that I forgot to start the apache and mysql in xampp... :S

How to rename a pane in tmux?

yes you can rename pane names, and not only window names starting with tmux >= 2.3. Just type the following in your shell:

printf '\033]2;%s\033\\' 'title goes here'

you might need to add the following to your .tmux.conf to display pane names:

# Enable names for panes
set -g pane-border-status top

you can also automatically assign a name:

set -g pane-border-format "#P: #{pane_current_command}"

Write to custom log file from a Bash script

If you see the man page of logger:

$ man logger

LOGGER(1) BSD General Commands Manual LOGGER(1)

NAME logger — a shell command interface to the syslog(3) system log module

SYNOPSIS logger [-isd] [-f file] [-p pri] [-t tag] [-u socket] [message ...]

DESCRIPTION Logger makes entries in the system log. It provides a shell command interface to the syslog(3) system log module.

It Clearly says that it will log to system log. If you want to log to file, you can use ">>" to redirect to log file.

How to search in an array with preg_match?

$items = array();
foreach ($haystacks as $haystack) {
    if (preg_match($pattern, $haystack, $matches)
        $items[] = $matches[1];
}

Add floating point value to android resources/values

As described in this link http://droidista.blogspot.in/2012/04/adding-float-value-to-your-resources.html

Declare in dimen.xml

<item name="my_float_value" type="dimen" format="float">9.52</item>

Referencing from xml

@dimen/my_float_value

Referencing from java

TypedValue typedValue = new TypedValue();
getResources().getValue(R.dimen.my_float_value, typedValue, true);
float myFloatValue = typedValue.getFloat();

Query to get all rows from previous month

Here is the query to get the records of the last month:

SELECT *
FROM `tablename`
WHERE `datefiled`
BETWEEN DATE_SUB( DATE( NOW( ) ) , INTERVAL 1
MONTH )
AND 
LAST_DAY( DATE_SUB( DATE( NOW( ) ) , INTERVAL 1
MONTH ) )

Regards - saqib

Matching an empty input box using CSS

If you're happy not not supporting IE or pre-Chromium Edge (which might be fine if you are using this for progressive enhancement), you can use :placeholder-shown as Berend has said. Note that for Chrome and Safari you actually need a non-empty placeholder for this to work, though a space works.

_x000D_
_x000D_
*,_x000D_
 ::after,_x000D_
 ::before {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
label.floating-label {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  height: 2.2em;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
label.floating-label input {_x000D_
  font-size: 1em;_x000D_
  height: 2.2em;_x000D_
  padding-top: 0.7em;_x000D_
  line-height: 1.5;_x000D_
  color: #495057;_x000D_
  background-color: #fff;_x000D_
  background-clip: padding-box;_x000D_
  border: 1px solid #ced4da;_x000D_
  border-radius: 0.25rem;_x000D_
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;_x000D_
}_x000D_
_x000D_
label.floating-label input:focus {_x000D_
  color: #495057;_x000D_
  background-color: #fff;_x000D_
  border-color: #80bdff;_x000D_
  outline: 0;_x000D_
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);_x000D_
}_x000D_
_x000D_
label.floating-label input+span {_x000D_
  position: absolute;_x000D_
  top: 0em;_x000D_
  left: 0;_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  font-size: 0.66em;_x000D_
  line-height: 1.5;_x000D_
  color: #495057;_x000D_
  border: 1px solid transparent;_x000D_
  border-radius: 0.25rem;_x000D_
  transition: font-size 0.1s ease-in-out, top 0.1s ease-in-out;_x000D_
}_x000D_
_x000D_
label.floating-label input:placeholder-shown {_x000D_
  padding-top: 0;_x000D_
  font-size: 1em;_x000D_
}_x000D_
_x000D_
label.floating-label input:placeholder-shown+span {_x000D_
  top: 0.3em;_x000D_
  font-size: 1em;_x000D_
}
_x000D_
<fieldset>_x000D_
  <legend>_x000D_
    Floating labels example (no-JS)_x000D_
  </legend>_x000D_
  <label class="floating-label">_x000D_
    <input type="text" placeholder=" ">_x000D_
    <span>Username</span>_x000D_
  </label>_x000D_
  <label class="floating-label">_x000D_
    <input type="Password" placeholder=" ">_x000D_
    <span>Password</span>_x000D_
  </label>_x000D_
</fieldset>_x000D_
<p>_x000D_
  Inspired by Bootstrap's <a href="https://getbootstrap.com/docs/4.0/examples/floating-labels/">floating labels</a>._x000D_
</p>
_x000D_
_x000D_
_x000D_

Setting up and using Meld as your git difftool and mergetool

This is an answer targeting primarily developers using Windows, as the path syntax of the diff tool differs from other platforms.

I use Kdiff3 as the git mergetool, but to set up the git difftool as Meld, I first installed the latest version of Meld from Meldmerge.org then added the following to my global .gitconfig using:

git config --global -e

Note, if you rather want Sublime Text 3 instead of the default Vim as core ditor, you can add this to the .gitconfig file:

[core]
editor = 'c:/Program Files/Sublime Text 3/sublime_text.exe'

Then you add inn Meld as the difftool

[diff]
tool = meld
guitool = meld 

[difftool "meld"]
cmd = \"C:/Program Files (x86)/Meld/Meld.exe\" \"$LOCAL\" \"$REMOTE\" --label \"DIFF 
(ORIGINAL MY)\"
prompt = false
path = C:\\Program Files (x86)\\Meld\\Meld.exe

Note the leading slash in the cmd above, on Windows it is necessary.

It is also possible to set up an alias to show the current git diff with a --dir-diff option. This will list the changed files inside Meld, which is handy when you have altered multiple files (a very common scenario indeed).

The alias looks like this inside the .gitconfig file, beneath [alias] section:

showchanges = difftool --dir-diff

To show the changes I have made to the code I then just enter the following command:

git showchanges

The following image shows how this --dir-diff option can show a listing of changed files (example): Meld showing list of files with changes between the $LOCAL and $REMOTE

Then it is possible to click on each file and show the changes inside Meld.

Can anyone explain IEnumerable and IEnumerator to me?

IEnumerable is a box that contains Ienumerator. IEnumerable is base interface for all the collections. foreach loop can operate if the collection implements IEnumerable. In the below code it explains the step of having our own Enumerator. Lets first define our Class of which we are going to make the collection.

public class Customer
{
    public String Name { get; set; }
    public String City { get; set; }
    public long Mobile { get; set; }
    public double Amount { get; set; }
}

Now we will define the Class which will act as a collection for our class Customer. Notice that it is implementing the interface IEnumerable. So that we have to implement the method GetEnumerator. This will return our custom Enumerator.

public class CustomerList : IEnumerable
{
    Customer[] customers = new Customer[4];
    public CustomerList()
    {
        customers[0] = new Customer { Name = "Bijay Thapa", City = "LA", Mobile = 9841639665, Amount = 89.45 };
        customers[1] = new Customer { Name = "Jack", City = "NYC", Mobile = 9175869002, Amount = 426.00 };
        customers[2] = new Customer { Name = "Anil min", City = "Kathmandu", Mobile = 9173694005, Amount = 5896.20 };
        customers[3] = new Customer { Name = "Jim sin", City = "Delhi", Mobile = 64214556002, Amount = 596.20 };
    }

    public int Count()
    {
        return customers.Count();
    }
    public Customer this[int index]
    {
        get
        {
            return customers[index];
        }
    }
    public IEnumerator GetEnumerator()
    {
        return customers.GetEnumerator(); // we can do this but we are going to make our own Enumerator
        return new CustomerEnumerator(this);
    }
}

Now we are going to create our own custom Enumerator as follow. So, we have to implement method MoveNext.

 public class CustomerEnumerator : IEnumerator
    {
        CustomerList coll;
        Customer CurrentCustomer;
        int currentIndex;
        public CustomerEnumerator(CustomerList customerList)
        {
            coll = customerList;
            currentIndex = -1;
        }

        public object Current => CurrentCustomer;

        public bool MoveNext()
        {
            if ((currentIndex++) >= coll.Count() - 1)
                return false;
            else
                CurrentCustomer = coll[currentIndex];
            return true;
        }

        public void Reset()
        {
            // we dont have to implement this method.
        }
    }

Now we can use foreach loop over our collection like below;

    class EnumeratorExample
    {
        static void Main(String[] args)
        {

            CustomerList custList = new CustomerList();
            foreach (Customer cust in custList)
            {
                Console.WriteLine("Customer Name:"+cust.Name + " City Name:" + cust.City + " Mobile Number:" + cust.Amount);
            }
            Console.Read();

        }
    }

Getting JavaScript object key list

Use Object.keys()... it's the way to go.

Full documentation is available on the MDN site linked below:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

How to remove all .svn directories from my application directories

Try this:

find . -name .svn -exec rm -rf '{}' \;

Before running a command like that, I often like to run this first:

find . -name .svn -exec ls '{}' \;

Design DFA accepting binary strings divisible by a number 'n'

I know I am quite late, but I just wanted to add a few things to the already correct answer provided by @Grijesh. I'd like to just point out that the answer provided by @Grijesh does not produce the minimal DFA. While the answer surely is the right way to get a DFA, if you need the minimal DFA you will have to look into your divisor.

Like for example in binary numbers, if the divisor is a power of 2 (i.e. 2^n) then the minimum number of states required will be n+1. How would you design such an automaton? Just see the properties of binary numbers. For a number, say 8 (which is 2^3), all its multiples will have the last 3 bits as 0. For example, 40 in binary is 101000. Therefore for a language to accept any number divisible by 8 we just need an automaton which sees if the last 3 bits are 0, which we can do in just 4 states instead of 8 states. That's half the complexity of the machine.

In fact, this can be extended to any base. For a ternary base number system, if for example we need to design an automaton for divisibility with 9, we just need to see if the last 2 numbers of the input are 0. Which can again be done in just 3 states.

Although if the divisor isn't so special, then we need to go through with @Grijesh's answer only. Like for example, in a binary system if we take the divisors of 3 or 7 or maybe 21, we will need to have that many number of states only. So for any odd number n in a binary system, we need n states to define the language which accepts all multiples of n. On the other hand, if the number is even but not a power of 2 (only in case of binary numbers) then we need to divide the number by 2 till we get an odd number and then we can find the minimum number of states by adding the odd number produced and the number of times we divided by 2.

For example, if we need to find the minimum number of states of a DFA which accepts all binary numbers divisible by 20, we do :

20/2 = 10 
10/2 = 5

Hence our answer is 5 + 1 + 1 = 7. (The 1 + 1 because we divided the number 20 twice).

How to select a drop-down menu value with Selenium using Python?

Selenium provides a convenient Select class to work with select -> option constructs:

from selenium import webdriver
from selenium.webdriver.support.ui import Select

driver = webdriver.Firefox()
driver.get('url')

select = Select(driver.find_element_by_id('fruits01'))

# select by visible text
select.select_by_visible_text('Banana')

# select by value 
select.select_by_value('1')

See also:

Why is quicksort better than mergesort?

"and yet most people use Quicksort instead of Mergesort. Why is that?"

One psychological reason that has not been given is simply that Quicksort is more cleverly named. ie good marketing.

Yes, Quicksort with triple partioning is probably one of the best general purpose sort algorithms, but theres no getting over the fact that "Quick" sort sounds much more powerful than "Merge" sort.

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

Since ASP.NET MVC 3 RTM is out there is no need for config section for Razor. And these sections can be safely removed.

How to find where gem files are installed

This works and gives you the installed at path for each gem. This super helpful when trying to do multi-stage docker builds.. You can copy in the specific directory post-bundle install.

bash-4.4# gem list -d

Output::

aasm (5.0.6)
    Authors: Thorsten Boettger, Anil Maurya
    Homepage: https://github.com/aasm/aasm
    License: MIT
    Installed at: /usr/local/bundle

  State machine mixin for Ruby objects

Swift 3: Display Image from URL

You could also use Alamofire\AlmofireImage for that task: https://github.com/Alamofire/AlamofireImage

The code should look something like that (Based on the first example on link above):

import AlamofireImage

Alamofire.request("http://i.imgur.com/w5rkSIj.jpg").responseImage { response in
    if let catPicture = response.result.value {
        print("image downloaded: \(image)")
    }
}

While it is neat yet safe, you should consider if that worth the Pod overhead. If you are going to use more images and would like to add also filter and transiations I would consider using AlamofireImage

Element count of an array in C++

There are no cases where, given an array arr, that the value of sizeof(arr) / sizeof(arr[0]) is not the count of elements, by the definition of array and sizeof.

In fact, it's even directly mentioned (§5.3.3/2):

.... When applied to an array, the result is the total number of bytes in the array. This implies that the size of an array of n elements is n times the size of an element.

Emphasis mine. Divide by the size of an element, sizeof(arr[0]), to obtain n.

curl_exec() always returns false

In my case I need to set VERIFYHOST and VERIFYPEER to false, like this:

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

before the call to curl_exec($ch).

Because i am working between two development environments with self-assigned certificates. With valid certificates there is no need to set VERIFYHOST and VERIFYPEER to false because the curl_exec($ch) method will work and return the response you expect.

Which HTML Parser is the best?

The best I've seen so far is HtmlCleaner:

HtmlCleaner is open-source HTML parser written in Java. HTML found on Web is usually dirty, ill-formed and unsuitable for further processing. For any serious consumption of such documents, it is necessary to first clean up the mess and bring the order to tags, attributes and ordinary text. For the given HTML document, HtmlCleaner reorders individual elements and produces well-formed XML. By default, it follows similar rules that the most of web browsers use in order to create Document Object Model. However, user may provide custom tag and rule set for tag filtering and balancing.

With HtmlCleaner you can locate any element using XPath.

For other html parsers see this SO question.

Spring @Transactional - isolation, propagation

Good question, although not a trivial one to answer.

Propagation

Defines how transactions relate to each other. Common options:

  • REQUIRED: Code will always run in a transaction. Creates a new transaction or reuses one if available.
  • REQUIRES_NEW: Code will always run in a new transaction. Suspends the current transaction if one exists.

Isolation

Defines the data contract between transactions.

  • ISOLATION_READ_UNCOMMITTED: Allows dirty reads.
  • ISOLATION_READ_COMMITTED: Does not allow dirty reads.
  • ISOLATION_REPEATABLE_READ: If a row is read twice in the same transaction, the result will always be the same.
  • ISOLATION_SERIALIZABLE: Performs all transactions in a sequence.

The different levels have different performance characteristics in a multi-threaded application. I think if you understand the dirty reads concept you will be able to select a good option.


Example of when a dirty read can occur:

  thread 1   thread 2      
      |         |
    write(x)    |
      |         |
      |        read(x)
      |         |
    rollback    |
      v         v 
           value (x) is now dirty (incorrect)

So a sane default (if such can be claimed) could be ISOLATION_READ_COMMITTED, which only lets you read values which have already been committed by other running transactions, in combination with a propagation level of REQUIRED. Then you can work from there if your application has other needs.


A practical example of where a new transaction will always be created when entering the provideService routine and completed when leaving:

public class FooService {
    private Repository repo1;
    private Repository repo2;

    @Transactional(propagation=Propagation.REQUIRES_NEW)
    public void provideService() {
        repo1.retrieveFoo();
        repo2.retrieveFoo();
    }
}

Had we instead used REQUIRED, the transaction would remain open if the transaction was already open when entering the routine. Note also that the result of a rollback could be different as several executions could take part in the same transaction.


We can easily verify the behaviour with a test and see how results differ with propagation levels:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:/fooService.xml")
public class FooServiceTests {

    private @Autowired TransactionManager transactionManager;
    private @Autowired FooService fooService;

    @Test
    public void testProvideService() {
        TransactionStatus status = transactionManager.getTransaction(new DefaultTransactionDefinition());
        fooService.provideService();
        transactionManager.rollback(status);
        // assert repository values are unchanged ... 
}

With a propagation level of

  • REQUIRES_NEW: we would expect fooService.provideService() was NOT rolled back since it created it's own sub-transaction.

  • REQUIRED: we would expect everything was rolled back and the backing store was unchanged.

matplotlib does not show my drawings although I call pyplot.show()

%matplotlib inline

For me working with notebook, adding the above line before the plot works.

UIViewController viewDidLoad vs. viewWillAppear: What is the proper division of labor?

viewDidLoad is things you have to do once. viewWillAppear gets called every time the view appears. You should do things that you only have to do once in viewDidLoad - like setting your UILabel texts. However, you may want to modify a specific part of the view every time the user gets to view it, e.g. the iPod application scrolls the lyrics back to the top every time you go to the "Now Playing" view.

However, when you are loading things from a server, you also have to think about latency. If you pack all of your network communication into viewDidLoad or viewWillAppear, they will be executed before the user gets to see the view - possibly resulting a short freeze of your app. It may be good idea to first show the user an unpopulated view with an activity indicator of some sort. When you are done with your networking, which may take a second or two (or may even fail - who knows?), you can populate the view with your data. Good examples on how this could be done can be seen in various twitter clients. For example, when you view the author detail page in Twitterrific, the view only says "Loading..." until the network queries have completed.

Find the PID of a process that uses a port on Windows

PowerShell (Core-compatible) one-liner to ease copypaste scenarios:

netstat -aon | Select-String 8080 | ForEach-Object { $_ -replace '\s+', ',' } | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID') | ForEach-Object { $portProcess = Get-Process | Where-Object Id -eq $_.PID; $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; Write-Output $_ } | Sort-Object ProcessName, State, Protocol, AddressLocal, AddressForeign | Select-Object  ProcessName, State, Protocol, AddressLocal, AddressForeign | Format-Table

Output:

ProcessName State     Protocol AddressLocal AddressForeign
----------- -----     -------- ------------ --------------
System      LISTENING TCP      [::]:8080    [::]:0
System      LISTENING TCP      0.0.0.0:8080 0.0.0.0:0

Same code, developer-friendly:

$Port = 8080

# Get PID's listening to $Port, as PSObject
$PidsAtPortString = netstat -aon `
  | Select-String $Port
$PidsAtPort = $PidsAtPortString `
  | ForEach-Object { `
      $_ -replace '\s+', ',' `
  } `
  | ConvertFrom-Csv -Header @('Empty', 'Protocol', 'AddressLocal', 'AddressForeign', 'State', 'PID')

# Enrich port's list with ProcessName data
$ProcessesAtPort = $PidsAtPort `
  | ForEach-Object { `
    $portProcess = Get-Process `
      | Where-Object Id -eq $_.PID; `
    $_ | Add-Member -NotePropertyName 'ProcessName' -NotePropertyValue $portProcess.ProcessName; `
    Write-Output $_;
  }

# Show output
$ProcessesAtPort `
  | Sort-Object    ProcessName, State, Protocol, AddressLocal, AddressForeign `
  | Select-Object  ProcessName, State, Protocol, AddressLocal, AddressForeign `
  | Format-Table

Add Legend to Seaborn point plot

I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.

import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')

In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,

plt.legend(handles=[red_patch, black_patch])

And the legend ought to appear in the pointplot.

Setting action for back button in navigation controller

I don't believe this is possible, easily. The only way I believe to get around this is to make your own back button arrow image to place up there. It was frustrating for me at first but I see why, for consistency's sake, it was left out.

You can get close (without the arrow) by creating a regular button and hiding the default back button:

self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"Servers" style:UIBarButtonItemStyleDone target:nil action:nil] autorelease];
self.navigationItem.hidesBackButton = YES;

Error handling with PHPMailer

We wrote a wrapper class that captures the buffer and converts the printed output to an exception. this lets us upgrade the phpmailer file without having to remember to comment out the echo statements each time we upgrade.

The wrapper class has methods something along the lines of:

public function AddAddress($email, $name = null) {
    ob_start();
    parent::AddAddress($email, $name);
    $error = ob_get_contents();
    ob_end_clean();
    if( !empty($error) ) {
        throw new Exception($error);
    }
}

How to put two divs on the same line with CSS in simple_form in rails?

Your css is fine, but I think it's not applying on divs. Just write simple class name and then try. You can check it at Jsfiddle.

.left {
  float: left;
  width: 125px;
  text-align: right;
  margin: 2px 10px;
  display: inline;
}

.right {
  float: left;
  text-align: left;
  margin: 2px 10px;
  display: inline;
}

How do I specify unique constraint for multiple columns in MySQL?

If you want to avoid duplicates in future. Create another column say id2.

UPDATE tablename SET id2 = id;

Now add the unique on two columns:

alter table tablename add unique index(columnname, id2);

How to set base url for rest in spring boot?

This solution applies if:

  1. You want to prefix RestController but not Controller.
  2. You are not using Spring Data Rest.

    @Configuration
    public class WebConfig extends WebMvcConfigurationSupport {
    
    @Override
    protected RequestMappingHandlerMapping createRequestMappingHandlerMapping() {
        return new ApiAwareRequestMappingHandlerMapping();
    }
    
    private static class ApiAwareRequestMappingHandlerMapping extends RequestMappingHandlerMapping {
    
        private static final String API_PATH_PREFIX = "api";
    
        @Override
        protected void registerHandlerMethod(Object handler, Method method, RequestMappingInfo mapping) {
            Class<?> beanType = method.getDeclaringClass();
            if (AnnotationUtils.findAnnotation(beanType, RestController.class) != null) {
                PatternsRequestCondition apiPattern = new PatternsRequestCondition(API_PATH_PREFIX)
                        .combine(mapping.getPatternsCondition());
    
                mapping = new RequestMappingInfo(mapping.getName(), apiPattern, mapping.getMethodsCondition(),
                        mapping.getParamsCondition(), mapping.getHeadersCondition(), mapping.getConsumesCondition(),
                        mapping.getProducesCondition(), mapping.getCustomCondition());
            }
            super.registerHandlerMethod(handler, method, mapping);
        }
    }
    

    }

This is similar to the solution posted by mh-dev, but I think this is a little cleaner and this should be supported on any version of Spring Boot 1.4.0+, including 2.0.0+.

How to detect a route change in Angular?

For Angular 7 someone should write like:

this.router.events.subscribe((event: Event) => {})


A detailed example can be as follows:

import { Component } from '@angular/core'; 
import { Router, Event, NavigationStart, NavigationEnd, NavigationError } from '@angular/router';

@Component({
    selector: 'app-root',
    template: `<router-outlet></router-outlet>`
})
export class AppComponent {

    constructor(private router: Router) {

        this.router.events.subscribe((event: Event) => {
            if (event instanceof NavigationStart) {
                // Show loading indicator
            }

            if (event instanceof NavigationEnd) {
                // Hide loading indicator
            }

            if (event instanceof NavigationError) {
                // Hide loading indicator

                // Present error to user
                console.log(event.error);
            }
        });

   }
}

Send FormData and String Data Together Through JQuery AJAX?

well, as an easier alternative and shorter, you could do this too!!

var fd = new FormData();

var file_data = object.get(0).files[i];
var other_data = $('form').serialize(); //page_id=&category_id=15&method=upload&required%5Bcategory_id%5D=Category+ID

fd.append("file", file_data);

$.ajax({
    url: 'add.php?'+ other_data,  //<== just add it to the end of url ***
    data: fd,
    contentType: false,
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

This question on StackOverflow deals with RadioButtonListFor and the answer addresses your question too. You can set the selected property in the RadioButtonListViewModel.

Proper way to return JSON using node or Express

Since Express.js 3x the response object has a json() method which sets all the headers correctly for you and returns the response in JSON format.

Example:

res.json({"foo": "bar"});

MySQL: Delete all rows older than 10 minutes

If time_created is a unix timestamp (int), you should be able to use something like this:

DELETE FROM locks WHERE time_created < (UNIX_TIMESTAMP() - 600);

(600 seconds = 10 minutes - obviously)

Otherwise (if time_created is mysql timestamp), you could try this:

DELETE FROM locks WHERE time_created < (NOW() - INTERVAL 10 MINUTE)