Programs & Examples On #Method dispatch

Find element in List<> that contains a value

Using function Find is cleaner way.

MyClass item = MyList.Find(item => item.name == "foo");
if (item != null) // check item isn't null
{
 ....
}

How to return a string value from a Bash function

You can echo a string, but catch it by piping (|) the function to something else.

You can do it with expr, though ShellCheck reports this usage as deprecated.

Creating a SearchView that looks like the material design guidelines

The following will create a SearchView identical to the one in Gmail and add it to the given Toolbar. You'll just have to implement your own "ViewUtil.convertDpToPixel" method.

private SearchView createMaterialSearchView(Toolbar toolbar, String hintText) {

    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setDisplayShowTitleEnabled(false);

    SearchView searchView = new SearchView(this);
    searchView.setIconifiedByDefault(false);
    searchView.setMaxWidth(Integer.MAX_VALUE);
    searchView.setMinimumHeight(Integer.MAX_VALUE);
    searchView.setQueryHint(hintText);

    int rightMarginFrame = 0;
    View frame = searchView.findViewById(getResources().getIdentifier("android:id/search_edit_frame", null, null));
    if (frame != null) {
        LinearLayout.LayoutParams frameParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        rightMarginFrame = ((LinearLayout.LayoutParams) frame.getLayoutParams()).rightMargin;
        frameParams.setMargins(0, 0, 0, 0);
        frame.setLayoutParams(frameParams);
    }

    View plate = searchView.findViewById(getResources().getIdentifier("android:id/search_plate", null, null));
    if (plate != null) {
        plate.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        plate.setPadding(0, 0, rightMarginFrame, 0);
        plate.setBackgroundColor(Color.TRANSPARENT);
    }

    int autoCompleteId = getResources().getIdentifier("android:id/search_src_text", null, null);
    if (searchView.findViewById(autoCompleteId) != null) {
        EditText autoComplete = (EditText) searchView.findViewById(autoCompleteId);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, (int) ViewUtil.convertDpToPixel(36));
        params.weight = 1;
        params.gravity = Gravity.CENTER_VERTICAL;
        params.leftMargin = rightMarginFrame;
        autoComplete.setLayoutParams(params);
        autoComplete.setTextSize(16f);
    }

    int searchMagId = getResources().getIdentifier("android:id/search_mag_icon", null, null);
    if (searchView.findViewById(searchMagId) != null) {
        ImageView v = (ImageView) searchView.findViewById(searchMagId);
        v.setImageDrawable(null);
        v.setPadding(0, 0, 0, 0);
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        params.setMargins(0, 0, 0, 0);
        v.setLayoutParams(params);
    }

    toolbar.setTitle(null);
    toolbar.setContentInsetsAbsolute(0, 0);
    toolbar.addView(searchView);

    return searchView;
}

What is the best way to create a string array in python?

Are you trying to do something like this?

>>> strs = [s.strip('\(\)') for s in ['some\\', '(list)', 'of', 'strings']]
>>> strs 
['some', 'list', 'of', 'strings']

Pass parameters in setInterval function

You can use a library called underscore js. It gives a nice wrapper on the bind method and is a much cleaner syntax as well. Letting you execute the function in the specified scope.

http://underscorejs.org/#bind

_.bind(function, scope, *arguments)

Mockito How to mock only the call of a method of the superclass

Maybe the easiest option if inheritance makes sense is to create a new method (package private??) to call the super (lets call it superFindall), spy the real instance and then mock the superFindAll() method in the way you wanted to mock the parent class one. It's not the perfect solution in terms of coverage and visibility but it should do the job and it's easy to apply.

 public Childservice extends BaseService {
    public void save(){
        //some code
        superSave();
    }

    void superSave(){
        super.save();
    }
}

How do I pass multiple ints into a vector at once?

These days (c++17) it's easy:

auto const pusher([](auto& v) noexcept
  {
    return [&](auto&& ...e)
      {
        (
          (
            v.push_back(std::forward<decltype(e)>(e))
          ),
          ...
        );
      };
  }
);

pusher(TestVector)(2, 5, 8, 11, 14);

Get user info via Google API

I am using Google API for .Net, but no doubt you can find the same way to obtain this information using other version of API. As user872858 mentioned, scope userinfo.profile has been deprecated (google article) .

To obtain user profile info I use following code (re-written part from google's example):

IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
                                  new GoogleAuthorizationCodeFlow.Initializer
                                      {
                                            ClientSecrets = Secrets,
                                            Scopes = new[] { PlusService.Scope.PlusLogin,"https://www.googleapis.com/auth/plus.profile.emails.read"  }
                                       });    
TokenResponse _token = flow.ExchangeCodeForTokenAsync("", code, "postmessage", 
                              CancellationToken.None).Result;

                    // Create an authorization state from the returned token.
                    context.Session["authState"] = _token;

                    // Get tokeninfo for the access token if you want to verify.
                    Oauth2Service service = new Oauth2Service(
                     new Google.Apis.Services.BaseClientService.Initializer());
                    Oauth2Service.TokeninfoRequest request = service.Tokeninfo();
                    request.AccessToken = _token.AccessToken;
                    Tokeninfo info = request.Execute();
                    if (info.VerifiedEmail.HasValue && info.VerifiedEmail.Value)
                    {
                        flow = new GoogleAuthorizationCodeFlow(
                                    new GoogleAuthorizationCodeFlow.Initializer
                                         {
                                             ClientSecrets = Secrets,
                                             Scopes = new[] { PlusService.Scope.PlusLogin }
                                          });

                        UserCredential credential = new UserCredential(flow, 
                                                              "me", _token);
                        _token = credential.Token;
                        _ps = new PlusService(
                              new Google.Apis.Services.BaseClientService.Initializer()
                               {
                                   ApplicationName = "Your app name",
                                   HttpClientInitializer = credential
                               });
                        Person userProfile = _ps.People.Get("me").Execute();
                    }

Than, you can access almost anything using userProfile.

UPDATE: To get this code working you have to use appropriate scopes on google sign in button. For example my button:

     <button class="g-signin"
             data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read"
             data-clientid="646361778467-nb2uipj05c4adlk0vo66k96bv8inqles.apps.googleusercontent.com"
             data-accesstype="offline"
             data-redirecturi="postmessage"
             data-theme="dark"
             data-callback="onSignInCallback"
             data-cookiepolicy="single_host_origin"
             data-width="iconOnly">
     </button>

How to get box-shadow on left & right sides only

You can use 1 div inside that to "erase" the shadow:

.yourdiv{
    position:relative;
    width:400px;
    height:400px;
    left:10px;
    top:40px;
    background-color:white;
    box-shadow: 0px 0px 1px 0.5px #5F5F5F;

}
.erase{
    position:absolute;
    width:100%;
    top:50%;
    height:105%;
    transform:translate(0%,-50%);
    background-color:white;
}

You can play with "height:%;" and "width:%;" to erase what shadow you want.

Set up git to pull and push all branches

The simplest way is to do:

git push --all origin

This will push tags and branches.

Align button at the bottom of div using CSS

CSS3 flexbox can also be used to align button at the bottom of parent element.

Required HTML:

<div class="container">
  <div class="btn-holder">
    <button type="button">Click</button>
  </div>
</div>

Necessary CSS:

.container {
  justify-content: space-between;
  flex-direction: column;
  height: 100vh;
  display: flex;
}
.container .btn-holder {
  justify-content: flex-end;
  display: flex;
}

Screenshot:

Output Image

Useful Resources:

_x000D_
_x000D_
* {box-sizing: border-box;}_x000D_
body {_x000D_
  background: linear-gradient(orange, yellow);_x000D_
  font: 14px/18px Arial, sans-serif;_x000D_
  margin: 0;_x000D_
}_x000D_
.container {_x000D_
  justify-content: space-between;_x000D_
  flex-direction: column;_x000D_
  height: 100vh;_x000D_
  display: flex;_x000D_
  padding: 10px;_x000D_
}_x000D_
.container .btn-holder {_x000D_
  justify-content: flex-end;_x000D_
  display: flex;_x000D_
}_x000D_
.container .btn-holder button {_x000D_
  padding: 10px 25px;_x000D_
  background: blue;_x000D_
  font-size: 16px;_x000D_
  border: none;_x000D_
  color: #fff;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p>Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... </p>_x000D_
  <div class="btn-holder">_x000D_
    <button type="button">Click</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to disable auto-play for local video in iframe

I've tried all the possible solutions but nothing worked for local video bindings. I believe best solution would be to fix using jQuery if you still wants to use iframes.

$(document).ready(function () {
    var ownVideos = $("iframe");
    $.each(ownVideos, function (i, video) {                
        var frameContent = $(video).contents().find('body').html();
        if (frameContent) {
            $(video).contents().find('body').html(frameContent.replace("autoplay", ""));
        }
    });
});

Note: It'll find all the iframes on document ready and loop through each iframe contents and replace/remove autoplay attribute. This solution can be use anywhere in your project. If you would like to do for specific element then use the code under $.each function and replace $(video) with your iframe element id like $("#myIFrameId").

SQL Group By with an Order By

Try this query

 SELECT  data_collector_id , count (data_collector_id ) as frequency 
    from rent_flats 
    where is_contact_person_landlord = 'True' 
    GROUP BY data_collector_id 
    ORDER BY count(data_collector_id) DESC

How to write some data to excel file(.xlsx)

Hope here is the exact what we are looking for.

private void button2_Click(object sender, RoutedEventArgs e)
{
    UpdateExcel("Sheet3", 4, 7, "Namachi@gmail");
}

private void UpdateExcel(string sheetName, int row, int col, string data)
{
    Microsoft.Office.Interop.Excel.Application oXL = null;
    Microsoft.Office.Interop.Excel._Workbook oWB = null;
    Microsoft.Office.Interop.Excel._Worksheet oSheet = null;

    try
    {
        oXL = new Microsoft.Office.Interop.Excel.Application();
        oWB = oXL.Workbooks.Open("d:\\MyExcel.xlsx");
        oSheet = String.IsNullOrEmpty(sheetName) ? (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet : (Microsoft.Office.Interop.Excel._Worksheet)oWB.Worksheets[sheetName];

        oSheet.Cells[row, col] = data;

        oWB.Save();

        MessageBox.Show("Done!");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        if (oWB != null)
        oWB.Close();
    }
}

How to find the Vagrant IP?

I find that I do need the IP in order to configure /etc/hosts on the host system to point at services on the fresh VM.

Here's a rough version of what I use to fetch the IP. Let Vagrant do its SSH magic and ask the VM for its address; tweak for your needs.

new_ip=$(vagrant ssh -c "ip address show eth0 | grep 'inet ' | sed -e 's/^.*inet //' -e 's/\/.*$//'")

I just found this in the Vagrant Docs. Looks like they consider it a valid approach:

This will automatically assign an IP address from the reserved address space. The IP address can be determined by using vagrant ssh to SSH into the machine and using the appropriate command line tool to find the IP, such as ifconfig.

Automatically get loop index in foreach loop in Perl

I have tried like....

@array = qw /tomato banana papaya potato/;             # Example array
my $count;                                             # Local variable initial value will be 0.
print "\nBefore For loop value of counter is $count";  # Just printing value before entering the loop.

for (@array) { print "\n",$count++," $_" ; }           # String and variable seperated by comma to
                                                       # execute the value and print.
undef $count;                                          # Undefining so that later parts again it will
                                                       # be reset to 0.

print "\nAfter for loop value of counter is $count";   # Checking the counter value after for loop.

In short...

@array = qw /a b c d/;
my $count;
for (@array) { print "\n",$count++," $_"; }
undef $count;

jQuery vs. javascript?

Personally i think you should learn the hard way first. It will make you a better programmer and you will be able to solve that one of a kind issue when it comes up. After you can do it with pure JavaScript then using jQuery to speed up development is just an added bonus.

If you can do it the hard way then you can do it the easy way, it doesn't work the other way around. That applies to any programming paradigm.

iOS - Ensure execution on main thread

there any rule I can follow to be sure that my app executes my own code just in the main thread?

Typically you wouldn't need to do anything to ensure this — your list of things is usually enough. Unless you're interacting with some API that happens to spawn a thread and run your code in the background, you'll be running on the main thread.

If you want to be really sure, you can do things like

[self performSelectorOnMainThread:@selector(myMethod:) withObject:anObj waitUntilDone:YES];

to execute a method on the main thread. (There's a GCD equivalent too.)

instantiate a class from a variable in PHP?

If You Use Namespaces

In my own findings, I think it's good to mention that you (as far as I can tell) must declare the full namespace path of a class.

MyClass.php

namespace com\company\lib;
class MyClass {
}

index.php

namespace com\company\lib;

//Works fine
$i = new MyClass();

$cname = 'MyClass';

//Errors
//$i = new $cname;

//Works fine
$cname = "com\\company\\lib\\".$cname;
$i = new $cname;

Docker: How to use bash with an Alpine based docker image?

To Install bash you can do:

RUN apk add --update bash && rm -rf /var/cache/apk/*

If you do not want to add extra size to your image, you can use ash or sh that ships with alpine.

Reference: https://github.com/smebberson/docker-alpine/issues/43

Running CMD command in PowerShell

To run or convert batch files externally from PowerShell (particularly if you wish to sign all your scheduled task scripts with a certificate) I simply create a PowerShell script, e.g. deletefolders.ps1.

Input the following into the script:

cmd.exe /c "rd /s /q C:\#TEMP\test1"

cmd.exe /c "rd /s /q C:\#TEMP\test2"

cmd.exe /c "rd /s /q C:\#TEMP\test3"

*Each command needs to be put on a new line calling cmd.exe again.

This script can now be signed and run from PowerShell outputting the commands to command prompt / cmd directly.

It is a much safer way than running batch files!

python JSON only get keys in first level

As Karthik mentioned, dct.keys() will work but it will return all the keys in dict_keys type not in list type. So if you want all the keys in a list, then list(dct.keys()) will work.

No notification sound when sending notification from firebase in android

The onMessageReceived method is fired only when app is in foreground or the notification payload only contains the data type.

From the Firebase docs

For downstream messaging, FCM provides two types of payload: notification and data.

For notification type, FCM automatically displays the message to end-user devices on behalf of the client app. Notifications have a predefined set of user-visible keys.
For data type, client app is responsible for processing data messages. Data messages have only custom key-value pairs.

Use notifications when you want FCM to handle displaying a notification on your client app's behalf. Use data messages when you want your app to handle the display or process the messages on your Android client app, or if you want to send messages to iOS devices when there is a direct FCM connection.

Further down the docs

App behaviour when receiving messages that include both notification and data payloads depends on whether the app is in the background or the foreground—essentially, whether or not it is active at the time of receipt.
When in the background, apps receive the notification payload in the notification tray, and only handle the data payload when the user taps on the notification.
When in the foreground, your app receives a message object with both payloads available.

If you are using the firebase console to send notifications, the payload will always contain the notification type. You have to use the Firebase API to send the notification with only the data type in the notification payload. That way your app is always notified when a new notification is received and the app can handle the notification payload.

If you want to play notification sound when app is in background using the conventional method, you need to add the sound parameter to the notification payload.

Convert Unix timestamp to a date string

Other examples here are difficult to remember. At its simplest:

date -r 1305712800

How do you get the current project directory from C# code when creating a custom MSBuild task?

Use this to get the Project directory (worked for me):

string projectPath = 
    Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName;

How to resize Twitter Bootstrap modal dynamically based on the content

I couldn't get PSL's answer working for me so I found all I have to do is set the div holding the modal content with style="display: table;". The modal content itself says how big it wants to be and the modal accommodates it.

MySQL compare DATE string with string from DATETIME field

SELECT * FROM `calendar` WHERE startTime like '2010-04-29%'

You can also use comparison operators on MySQL dates if you want to find something after or before. This is because they are written in such a way (largest value to smallest with leading zeros) that a simple string sort will sort them correctly.

Spring Boot Rest Controller how to return different HTTP status codes?

In case you want to return a custom defined status code, you can use the ResponseEntity as here:

@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody String data) {
    int customHttpStatusValue = 499;
    Foo foo = bar();
    return ResponseEntity.status(customHttpStatusValue).body(foo);
}

The CustomHttpStatusValue could be any integer within or outside of standard HTTP Status Codes.

How to stop C# console applications from closing automatically?

Alternatively, you can delay the closing using the following code:

System.Threading.Thread.Sleep(1000);

Note the Sleep is using milliseconds.

Pointer arithmetic for void pointer in C

You have to cast it to another type of pointer before doing pointer arithmetic.

How to remove the Flutter debug banner?

  • If you are using Android Studio, you can find the option in the Flutter Inspector tab --> More Actions.

Android Studio

  • Or if you're using Dart DevTools, you can find the same button in the top right corner as well.

Dart DevTools

How to get CRON to call in the correct PATHs

Most likely, cron is running in a very sparse environment. Check the environment variables cron is using by appending a dummy job which dumps env to a file like this:

* * * * * env > env_dump.txt

Compare that with the output of env in a normal shell session.

You can prepend your own environment variables to the local crontab by defining them at the top of your crontab.

Here's a quick fix to prepend $PATH to the current crontab:

# echo PATH=$PATH > tmp.cron
# echo >> tmp.cron
# crontab -l >> tmp.cron
# crontab tmp.cron

The resulting crontab will look similar to chrissygormley's answer, with PATH defined before the crontab rules.

Count the Number of Tables in a SQL Server Database

Try this:

SELECT Count(*)
FROM <DATABASE_NAME>.INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'

ASP.NET: Session.SessionID changes between requests

Another possibility that causes the SessionID to change between requests, even when Session_OnStart is defined and/or a Session has been initialized, is that the URL hostname contains an invalid character (such as an underscore). I believe this is IE specific (not verified), but if your URL is, say, http://server_name/app, then IE will block all cookies and your session information will not be accessible between requests.

In fact, each request will spin up a separate session on the server, so if your page contains multiple images, script tags, etc., then each of those GET requests will result in a different session on the server.

Further information: http://support.microsoft.com/kb/316112

Bootstrap 3 jquery event for active tab change

This worked for me.

$('.nav-pills > li > a').click( function() {
    $('.nav-pills > li.active').removeClass('active');
    $(this).parent().addClass('active');
} );

jQuery click event on radio button doesn't get fired

Seems like you're #inline_content isn't there! Remove the jQuery-Selector or check the parent elements, maybe you have a typo or forgot to add the id.

(made you a jsfiddle, works after adding a parent <div id="inline_content">: http://jsfiddle.net/J5HdN/)

Are HTTPS URLs encrypted?

An addition to the helpful answer from Marc Novakowski - the URL is stored in the logs on the server (e.g., in /etc/httpd/logs/ssl_access_log), so if you don't want the server to maintain the information over the longer term, don't put it in the URL.

If using maven, usually you put log4j.properties under java or resources?

The resources used for initializing the project are preferably put in src/main/resources folder. To enable loading of these resources during the build, one can simply add entries in the pom.xml in maven project as a build resource

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering> 
        </resource>
    </resources>
</build> 

Other .properties files can also be kept in this folder used for initialization. Filtering is set true if you want to have some variables in the properties files of resources folder and populate them from the profile filters properties files, which are kept in src/main/filters which is set as profiles but it is a different use case altogether. For now, you can ignore them.

This is a great resource maven resource plugins, it's useful, just browse through other sections too.

AndroidStudio gradle proxy

The following works for me . File -> Settings -> Appearance & Behavior -> System Settings -> HTTP Proxy Put in your proxy setting in Manual proxy configuration

Restart android studio, a prompt pops up and asks you to add the proxy setting to gradle, click yes.

Create thumbnail image

Here is an example to convert high res image into thumbnail size-

protected void Button1_Click(object sender, EventArgs e)
{
    //----------        Getting the Image File
    System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("~/profile/Avatar.jpg"));

    //----------        Getting Size of Original Image
    double imgHeight = img.Size.Height;
    double imgWidth = img.Size.Width;

    //----------        Getting Decreased Size
    double x = imgWidth / 200;
    int newWidth = Convert.ToInt32(imgWidth / x);
    int newHeight = Convert.ToInt32(imgHeight / x);

    //----------        Creating Small Image
    System.Drawing.Image.GetThumbnailImageAbort myCallback = new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
    System.Drawing.Image myThumbnail = img.GetThumbnailImage(newWidth, newHeight, myCallback, IntPtr.Zero);

    //----------        Saving Image
    myThumbnail.Save(Server.MapPath("~/profile/NewImage.jpg"));
}
public bool ThumbnailCallback()
{
    return false;
}

Source- http://iknowledgeboy.blogspot.in/2014/03/c-creating-thumbnail-of-large-image-by.html

How to Migrate to WKWebView?

WKWebView using Swift in iOS 8..

The whole ViewController.swift file now looks like this:

import UIKit
import WebKit

class ViewController: UIViewController {

    @IBOutlet var containerView : UIView! = nil
    var webView: WKWebView?

    override func loadView() {
        super.loadView()

        self.webView = WKWebView()
        self.view = self.webView!
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        var url = NSURL(string:"http://www.kinderas.com/")
        var req = NSURLRequest(URL:url)
        self.webView!.loadRequest(req)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

}

MVC 3: How to render a view without its layout page when loaded via ajax?

In ~/Views/ViewStart.cshtml:

@{
    Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_Layout.cshtml";
}

and in the controller:

public ActionResult Index()
{
    return View();
}

How do I count the number of rows and columns in a file using bash?

If your file is big but you are certain that the number of columns remains the same for each row (and you have no heading) use:

head -n 1 FILE | awk '{print NF}'

to find the number of columns, where FILE is your file name.

To find the number of lines 'wc -l FILE' will work.

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

A lot of the times the implementation will exist in the same namespace as the interface. So, I came up with this:

    public class InterfaceConverter : JsonConverter
    {
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.ReadFrom(reader);
        var typeVariable = this.GetTypeVariable(token);
        if (TypeExtensions.TryParse(typeVariable, out var implimentation))
        { }
        else if (!typeof(IEnumerable).IsAssignableFrom(objectType))
        {
            implimentation = this.GetImplimentedType(objectType);
        }
        else
        {
            var genericArgumentTypes = objectType.GetGenericArguments();
            var innerType = genericArgumentTypes.FirstOrDefault();
            if (innerType == null)
            {
                implimentation = typeof(IEnumerable);
            }
            else
            {
                Type genericType = null;
                if (token.HasAny())
                {
                    var firstItem = token[0];
                    var genericTypeVariable = this.GetTypeVariable(firstItem);
                    TypeExtensions.TryParse(genericTypeVariable, out genericType);
                }

                genericType = genericType ?? this.GetImplimentedType(innerType);
                implimentation = typeof(IEnumerable<>);
                implimentation = implimentation.MakeGenericType(genericType);
            }
        }

        return JsonConvert.DeserializeObject(token.ToString(), implimentation);
    }

    public override bool CanConvert(Type objectType)
    {
        return !typeof(IEnumerable).IsAssignableFrom(objectType) && objectType.IsInterface || typeof(IEnumerable).IsAssignableFrom(objectType) && objectType.GetGenericArguments().Any(t => t.IsInterface);
    }

    protected Type GetImplimentedType(Type interfaceType)
    {
        if (!interfaceType.IsInterface)
        {
            return interfaceType;
        }

        var implimentationQualifiedName = interfaceType.AssemblyQualifiedName?.Replace(interfaceType.Name, interfaceType.Name.Substring(1));
        return implimentationQualifiedName == null ? interfaceType : Type.GetType(implimentationQualifiedName) ?? interfaceType;
    }

    protected string GetTypeVariable(JToken token)
    {
        if (!token.HasAny())
        {
            return null;
        }

        return token.Type != JTokenType.Object ? null : token.Value<string>("$type");
    }
}

Therefore, you can include this globally like so:

public static JsonSerializerSettings StandardSerializerSettings => new JsonSerializerSettings
    {
        Converters = new List<JsonConverter>
        {
            new InterfaceConverter()
        }
    };

How do I deal with installing peer dependencies in Angular CLI?

NPM package libraries have a section in the package.json file named peerDependencies. For example; a library built in Angular 8, will usually list Angular 8 as a dependency. This is a true dependency for anyone running less than version 8. But for anyone running version 8, 9 or 10, it's questionable whether any concern should be pursued.

I have been safely ignoring these messages on Angular Updates, but then again we do have Unit and Cypress Tests!

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

Just add another way , in normal mode , type ctrl+v then G, select the rest, then D, I don't think it is effective , you should do like @Ed Guiness, head -n 20 > filename in linux.

Keyboard shortcuts with jQuery

Since this question was originally asked, John Resig (the primary author of jQuery) has forked and improved the js-hotkeys project. His version is available at:

http://github.com/jeresig/jquery.hotkeys

how to specify new environment location for conda create

like Paul said, use

conda create --prefix=/users/.../yourEnvName python=x.x

if you are located in the folder in which you want to create your virtual environment, just omit the path and use

conda create --prefix=yourEnvName python=x.x

conda only keep track of the environments included in the folder envs inside the anaconda folder. The next time you will need to activate your new env, move to the folder where you created it and activate it with

source activate yourEnvName

How to insert a blob into a database using sql server management studio

There are two ways to SELECT a BLOB with TSQL:

SELECT * FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a

As well as:

SELECT BulkColumn FROM OPENROWSET (BULK 'C:\Test\Test1.pdf', SINGLE_BLOB) a

Note the correlation name after the FROM clause, which is mandatory.

You can then this to INSERT by doing an INSERT SELECT.

You can also use the second version to do an UPDATE as I described in How To Update A BLOB In SQL SERVER Using TSQL .

How to add an empty column to a dataframe?

The reason I was looking for such a solution is simply to add spaces between multiple DFs which have been joined column-wise using the pd.concat function and then written to excel using xlsxwriter.

df[' ']=df.apply(lambda _: '', axis=1)
df_2 = pd.concat([df,df1],axis=1)                #worked but only once. 
# Note: df & df1 have the same rows which is my index. 
#
df_2[' ']=df_2.apply(lambda _: '', axis=1)       #didn't work this time !!?     
df_4 = pd.concat([df_2,df_3],axis=1)

I then replaced the second lambda call with

df_2['']=''                                 #which appears to add a blank column
df_4 = pd.concat([df_2,df_3],axis=1)

The output I tested it on was using xlsxwriter to excel. Jupyter blank columns look the same as in excel although doesnt have xlsx formatting. Not sure why the second Lambda call didnt work.

Call of overloaded function is ambiguous

The solution is very simple if we consider the type of the constant value, which should be "unsigned int" instead of "int".

Instead of:

setval(0)

Use:

setval(0u)

The suffix "u" tell the compiler this is a unsigned integer. Then, no conversion would be needed, and the call will be unambiguous.

Comparing two integer arrays in Java

From what I see you just try to see if they are equal, if this is true, just go with something like this:

boolean areEqual = Arrays.equals(arr1, arr2);

This is the standard way of doing it.

Please note that the arrays must be also sorted to be considered equal, from the JavaDoc:

Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order.

Sorry for missing that.

Recommended way to get hostname in Java

As others have noted, getting the hostname based on DNS resolution is unreliable.

Since this question is unfortunately still relevant in 2018, I'd like to share with you my network-independent solution, with some test runs on different systems.

The following code tries to do the following:

  • On Windows

    1. Read the COMPUTERNAME environment variable through System.getenv().

    2. Execute hostname.exe and read the response

  • On Linux

    1. Read the HOSTNAME environment variable through System.getenv()

    2. Execute hostname and read the response

    3. Read /etc/hostname (to do this I'm executing cat since the snippet already contains code to execute and read. Simply reading the file would be better, though).

The code:

public static void main(String[] args) throws IOException {
    String os = System.getProperty("os.name").toLowerCase();

    if (os.contains("win")) {
        System.out.println("Windows computer name through env:\"" + System.getenv("COMPUTERNAME") + "\"");
        System.out.println("Windows computer name through exec:\"" + execReadToString("hostname") + "\"");
    } else if (os.contains("nix") || os.contains("nux") || os.contains("mac os x")) {
        System.out.println("Unix-like computer name through env:\"" + System.getenv("HOSTNAME") + "\"");
        System.out.println("Unix-like computer name through exec:\"" + execReadToString("hostname") + "\"");
        System.out.println("Unix-like computer name through /etc/hostname:\"" + execReadToString("cat /etc/hostname") + "\"");
    }
}

public static String execReadToString(String execCommand) throws IOException {
    try (Scanner s = new Scanner(Runtime.getRuntime().exec(execCommand).getInputStream()).useDelimiter("\\A")) {
        return s.hasNext() ? s.next() : "";
    }
}

Results for different operating systems:

macOS 10.13.2

Unix-like computer name through env:"null"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:""

OpenSuse 13.1

Unix-like computer name through env:"machinename"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:""

Ubuntu 14.04 LTS This one is kinda strange since echo $HOSTNAME returns the correct hostname, but System.getenv("HOSTNAME") does not:

Unix-like computer name through env:"null"
Unix-like computer name through exec:"machinename
"
Unix-like computer name through /etc/hostname:"machinename
"

EDIT: According to legolas108, System.getenv("HOSTNAME") works on Ubuntu 14.04 if you run export HOSTNAME before executing the Java code.

Windows 7

Windows computer name through env:"MACHINENAME"
Windows computer name through exec:"machinename
"

Windows 10

Windows computer name through env:"MACHINENAME"
Windows computer name through exec:"machinename
"

The machine names have been replaced but I kept the capitalization and structure. Note the extra newline when executing hostname, you might have to take it into account in some cases.

Python: call a function from string name

If it's in a class, you can use getattr:

class MyClass(object):
    def install(self):
          print "In install"

method_name = 'install' # set by the command line options
my_cls = MyClass()

method = None
try:
    method = getattr(my_cls, method_name)
except AttributeError:
    raise NotImplementedError("Class `{}` does not implement `{}`".format(my_cls.__class__.__name__, method_name))

method()

or if it's a function:

def install():
       print "In install"

method_name = 'install' # set by the command line options
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
     raise NotImplementedError("Method %s not implemented" % method_name)
method()

Getting reference to the top-most view/window in iOS application

Whenever I want to display some overlay on top of everything else, I just add it on top of the Application Window directly:

[[[UIApplication sharedApplication] keyWindow] addSubview:someView]

Check if an HTML input element is empty or has no value entered by user

var input = document.getElementById("customx");

if (input && input.value) {
    alert(1);
}
else {
    alert (0);
}

How can I scale the content of an iframe?

For those of you having trouble getting this to work in IE, it is helpful to use -ms-zoom as suggested below and use the zoom function on the #wrap div, not the iframe id. In my experience, with the zoom function trying to scale the iframe div of #frame, it would scale the iframe size and not the content within it (which is what you're going for).

Looks like this. Works for me on IE8, Chrome and FF.

#wrap {
  overflow: hidden;
  position: relative;
  width:800px;
  height:850px;
  -ms-zoom: 0.75;
}

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

it turns out that I got this error because my requested module is not bundled in the minification prosses due to path misspelling

so make sure that your module exists in minified js file (do search for a word within it to be sure)

Using ChildActionOnly in MVC

You would use it if you are using RenderAction in any of your views, usually to render a partial view.

The reason for marking it with [ChildActionOnly] is that you need the controller method to be public so you can call it with RenderAction but you don't want someone to be able to navigate to a URL (e.g. /Controller/SomeChildAction) and see the results of that action directly.

Service Reference Error: Failed to generate code for the service reference

As stated above, there are a couple of different problems possible. What we found is that the .DLL for the WCF library had been added as a reference to the client project. This, in turn, created problems with resolving the objects and thus caused the files to be "emptied" by code generation steps. While unchecking the use "Reuse Types..." can seem like an answer, it creates extra definitions of object types, which are proxies to the real types, in a new name space, which then causes all kinds of "compatibility" issues with the use of those types. Only if you really want to "hide" a type should you check this option.

Hiding the type would be appropriate when you don't want a "DLL" type dependency to "leak" into a project that you are trying to keep segregated from another. If the DLL for the WCF library project creeps into the client project references, then you will have this problem with all kinds of strange side effects since the type definitions are also in the DLL.

Circular dependency in Spring

The Spring container is able to resolve Setter-based circular dependencies but gives a runtime exception BeanCurrentlyInCreationException in case of Constructor-based circular dependencies. In case of Setter-based circular dependency, the IOC container handles it differently from a typical scenario wherein it would fully configure the collaborating bean before injecting it. For eg., if Bean A has a dependency on Bean B and Bean B on Bean C, the container fully initializes C before injecting it to B and once B is fully initialized it is injected to A. But in case of circular dependency, one of the beans is injected to the other before it is fully initialized.

Multiple Cursors in Sublime Text 2 Windows

In Sublime Text, after you select multiple regions of text, a click is considered a way to exit the multi-select mode. Move the cursor with the keyboard keys (arrows, Ctrl+arrows, etc.) instead, and you'll be fine

SQL: Select columns with NULL values only

Try this -

DECLARE @table VARCHAR(100) = 'dbo.table'

DECLARE @sql NVARCHAR(MAX) = ''

SELECT @sql = @sql + 'IF NOT EXISTS(SELECT 1 FROM ' + @table + ' WHERE ' + c.name + ' IS NOT NULL) PRINT ''' + c.name + ''''
FROM sys.objects o
JOIN sys.columns c ON o.[object_id] = c.[object_id]
WHERE o.[type] = 'U'
    AND o.[object_id] = OBJECT_ID(@table)
    AND c.is_nullable = 1

EXEC(@sql)

How to INNER JOIN 3 tables using CodeIgniter

For executing pure SQL statements (I Don't Know About the FRAMEWORK- CodeIGNITER!!!) you can use SUB QUERY! The Syntax Would be as follows

SELECT t1.id FROM example t1 INNER JOIN (select id from (example2 t1 join example3 t2 on t1.id = t2.id)) as t2 ON t1.id = t2.id;

Hope you Get My Point!

What is the most efficient way to store a list in the Django models?

"Premature optimization is the root of all evil."

With that firmly in mind, let's do this! Once your apps hit a certain point, denormalizing data is very common. Done correctly, it can save numerous expensive database lookups at the cost of a little more housekeeping.

To return a list of friend names we'll need to create a custom Django Field class that will return a list when accessed.

David Cramer posted a guide to creating a SeperatedValueField on his blog. Here is the code:

from django.db import models

class SeparatedValuesField(models.TextField):
    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        self.token = kwargs.pop('token', ',')
        super(SeparatedValuesField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value: return
        if isinstance(value, list):
            return value
        return value.split(self.token)

    def get_db_prep_value(self, value):
        if not value: return
        assert(isinstance(value, list) or isinstance(value, tuple))
        return self.token.join([unicode(s) for s in value])

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

The logic of this code deals with serializing and deserializing values from the database to Python and vice versa. Now you can easily import and use our custom field in the model class:

from django.db import models
from custom.fields import SeparatedValuesField 

class Person(models.Model):
    name = models.CharField(max_length=64)
    friends = SeparatedValuesField()

How to split a string content into an array of strings in PowerShell?

Remove the spaces from the original string and split on semicolon

$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')

$addresses becomes:

@('[email protected]','[email protected]','[email protected]')

How can I inspect the file system of a failed `docker build`?

The top answer works in the case that you want to examine the state immediately prior to the failed command.

However, the question asks how to examine the state of the failed container itself. In my situation, the failed command is a build that takes several hours, so rewinding prior to the failed command and running it again takes a long time and is not very helpful.

The solution here is to find the container that failed:

$ docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                          PORTS               NAMES
6934ada98de6        42e0228751b3        "/bin/sh -c './utils/"   24 minutes ago      Exited (1) About a minute ago                       sleepy_bell

Commit it to an image:

$ docker commit 6934ada98de6
sha256:7015687976a478e0e94b60fa496d319cdf4ec847bcd612aecf869a72336e6b83

And then run the image [if necessary, running bash]:

$ docker run -it 7015687976a4 [bash -il]

Now you are actually looking at the state of the build at the time that it failed, instead of at the time before running the command that caused the failure.

PHP Checking if the current date is before or after a set date

if( strtotime($database_date) > strtotime('now') ) {
...

Import python package from local directory into interpreter

Keep it simple:

 try:
     from . import mymodule     # "myapp" case
 except:
     import mymodule            # "__main__" case

How can I join on a stored procedure?

I resolved this problem writing function instead of procedure and using CROSS APPLY in SQL statement. This solution works on SQL 2005 and later versions.

Using JQuery hover with HTML image map

Although jQuery Maphilight plugin does the job, it relies on the outdated verbose imagemap in your html. I would prefer to keep the mapcoordinates external. This could be as JS with the jquery imagemap plugin but it lacks hover states. A nice solution is googles geomap visualisation in flash and JS. But the opensource future for this kind of vectordata however is svg, considering svg support accross all modern browsers, and googles svgweb for a flash convert for IE, why not a jquery plugin to add links and hoverstates to a svg map, like the JS demo here? That way you also avoid the complex step of transforming a vectormap to a imagemap coordinates.

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

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

First Install MinGW or other C/C++ compiler as it's required by Eclipse C++.

Use https://sourceforge.net/projects/mingw-w64/ as unbelievably the download.cnet.com's version has malware attached.

Back to Eclipse.

Now in all those path settings that the Eclipse Help manual talks about INSTEAD of typing the path, Select Variables and

**MINGW_HOME** 

and do so for all instances which would ask for the compiler's path.

First would be to click Preferences of the whatever project and C/C++ General then Paths and Symbols and add the

**MINGW_HOME** to those paths of for the compiler.

Next simply add the home directory to the Build Variables under the C++/C Build

Build Variables Screen Capture

Remove numbers from string sql server

Remove everything after first digit (was adequate for my use case): LEFT(field,PATINDEX('%[0-9]%',field+'0')-1)

Remove trailing digits: LEFT(field,len(field)+1-PATINDEX('%[^0-9]%',reverse('0'+field))

Best way to check if a character array is empty

if (!*text) {}  

The above dereferences the pointer 'text' and checks to see if it's zero. alternatively:

if (*text == 0) {} 

Detect IE version (prior to v9) in JavaScript

The below codepen identifies IE version in all cases (IE<=9, IE10, IE11 and IE/Edge)

function detectIE() {
    var ua = window.navigator.userAgent;
    var msie = ua.indexOf('MSIE ');
    if (msie > 0) {
        // IE 10 or older => return version number
        return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
    }
    var trident = ua.indexOf('Trident/');
    if (trident > 0) {
        // IE 11 => return version number
        var rv = ua.indexOf('rv:');
        return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
    }
    var edge = ua.indexOf('Edge/');
    if (edge > 0) {
        // Edge (IE 12+) => return version number
        return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
    }
    // other browser
    return false;
}

ref: https://codepen.io/gapcode/pen/vEJNZN

How do I get the last character of a string?

Here is a method I use to get the last xx of a string:

public static String takeLast(String value, int count) {
    if (value == null || value.trim().length() == 0) return "";
    if (count < 1) return "";

    if (value.length() > count) {
        return value.substring(value.length() - count);
    } else {
        return value;
    }
}

Then use it like so:

String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring

How can I do a BEFORE UPDATED trigger with sql server?

All "normal" triggers in SQL Server are "AFTER ..." triggers. There are no "BEFORE ..." triggers.

To do something before an update, check out INSTEAD OF UPDATE Triggers.

print arraylist element?

Printing a specific element is

list.get(INDEX)

I think the best way to print the whole list in one go and this will also avoid putting a loop

Arrays.toString(list.toArray())

How do you implement a Stack and a Queue in JavaScript?

Construct a Queue using two Stacks.

O(1) for both enqueue and dequeue operations.

class Queue {
  constructor() {
    this.s1 = []; // in
    this.s2 = []; // out
  }

  enqueue(val) {
    this.s1.push(val);
  }

  dequeue() {
    if (this.s2.length === 0) {
      this._move();
    }

    return this.s2.pop(); // return undefined if empty
  }

  _move() {
    while (this.s1.length) {
      this.s2.push(this.s1.pop());
    }
  }
}

Any reason to prefer getClass() over instanceof when generating .equals()?

Both methods have their problems.

If the subclass changes the identity, then you need to compare their actual classes. Otherwise, you violate the symmetric property. For instance, different types of Persons should not be considered equivalent, even if they have the same name.

However, some subclasses don't change identity and these need to use instanceof. For instance, if we have a bunch of immutable Shape objects, then a Rectangle with length and width of 1 should be equal to the unit Square.

In practice, I think the former case is more likely to be true. Usually, subclassing is a fundamental part of your identity and being exactly like your parent except you can do one little thing does not make you equal.

Refresh certain row of UITableView based on Int in Swift

Swift 4.1

use it when you delete row using selectedTag of row.

self.tableView.beginUpdates()

        self.yourArray.remove(at:  self.selectedTag)
        print(self.allGroups)

        let indexPath = NSIndexPath.init(row:  self.selectedTag, section: 0)

        self.tableView.deleteRows(at: [indexPath as IndexPath], with: .automatic)

        self.tableView.endUpdates()

        self.tableView.reloadRows(at: self.tableView.indexPathsForVisibleRows!, with: .automatic)

Increment a value in Postgres

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill';

If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:

UPDATE totals 
   SET total = total + 1
WHERE name = 'bill'
  AND total = 203;

Listing all extras of an Intent

The Kotlin version of Pratik's utility method which dumps all extras of an Intent:

fun dumpIntent(intent: Intent) {

    val bundle: Bundle = intent.extras ?: return

    val keys = bundle.keySet()
    val it = keys.iterator()

    Log.d(TAG, "Dumping intent start")

    while (it.hasNext()) {
        val key = it.next()
        Log.d(TAG,"[" + key + "=" + bundle.get(key)+"]");
    }

    Log.d(TAG, "Dumping intent finish")

}

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

If you're using typescript, this could be a good thing for you

enum ETime {
  Seconds = 1000,
  Minutes = 60000,
  Hours = 3600000,
  SecInMin = 60,
  MinInHours = 60,
  HoursMod = 24,
  timeMin = 10,
}

interface ITime {
  millis: number
  modulo: number
}

const Times = {
  seconds: {
    millis: ETime.Seconds,
    modulo: ETime.SecInMin,
  },
  minutes: {
    millis: ETime.Minutes,
    modulo: ETime.MinInHours,
  },
  hours: {
    millis: ETime.Hours,
    modulo: ETime.HoursMod,
  },
}

const dots: string = ":"

const msToTime = (duration: number, needHours: boolean = true): string => {
  const getCorrectTime = (divider: ITime): string => {
    const timeStr: number = Math.floor(
      (duration / divider.millis) % divider.modulo,
    )

    return timeStr < ETime.timeMin ? "0" + timeStr : String(timeStr)
  }

  return (
    (needHours ? getCorrectTime(Times.hours) + dots : "") +
    getCorrectTime(Times.minutes) +
    dots +
    getCorrectTime(Times.seconds)
  )
}

How do I get the information from a meta tag with JavaScript?

There is an easier way:

document.getElementsByName('name of metatag')[0].getAttribute('content')

jQuery - prevent default, then continue default

I would just do:

 $('#submiteButtonID').click(function(e){
     e.preventDefault();
     //do your stuff.
     $('#formId').submit();
 });

Call preventDefault at first and use submit() function later, if you just need to submit the form

File URL "Not allowed to load local resource" in the Internet Browser

Now we know what the actual error is can formulate an answer.

Not allowed to load local resource

is a Security exception built into Chrome and other modern browsers. The wording may be different but in some way shape or form they all have security exceptions in place to deal with this scenario.

In the past you could override certain settings or apply certain flags such as

--disable-web-security --allow-file-access-from-files --allow-file-access

in Chrome (See https://stackoverflow.com/a/22027002/692942)

It's there for a reason

At this point though it's worth pointing out that these security exceptions exist for good reason and trying to circumvent them isn't the best idea.

There is another way

As you have access to Classic ASP already you could always build a intermediary page that serves the network based files. You do this using a combination of the ADODB.Stream object and the Response.BinaryWrite() method. Doing this ensures your network file locations are never exposed to the client and due to the flexibility of the script it can be used to load resources from multiple locations and multiple file types.

Here is a basic example (getfile.asp);

<%
Option Explicit

Dim s, id, bin, file, filename, mime

id = Request.QueryString("id")

'id can be anything just use it as a key to identify the 
'file to return. It could be a simple Case statement like this
'or even pulled from a database.
Select Case id
Case "TESTFILE1"
  'The file, mime and filename can be built-up anyway they don't 
  'have to be hard coded.
  file = "\\server\share\Projecten\Protocollen\346\Uitvoeringsoverzicht.xls"     
  mime = "application/vnd.ms-excel"
  'Filename you want to display when downloading the resource.
  filename = "Uitvoeringsoverzicht.xls"

'Assuming other files 
Case ...
End Select

If Len(file & "") > 0 Then
  Set s = Server.CreateObject("ADODB.Stream")
  s.Type = adTypeBinary 'adTypeBinary = 1 See "Useful Links"
  Call s.Open()
  Call s.LoadFromFile(file)
  bin = s.Read()

  'Clean-up the stream and free memory
  Call s.Close()
  Set s = Nothing

  'Set content type header based on mime variable
  Response.ContentType = mime
  'Control how the content is returned using the 
  'Content-Disposition HTTP Header. Using "attachment" forces the resource
  'to prompt the client to download while "inline" allows the resource to
  'download and display in the client (useful for returning images
  'as the "src" of a <img> tag).
  Call Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
  Call Response.BinaryWrite(bin)
Else
  'Return a 404 if there's no file.
  Response.Status = "404 Not Found"
End If
%>

This example is pseudo coded and as such is untested.

This script can then be used in <a> like this to return the resource;

<a href="/getfile.asp?id=TESTFILE1">Click Here</a>

The could take this approach further and consider (especially for larger files) reading the file in chunks using Response.IsConnected to check whether the client is still there and s.EOS property to check for the end of the stream while the chunks are being read. You could also add to the querystring parameters to set whether you want the file to return in-line or prompt to be downloaded.


Useful Links

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

#temp is materalized and CTE is not.

CTE is just syntax so in theory it is just a subquery. It is executed. #temp is materialized. So an expensive CTE in a join that is execute many times may be better in a #temp. On the other side if it is an easy evaluation that is not executed but a few times then not worth the overhead of #temp.

The are some people on SO that don't like table variable but I like them as the are materialized and faster to create than #temp. There are times when the query optimizer does better with a #temp compared to a table variable.

The ability to create a PK on a #temp or table variable gives the query optimizer more information than a CTE (as you cannot declare a PK on a CTE).

Disable scrolling when touch moving certain element

Note: As pointed out in the comments by @nevf, this solution may no longer work (at least in Chrome) due to performance changes. The recommendation is to use touch-action which is also suggested by @JohnWeisz's answer.

Similar to the answer given by @Llepwryd, I used a combination of ontouchstart and ontouchmove to prevent scrolling when it is on a certain element.

Taken as-is from a project of mine:

window.blockMenuHeaderScroll = false;
$(window).on('touchstart', function(e)
{
    if ($(e.target).closest('#mobileMenuHeader').length == 1)
    {
        blockMenuHeaderScroll = true;
    }
});
$(window).on('touchend', function()
{
    blockMenuHeaderScroll = false;
});
$(window).on('touchmove', function(e)
{
    if (blockMenuHeaderScroll)
    {
        e.preventDefault();
    }
});

Essentially, what I am doing is listening on the touch start to see whether it begins on an element that is a child of another using jQuery .closest and allowing that to turn on/off the touch movement doing scrolling. The e.target refers to the element that the touch start begins with.

You want to prevent the default on the touch move event however you also need to clear your flag for this at the end of the touch event otherwise no touch scroll events will work.

This can be accomplished without jQuery however for my usage, I already had jQuery and didn't need to code something up to find whether the element has a particular parent.

Tested in Chrome on Android and an iPod Touch as of 2013-06-18

MySQL SELECT WHERE datetime matches day (and not necessarily time)

You can use %:

SELECT * FROM datetable WHERE datecol LIKE '2012-12-25%'

pip not working in Python Installation in Windows 10

open command prompt

python pip install <package-name> 

This should complete the process

How can I check if a View exists in a Database?

To expand on Kevin's answer.

    private bool CustomViewExists(string viewName)
    {
        using (SalesPad.Data.DataConnection dc = yourconnection)
        {
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(String.Format(@"IF EXISTS(select * FROM sys.views where name = '{0}')
                Select 1
            else
                Select 0", viewName));
            cmd.CommandType = CommandType.Text;
            return Convert.ToBoolean(dc.ExecuteScalar(cmd));
        }
    }

How can I check for existence of element in std::vector, in one line?

int elem = 42;
std::vector<int> v;
v.push_back(elem);
if(std::find(v.begin(), v.end(), elem) != v.end())
{
  //elem exists in the vector
} 

PHP: How do you determine every Nth iteration of a loop?

It will not work for first position so better solution is :

if ($counter != 0 && $counter % 3 == 0) {
   echo 'image file';
}

Check it by yourself. I have tested it for adding class for every 4th element.

How do I compile with -Xlint:unchecked?

In gradle project, You can added this compile parameter in the following way:

gradle.projectsEvaluated {
    tasks.withType(JavaCompile) {
        options.compilerArgs << "-Xlint:unchecked"
    }
}

Get the current displaying UIViewController on the screen in AppDelegate.m

You can use the rootViewController also when your controller is not a UINavigationController:

UIViewController *vc = self.window.rootViewController;

Once you know the root view controller, then it depends on how you have built your UI, but you can possibly find out a way to navigate through the controllers hierarchy.

If you give some more details about the way you defined your app, then I might give some more hint.

EDIT:

If you want the topmost view (not view controller), you could check

[[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];

although this view might be invisible or even covered by some of its subviews...

again, it depends on your UI, but this might help...

How to find out when an Oracle table was updated the last time

If any one is still looking for an answer they can use Oracle Database Change Notification feature coming with Oracle 10g. It requires CHANGE NOTIFICATION system privilege. You can register listeners when to trigger a notification back to the application.

go to link on button click - jquery

Why not just change the second line to

document.location.href="www.example.com/index.php?id=" + $(this).attr('id');

What is the difference between association, aggregation and composition?

For two objects, Foo and Bar the relationships can be defined

Association - I have a relationship with an object. Foo uses Bar

public class Foo { 
    void Baz(Bar bar) {
    } 
};

Composition - I own an object and I am responsible for its lifetime. When Foo dies, so does Bar

public class Foo {
    private Bar bar = new Bar(); 
}

Aggregation - I have an object which I've borrowed from someone else. When Foo dies, Bar may live on.

public class Foo { 
    private Bar bar; 
    Foo(Bar bar) { 
       this.bar = bar; 
    }
}

Jquery, Clear / Empty all contents of tbody element?

Without use ID (<tbody id="tbodyid">) , it is a great way to cope with this issue

$('#table1').find("tr:gt(0)").remove();

PS:To remove specific row number as following example

$('#table1 tr').eq(1).remove();

or

$('#tr:nth-child(2)').remove();

How to put comments in Django templates

Comment tags are documented at https://docs.djangoproject.com/en/stable/ref/templates/builtins/#std:templatetag-comment

{% comment %} this is a comment {% endcomment %}

Single line comments are documented at https://docs.djangoproject.com/en/stable/topics/templates/#comments

{# this won't be rendered #}

Stopping fixed position scrolling at a certain point?

In a project, I actually have some heading fixed to the bottom of the screen on page load (it's a drawing app so the heading is at the bottom to give maximum space to the canvas element on wide viewport).

I needed the heading to become 'absolute' when it reaches the footer on scroll, since I don't want the heading over the footer (heading colour is same as footer background colour).

I took the oldest response on here (edited by Gearge Millo) and that code snippet worked for my use-case. With some playing around I got this working. Now the fixed heading sits beautifully above the footer once it reaches the footer.

Just thought I'd share my use-case and how it worked, and say thank you! The app: http://joefalconer.com/web_projects/drawingapp/index.html

    /* CSS */
    @media screen and (min-width: 1100px) {
        #heading {
            height: 80px;
            width: 100%;
            position: absolute;  /* heading is 'absolute' on page load. DOESN'T WORK if I have this on 'fixed' */
            bottom: 0;
        }
    }

    // jQuery
    // Stop the fixed heading from scrolling over the footer
    $.fn.followTo = function (pos) {
      var $this = this,
      $window = $(window);

      $window.scroll(function (e) {
        if ($window.scrollTop() > pos) {
          $this.css( { position: 'absolute', bottom: '-180px' } );
        } else {
          $this.css( { position: 'fixed', bottom: '0' } );
        }
      });
    };
    // This behaviour is only needed for wide view ports
    if ( $('#heading').css("position") === "absolute" ) {
      $('#heading').followTo(180);
    }

How do I tell Python to convert integers into words

You have to use a dictionnary/array. For example :

 to_19= ['zero','one','two','three','four','five','six','seven','eight','nine'..'nineteen']
 tens = ['twenty'...'ninety']

And you could generate the string of a number by doing, for example :

 if len(str(number)) == 2 and  number > 20:
       word_number = tens[str(number)[0]]+' '+units[str(number)[0]]

You have to check if the last figure is not a zero and so on.. classic value checking.

It reminds a project euler challenge (problem 17).. you should try to find some solutions about it

Hope it helps

WordPress Get the Page ID outside the loop

You can also create a generic function to get the ID of the post, whether its outside or inside the loop (handles both the cases):

<?php

/**
 * @uses WP_Query
 * @uses get_queried_object()
 * @see get_the_ID()
 * @return int
 */
function get_the_post_id() {
  if (in_the_loop()) {
       $post_id = get_the_ID();
  } else {
       global $wp_query;
       $post_id = $wp_query->get_queried_object_id();
         }
  return $post_id;
} ?>

And simply do:

$page_id = get_the_post_id();

How can I specify a local gem in my Gemfile?

If you want the branch too:

gem 'foo', path: "point/to/your/path", branch: "branch-name"

ImportError: No module named site on Windows

Quick solution: set PYTHONHOME and PYTHONPATH and include PYTHONHOME on PATH

For example if you installed to c:\Python27

set PYTHONHOME=c:\Python27
set PYTHONPATH=c:\Python27\Lib
set PATH=%PYTHONHOME%;%PATH%

Make sure you don't have a trailing '\' on the PYTHON* vars, this seems to break it aswel.

How to create string with multiple spaces in JavaScript

var a = 'something' + Array(10).fill('\xa0').join('') + 'something'

number inside Array(10) can be changed to needed number of spaces

Capturing window.onbeforeunload

The reason why nothing happens when you use 'alert()' is probably as explained by MDN: "The HTML specification states that calls to window.alert(), window.confirm(), and window.prompt() methods may be ignored during this event."

But there is also another reason why you might not see the warning at all, whether it calls alert() or not, also explained on the same site:

"... browsers may not display prompts created in beforeunload event handlers unless the page has been interacted with"

That is what I see with current versions of Chrome and FireFox. I open my page which has beforeunload handler set up with this code:

window.addEventListener
('beforeunload'
, function (evt)
  { evt.preventDefault();
    evt.returnValue = 'Hello';
    return "hello 2222"
  }
 );

If I do not click on my page, in other words "do not interact" with it, and click the close-button, the window closes without warning.

But if I click on the page before trying to close the window or tab, I DO get the warning, and can cancel the closing of the window.

So these browsers are "smart" (and user-friendly) in that if you have not done anything with the page, it can not have any user-input that would need saving, so they will close the window without any warnings.

Consider that without this feature any site might selfishly ask you: "Do you really want to leave our site?", when you have already clearly indicated your intention to leave their site.

SEE: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload

Hive cast string to date dd-MM-yyyy

try:

from_unixtime(unix_timestamp('12-03-2010' , 'dd-MM-yyyy'))

Is there a format code shortcut for Visual Studio?

Ctrl + K + D (Entire document)

Ctrl + K + F (Selection only)

Render Content Dynamically from an array map function in React Native

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })
}

You forgot to return the map. this code will resolve the issue.

EditText request focus

It has worked for me as follows.

ed1.requestFocus();

            return; //Faça um return para retornar o foco

Horizontal Scroll Table in Bootstrap/CSS

@Ciwan. You're right. The table goes to full width (much too wide). Not a good solution. Better to do this:

css:

.scrollme {
    overflow-x: auto;
}

html:

<div class="scrollme">                        
  <table class="table table-responsive"> ...
  </table>
</div>

Edit: changing scroll-y to scroll-x

How to trap the backspace key using jQuery?

The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault(). However as the OP alluded to, if you always call it preventDefault() you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.

Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.

// Bind keydown event to this function.  Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){

    // Use jquery's constants rather than an unintuitive magic number.
    // $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
    if (e.keyCode == $.ui.keyCode.BACKSPACE) {

        // Filters out events coming from any of the following tags so Backspace
        // will work when typing text, but not take the page back otherwise.
        var rx = /INPUT|SELECT|TEXTAREA/i;
        if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
            e.preventDefault();
        }

       // Add your code here.
     }
});

Move a view up only when the keyboard covers an input field

For Swift 4.2

This code will allow you to control the Y axis moment of the frame for a specific device screen size.

PS: This code will not intelligently move the frame based on the location of TextField.

Create an extension for UIDevice

extension UIDevice {
    enum ScreenType: String {
        case iPhone4_4S = "iPhone 4 or iPhone 4s"
        case iPhones_5_5s_5c_SE = "iPhone 5, iPhone 5s, iPhone 5c or iPhone SE"
        case iPhones_6_6s_7_8 = "iPhone 6, iPhone 6s, iPhone 7 or iPhone 8"
        case iPhones_6Plus_6sPlus_7Plus_8Plus = "iPhone 6 Plus, iPhone 6s Plus, iPhone 7 Plus or iPhone 8 Plus"
        case iPhoneX_Xs = "iPhone X, iPhone Xs"
        case iPhoneXR = "iPhone XR"
        case iPhoneXSMax = "iPhone Xs Max"
        case unknown
    }
    var screenType: ScreenType {
        switch UIScreen.main.nativeBounds.height {
        case 960:
            return .iPhone4_4S
        case 1136:
            return .iPhones_5_5s_5c_SE
        case 1334:
            return .iPhones_6_6s_7_8
        case 1920, 2208:
            return .iPhones_6Plus_6sPlus_7Plus_8Plus
        case 1792:
            return .iPhoneXR
        case 2436:
            return .iPhoneX_Xs
        case 2688:
            return .iPhoneXSMax
        default:
            return .unknown
        }
    }
}

Add NotificationObserver on viewDidLoad

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil)

Selector

@objc func keyboardWillShow(notification: NSNotification) {
    if ((notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
        if self.view.frame.origin.y == 0 {
            switch (UIDevice.current.screenType.rawValue) {
            case (UIDevice.ScreenType.iPhones_5_5s_5c_SE.rawValue):
                self.view.frame.origin.y -= 210
            case (UIDevice.ScreenType.iPhones_6_6s_7_8.rawValue):
                self.view.frame.origin.y -= 110
            case (UIDevice.ScreenType.iPhones_6Plus_6sPlus_7Plus_8Plus.rawValue):
                self.view.frame.origin.y -= 80
            case (UIDevice.ScreenType.iPhoneX_Xs.rawValue):
                self.view.frame.origin.y -= 70
            case (UIDevice.ScreenType.iPhoneXR.rawValue):
                self.view.frame.origin.y -= 70
            case (UIDevice.ScreenType.iPhoneXSMax.rawValue):
                self.view.frame.origin.y -= 70
            default:
                self.view.frame.origin.y -= 150
            }
        }
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if ((notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue) != nil {
        if self.view.frame.origin.y != 0 {
            switch (UIDevice.current.screenType.rawValue) {
            case (UIDevice.ScreenType.iPhones_5_5s_5c_SE.rawValue):
                self.view.frame.origin.y += 210
            case (UIDevice.ScreenType.iPhones_6_6s_7_8.rawValue):
                self.view.frame.origin.y += 110
            case (UIDevice.ScreenType.iPhones_6Plus_6sPlus_7Plus_8Plus.rawValue):
                self.view.frame.origin.y += 80
            case (UIDevice.ScreenType.iPhoneX_Xs.rawValue):
                self.view.frame.origin.y += 70
            case (UIDevice.ScreenType.iPhoneXR.rawValue):
                self.view.frame.origin.y += 70
            case (UIDevice.ScreenType.iPhoneXSMax.rawValue):
                self.view.frame.origin.y += 70
            default:
                self.view.frame.origin.y += 150
            }
        }
    }
}

Difference between attr_accessor and attr_accessible

attr_accessor is a Ruby method that gives you setter and getter methods to an instance variable of the same name. So it is equivalent to

class MyModel
  def my_variable
    @my_variable
  end
  def my_variable=(value)
    @my_variable = value
  end
end

attr_accessible is a Rails method that determines what variables can be set in a mass assignment.

When you submit a form, and you have something like MyModel.new params[:my_model] then you want to have a little bit more control, so that people can't submit things that you don't want them to.

You might do attr_accessible :email so that when someone updates their account, they can change their email address. But you wouldn't do attr_accessible :email, :salary because then a person could set their salary through a form submission. In other words, they could hack their way to a raise.

That kind of information needs to be explicitly handled. Just removing it from the form isn't enough. Someone could go in with firebug and add the element into the form to submit a salary field. They could use the built in curl to submit a new salary to the controller update method, they could create a script that submits a post with that information.

So attr_accessor is about creating methods to store variables, and attr_accessible is about the security of mass assignments.

How to put Google Maps V2 on a Fragment using ViewPager

For the issue of getting a NullPointerException when we change the Tabs in a FragmentTabHost you just need to add this code to your class which has the TabHost. I mean the class where you initialize the tabs. This is the code :

/**** Fix for error : Activity has been destroyed, when using Nested tabs 
 * We are actually detaching this tab fragment from the `ChildFragmentManager`
 * so that when this inner tab is viewed back then the fragment is attached again****/

import java.lang.reflect.Field;

@Override
public void onDetach() {
    super.onDetach();
    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

Simple timeout in java

    @Singleton
    @AccessTimeout(value=120000)
    public class StatusSingletonBean {
      private String status;
    
      @Lock(LockType.WRITE)
      public void setStatus(String new Status) {
        status = newStatus;
      }
      @Lock(LockType.WRITE)
      @AccessTimeout(value=360000)
      public void doTediousOperation {
        //...
      }
    }
    //The following singleton has a default access timeout value of 60 seconds, specified //using the TimeUnit.SECONDS constant:
    @Singleton
    @AccessTimeout(value=60, timeUnit=SECONDS) 
    public class StatusSingletonBean { 
    //... 
    }  
    //The Java EE 6 Tutorial

//https://docs.oracle.com/javaee/6/tutorial/doc/gipvi.html

Using Thymeleaf when the value is null

   <p data-th-text ="${#strings.defaultString(yourNullable,'defaultValueIfYourValueIsNull')}"></p>

Writing an input integer into a cell

I recommend always using a named range (as you have suggested you are doing) because if any columns or rows are added or deleted, the name reference will update, whereas if you hard code the cell reference (eg "H1" as suggested in one of the responses) in VBA, then it will not update and will point to the wrong cell.

So

Range("RefNo") = InputBox("....") 

is safer than

Range("H1") = InputBox("....") 

You can set the value of several cells, too.

Range("Results").Resize(10,3) = arrResults()

where arrResults is an array of at least 10 rows & 3 columns (and can be any type). If you use this, put this

Option Base 1

at the top of the VBA module, otherwise VBA will assume the array starts at 0 and put a blank first row and column in the sheet. This line makes all arrays start at 1 as a default (which may be abnormal in most languages but works well with spreadsheets).

How to remove certain characters from a string in C++?

Here is a different solution for anyone interested. It uses the new For range in c++11

string str("(555) 555-5555");
string str2="";

for (const auto c: str){

    if(!ispunct(c)){

        str2.push_back(c);
    }
}

str = str2;
//output: 555 5555555
cout<<str<<endl;

How can I get a process handle by its name in C++?

If you don't mind using system(), doing system("taskkill /f /im process.exe") would be significantly easier than these other methods.

change type of input field with jQuery

Just create a new field to bypass this security thing:

var $oldPassword = $("#password");
var $newPassword = $("<input type='text' />")
                          .val($oldPassword.val())
                          .appendTo($oldPassword.parent());
$oldPassword.remove();
$newPassword.attr('id','password');

Ansible date variable

I tried the lookup('pipe,'date') method and got trouble when I push the playbook to the tower. The tower is somehow using UTC timezone. All play executed as early as the + hours of my TZ will give me one day later of the actual date.

For example: if my TZ is Asia/Manila I supposed to have UTC+8. If I execute the playbook earlier than 8:00am in Ansible Tower, the date will follow to what was in UTC+0. It took me a while until I found this case. It let me use the date option '-d \"+8 hours\" +%F'. Now it gives me the exact date that I wanted.

Below is the variable I set in my playbook:

  vars:
    cur_target_wd: "{{ lookup('pipe','date -d \"+8 hours\" +%Y/%m-%b/%d-%a') }}"

That will give me the value of "cur_target_wd = 2020/05-May/28-Thu" even I run it earlier than 8:00am now.

Removing whitespace from strings in Java

There are others space char too exists in strings.. So space char we may need to replace from strings.

Ex: NO-BREAK SPACE, THREE-PER-EM SPACE, PUNCTUATION SPACE

Here is the list of space char http://jkorpela.fi/chars/spaces.html

So we need to modify

\u2004 us for THREE-PER-EM SPACE

s.replaceAll("[\u0020\u2004]","")

How to escape the % (percent) sign in C's printf?

Nitpick:
You don't really escape the % in the string that specifies the format for the printf() (and scanf()) family of functions.

The %, in the printf() (and scanf()) family of functions, starts a conversion specification. One of the rules for conversion specification states that a % as a conversion specifier (immediately following the % that started the conversion specification) causes a '%' character to be written with no argument converted.

The string really has 2 '%' characters inside (as opposed to escaping characters: "a\bc" is a string with 3 non null characters; "a%%b" is a string with 4 non null characters).

How to show shadow around the linearlayout in Android?

set this xml drwable as your background;---

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<!-- Bottom 2dp Shadow -->
<item>
    <shape android:shape="rectangle" >
        <solid android:color="#d8d8d8" />-->Your shadow color<--

        <corners android:radius="15dp" />
    </shape>
</item>

<!-- White Top color -->
<item android:bottom="3px" android:left="3px" android:right="3px" android:top="3px">-->here you can customize the shadow size<---
    <shape android:shape="rectangle" >
        <solid android:color="#FFFFFF" />

        <corners android:radius="15dp" />
    </shape>
</item>

</layer-list>

Duplicate AssemblyVersion Attribute

Yet another solution when upgrading core to VS2017 is to remove them in the properties\assemblyinfo.cs file.

Since they now are stored in the project.

Java Map equivalent in C#

You can index Dictionary, you didn't need 'get'.

Dictionary<string,string> example = new Dictionary<string,string>();
...
example.Add("hello","world");
...
Console.Writeline(example["hello"]);

An efficient way to test/get values is TryGetValue (thanx to Earwicker):

if (otherExample.TryGetValue("key", out value))
{
    otherExample["key"] = value + 1;
}

With this method you can fast and exception-less get values (if present).

Resources:

Dictionary-Keys

Try Get Value

How can I fix "Design editor is unavailable until a successful build" error?

  1. First, find your build.gradle in your all modules in project, include app/build.gradle. Find the compileSdkVersion inside android tag, in this case, compile sdk version is 30:

In this case, SDK version is 30

  1. Next, open SDK Manager > SDK Platforms, check correct version then install selected platforms. After installed, go to menu File > Sync project with Gradle files....

Install the API version which module requires

This issue often appear when project has many modules, each module use different compile SDK version, so app may be able to build but IDE have some issue while processing your resources.

Mock MVC - Add Request Parameter to test

If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params with a MultivalueMap instead of adding each .param :

LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");

mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())

Check if a specific tab page is selected (active)

Assuming you are looking out in Winform, there is a SelectedIndexChanged event for the tab

Now in it you could check for your specific tab and proceed with the logic

private void tab1_SelectedIndexChanged(object sender, EventArgs e)
{
     if (tab1.SelectedTab == tab1.TabPages["tabname"])//your specific tabname
     {
         // your stuff
     }
}

How to exit an if clause

use return in the if condition will returns you out from the function, so that you can use return to break the the if condition.

SMTP connect() failed PHPmailer - PHP

Solved an almost identical problem, by adding these lines to the standard PHPMailer configuration. Works like a charm.

$mail->SMTPKeepAlive = true;   
$mail->Mailer = “smtp”; // don't change the quotes!

Came across this code (from Simon Chen) while researching a solution here, https://webolio.wordpress.com/2008/03/02/phpmailer-and-smtp-on-1and1-shared-hosting/#comment-89

Create list or arrays in Windows Batch

@echo off
setlocal
set "list=a b c d"
(
 for %%i in (%list%) do (
  echo(%%i
  echo(
 )
)>file.txt

You don't need - actually, can't "declare" variables in batch. Assigning a value to a variable creates it, and assigning an empty string deletes it. Any variable name that doesn't have an assigned value HAS a value of an empty string. ALL variables are strings - WITHOUT exception. There ARE operations that appear to perform (integer) mathematical functions, but they operate by converting back and forth from strings.

Batch is sensitive to spaces in variable names, so your assignment as posted would assign the string "A B C D" - including the quotes, to the variable "list " - NOT including the quotes, but including the space. The syntax set "var=string" is used to assign the value string to var whereas set var=string will do the same thing. Almost. In the first case, any stray trailing spaces after the closing quote are EXCLUDED from the value assigned, in the second, they are INCLUDED. Spaces are a little hard to see when printed.

ECHO echoes strings. Clasically, it is followed by a space - one of the default separators used by batch (the others are TAB, COMMA, SEMICOLON - any of these do just as well BUT TABS often get transformed to a space-squence by text-editors and the others have grown quirks of their own over the years.) Other characters following the O in ECHO have been found to do precisely what the documented SPACE should do. DOT is common. Open-parenthesis ( is probably the most useful since the command

ECHO.%emptyvalue%

will produce a report of the ECHO state (ECHO is on/off) whereas

ECHO(%emptyvalue%

will produce an empty line.

The problem with ECHO( is that the result "looks" unbalanced.

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

Let's say you have an array of data:

n = [1    2   3   4   6   12  18  51  69  81  ]

then you can 'foreach' it like this:

for i = n, i, end

This will echo every element in n (but replacing the i with more interesting stuff is also possible of course!)

How to add a "sleep" or "wait" to my Lua Script?

if you're using a MacBook or UNIX based system, use this:

function wait(time)
if tonumber(time) ~= nil then
os.execute("Sleep "..tonumber(time))
else
os.execute("Sleep "..tonumber("0.1"))
end
wait()

How to use __doPostBack()

Here's a brief tutorial on how __doPostBack() works.

To be honest, I don't use it much; at least directly. Many server controls, (e.g., Button, LinkButton, ImageButton, parts of the GridView, etc.) use __doPostBack as their post back mechanism.

How to make type="number" to positive numbers only

_x000D_
_x000D_
<input type="number" min="1" step="1">
_x000D_
_x000D_
_x000D_

SQL WHERE.. IN clause multiple columns

You can make a derived table from the subquery, and join table1 to this derived table:

select * from table1 LEFT JOIN 
(
   Select CM_PLAN_ID, Individual_ID
   From CRM_VCM_CURRENT_LEAD_STATUS
   Where Lead_Key = :_Lead_Key
) table2
ON 
   table1.CM_PLAN_ID=table2.CM_PLAN_ID
   AND table1.Individual=table2.Individual
WHERE table2.CM_PLAN_ID IS NOT NULL

Add some word to all or some rows in Excel?

Save a copy of your spreadsheet first (just in case).

  1. Insert two new columns to the left of the numbered column.

  2. Put a k in the first row of the first (new) column.

  3. Copy it (the k).

  4. Go to the original first column (now the third column) and leave your cursor on the first row that has data.

  5. Hit ctrl and down arrow (at the same time) to jump to the bottom of the populated data range for your original first column.

  6. Left arrow twice to get to the new first column, the one with a k at the very top.

  7. Hit Ctrl-shift-up arrow to go to the first cell with data populated (the original k you put in), highlighting all the cells in-between your starting and ending point.

  8. Use paste (ctrl-v, right-click or whatever your preferred method), and it'll fill all those cells with a k.

  9. Then use the "Concatenate" formula in the second column. Its two arguments will be the column of Ks (column A, first column) and the column with the numbers in it.

  10. This will get you a column with the results of the K column and your numbers.

Hope this helps! The ctrl-shift-arrow and ctrl-arrow shortcuts are amazing for working with large datasets in Excel.

Using "If cell contains #N/A" as a formula condition.

Input the following formula in C1:

=IF(ISNA(A1),B1,A1*B1)

Screenshots:

When #N/A:

enter image description here

When not #N/A:

enter image description here

Let us know if this helps.

Clear Application's Data Programmatically

There's a new API introduced in API 19 (KitKat): ActivityManager.clearApplicationUserData().

I highly recommend using it in new applications:

import android.os.Build.*;
if (VERSION_CODES.KITKAT <= VERSION.SDK_INT) {
    ((ActivityManager)context.getSystemService(ACTIVITY_SERVICE))
            .clearApplicationUserData(); // note: it has a return value!
} else {
    // use old hacky way, which can be removed
    // once minSdkVersion goes above 19 in a few years.
}

If you don't want the hacky way you can also hide the button on the UI, so that functionality is just not available on old phones.

Knowledge of this method is mandatory for anyone using android:manageSpaceActivity.


Whenever I use this, I do so from a manageSpaceActivity which has android:process=":manager". There, I manually kill any other processes of my app. This allows me to let a UI stay running and let the user decide where to go next.

private static void killProcessesAround(Activity activity) throws NameNotFoundException {
    ActivityManager am = (ActivityManager)activity.getSystemService(Context.ACTIVITY_SERVICE);
    String myProcessPrefix = activity.getApplicationInfo().processName;
    String myProcessName = activity.getPackageManager().getActivityInfo(activity.getComponentName(), 0).processName;
    for (ActivityManager.RunningAppProcessInfo proc : am.getRunningAppProcesses()) {
        if (proc.processName.startsWith(myProcessPrefix) && !proc.processName.equals(myProcessName)) {
            android.os.Process.killProcess(proc.pid);
        }
    }
}

How do I check what version of Python is running my script?

If you want to detect pre-Python 3 and don't want to import anything...

...you can (ab)use list comprehension scoping changes and do it in a single expression:

is_python_3_or_above = (lambda x: [x for x in [False]] and None or x)(True)

Replacing a fragment with another fragment inside activity group

Use this code using v4

 ExampleFragment newFragment = new ExampleFragment();     
 FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();  
 // Replace whatever is in the fragment_container view with this fragment,  
 // and add the transaction to the back stack so the user can navigate back   
 transaction.replace(R.id.container, newFragment);
 transaction.addToBackStack(null);  
 // Commit the transaction   
 transaction.commit();

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail 
WHERE ISDATE(LoginTime) = 1

EDIT :

As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT

SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail 

or

SELECT LEFT(LoginTime,10) FROM AuditTrail

EDIT 2 :

The major reason for the error will be in your date in WHERE clause.ie,

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('06/18/2012' AS DATE)

will be different from

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('18/06/2012' AS DATE)

CONCLUSION

In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

Replacing instances of a character in a string

My problem was that I had a list of numbers, and I only want to replace a part of that number, soy I do this:

original_list = ['08113', '09106', '19066', '17056', '17063', '17053']

# With this part I achieve my goal
cves_mod = []
for i in range(0,len(res_list)):
    cves_mod.append(res_list[i].replace(res_list[i][2:], '999'))
cves_mod

# Result
cves_mod
['08999', '09999', '19999', '17999', '17999', '17999']

How to fix Warning Illegal string offset in PHP

1.

 if(1 == @$manta_option['iso_format_recent_works']){
      $theme_img = 'recent_works_thumbnail';
 } else {
      $theme_img = 'recent_works_iso_thumbnail';
 }

2.

if(isset($manta_option['iso_format_recent_works']) && 1 == $manta_option['iso_format_recent_works']){
    $theme_img = 'recent_works_thumbnail';
} else {
    $theme_img = 'recent_works_iso_thumbnail';
}

3.

if (!empty($manta_option['iso_format_recent_works']) && $manta_option['iso_format_recent_works'] == 1){
}
else{
}

Angularjs if-then-else construction in expression

This can be done in one line.

{{corretor.isAdministrador && 'YES' || 'NÂO'}}

Usage in a td tag:

<td class="text-center">{{corretor.isAdministrador && 'Sim' || 'Não'}}</td>

Get Today's date in Java at midnight time

If you are able to add external libs to your project. I would recommend that you try out Joda-time. It has a very clever way of working with dates.

http://joda-time.sourceforge.net/

Chart.js v2 hide dataset labels

add:

Chart.defaults.global.legend.display = false;

in the starting of your script code;

Sorting a DropDownList? - C#, ASP.NET

is better if you sort the Source before Binding it to DropDwonList. but sort DropDownList.Items like this:

    Dim Lista_Items = New List(Of ListItem)

    For Each item As ListItem In ddl.Items
        Lista_Items.Add(item)
    Next

    Lista_Items.Sort(Function(x, y) String.Compare(x.Text, y.Text))

    ddl.Items.Clear()
    ddl.Items.AddRange(Lista_Items.ToArray())

(this case i sort by a string(the item's text), it could be the suplier's name, supplier's id)

the Sort() method is for every List(of ) / List<MyType>, you can use it.

Creating a div element in jQuery

I hope that helps code. :) (I use)

function generateParameterForm(fieldName, promptText, valueType) {
    //<div class="form-group">
    //<label for="yyy" class="control-label">XXX</label>
    //<input type="text" class="form-control" id="yyy" name="yyy"/>
    //</div>

    // Add new div tag
    var form = $("<div/>").addClass("form-group");

    // Add label for prompt text
    var label = $("<label/>").attr("for", fieldName).addClass("control-label").text(promptText);

    // Add text field
    var input = $("<input/>").attr("type", "text").addClass("form-control").addClass(valueType).attr("id", fieldName).attr("name", fieldName);

    // lbl and inp => form
    $(form).append(label).append(input);

    return $(form);
}

Read file from line 2 or skip header row

with open(fname) as f:
    next(f)
    for line in f:
        #do something

fstream won't create a file

You should add fstream::out to open method like this:

file.open("test.txt",fstream::out);

More information about fstream flags, check out this link: http://www.cplusplus.com/reference/fstream/fstream/open/

Remove characters before character "."

public string RemoveCharactersBeforeDot(string s)
{
 string splitted=s.Split('.');
 return splitted[splitted.Length-1]
}

Using pg_dump to only get insert statements from one table within database

Put into a script I like something like that:

#!/bin/bash
set -o xtrace # remove me after debug
TABLE=some_table_name
DB_NAME=prod_database

BASE_DIR=/var/backups/someDir
LOCATION="${BASE_DIR}/myApp_$(date +%Y%m%d_%H%M%S)"
FNAME="${LOCATION}_${DB_NAME}_${TABLE}.sql"

# Create backups directory if not exists
if [[ ! -e $BASE_DIR ]];then
       mkdir $BASE_DIR
       chown -R postgres:postgres $BASE_DIR
fi

sudo -H -u postgres pg_dump --column-inserts --data-only --table=$TABLE $DB_NAME > $FNAME
sudo gzip $FNAME

Remove blank lines with grep

Try the following:

grep -v -e '^$' foo.txt

The -e option allows regex patterns for matching.

The single quotes around ^$ makes it work for Cshell. Other shells will be happy with either single or double quotes.

UPDATE: This works for me for a file with blank lines or "all white space" (such as windows lines with "\r\n" style line endings), whereas the above only removes files with blank lines and unix style line endings:

grep -v -e '^[[:space:]]*$' foo.txt

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

Why is System.Web.Mvc not listed in Add References?

In VS Express 2012 I couldn't find System.Web.Mvc in the "assemblies" tab, but after a bit of searching I found out that I need to look into "assemblies\extensions" tab rather than the default "assemblies\framework" tab.

How do I programmatically click a link with javascript?

Simply like that :

<a id="myLink" onclick="alert('link click');">LINK 1</a>
<a id="myLink2" onclick="document.getElementById('myLink').click()">Click link 1</a>

or at page load :

<body onload="document.getElementById('myLink').click()">
...
<a id="myLink" onclick="alert('link click');">LINK 1</a>
...
</body>

expected constructor, destructor, or type conversion before ‘(’ token

The first constructor in the header should not end with a semicolon. #include <string> is missing in the header. string is not qualified with std:: in the .cpp file. Those are all simple syntax errors. More importantly: you are not using references, when you should. Also the way you use the ifstream is broken. I suggest learning C++ before trying to use it.

Let's fix this up:

//polygone.h
# if !defined(__POLYGONE_H__)
# define __POLYGONE_H__

#include <iostream>
#include <string>    

class Polygone {
public:
  // declarations have to end with a semicolon, definitions do not
  Polygone(){} // why would we needs this?
  Polygone(const std::string& fichier);
};

# endif

and

//polygone.cc
// no need to include things twice
#include "polygone.h"
#include <fstream>


Polygone::Polygone(const std::string& nom)
{
  std::ifstream fichier (nom, ios::in);


  if (fichier.is_open())
  {
    // keep the scope as tiny as possible
    std::string line;
    // getline returns the stream and streams convert to booleans
    while ( std::getline(fichier, line) )
    {
      std::cout << line << std::endl;
    }
  }
  else
  {
    std::cerr << "Erreur a l'ouverture du fichier" << std::endl;
  }
}

How do I specify local .gem files in my Gemfile?

I would unpack your gem in the application vendor folder

gem unpack your.gem --target /path_to_app/vendor/gems/

Then add the path on the Gemfile to link unpacked gem.

gem 'your', '2.0.1', :path => 'vendor/gems/your'

How can I send an HTTP POST request to a server from Excel using VBA?

Set objHTTP = CreateObject("MSXML2.ServerXMLHTTP")
URL = "http://www.somedomain.com"
objHTTP.Open "POST", URL, False
objHTTP.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"
objHTTP.send("")

Alternatively, for greater control over the HTTP request you can use WinHttp.WinHttpRequest.5.1 in place of MSXML2.ServerXMLHTTP.

How to redirect cin and cout to files?

Here is an working example of what you want to do. Read the comments to know what each line in the code does. I've tested it on my pc with gcc 4.6.1; it works fine.

#include <iostream>
#include <fstream>
#include <string>

void f()
{
    std::string line;
    while(std::getline(std::cin, line))  //input from the file in.txt
    {
        std::cout << line << "\n";   //output to the file out.txt
    }
}
int main()
{
    std::ifstream in("in.txt");
    std::streambuf *cinbuf = std::cin.rdbuf(); //save old buf
    std::cin.rdbuf(in.rdbuf()); //redirect std::cin to in.txt!

    std::ofstream out("out.txt");
    std::streambuf *coutbuf = std::cout.rdbuf(); //save old buf
    std::cout.rdbuf(out.rdbuf()); //redirect std::cout to out.txt!

    std::string word;
    std::cin >> word;           //input from the file in.txt
    std::cout << word << "  ";  //output to the file out.txt

    f(); //call function


    std::cin.rdbuf(cinbuf);   //reset to standard input again
    std::cout.rdbuf(coutbuf); //reset to standard output again

    std::cin >> word;   //input from the standard input
    std::cout << word;  //output to the standard input
}

You could save and redirect in just one line as:

auto cinbuf = std::cin.rdbuf(in.rdbuf()); //save and redirect

Here std::cin.rdbuf(in.rdbuf()) sets std::cin's buffer to in.rdbuf() and then returns the old buffer associated with std::cin. The very same can be done with std::cout — or any stream for that matter.

Hope that helps.

Differences between action and actionListener

actionListener

Use actionListener if you want have a hook before the real business action get executed, e.g. to log it, and/or to set an additional property (by <f:setPropertyActionListener>), and/or to have access to the component which invoked the action (which is available by ActionEvent argument). So, purely for preparing purposes before the real business action gets invoked.

The actionListener method has by default the following signature:

import javax.faces.event.ActionEvent;
// ...

public void actionListener(ActionEvent event) {
    // ...
}

And it's supposed to be declared as follows, without any method parentheses:

<h:commandXxx ... actionListener="#{bean.actionListener}" />

Note that you can't pass additional arguments by EL 2.2. You can however override the ActionEvent argument altogether by passing and specifying custom argument(s). The following examples are valid:

<h:commandXxx ... actionListener="#{bean.methodWithoutArguments()}" />
<h:commandXxx ... actionListener="#{bean.methodWithOneArgument(arg1)}" />
<h:commandXxx ... actionListener="#{bean.methodWithTwoArguments(arg1, arg2)}" />
public void methodWithoutArguments() {}
public void methodWithOneArgument(Object arg1) {}
public void methodWithTwoArguments(Object arg1, Object arg2) {}

Note the importance of the parentheses in the argumentless method expression. If they were absent, JSF would still expect a method with ActionEvent argument.

If you're on EL 2.2+, then you can declare multiple action listener methods via <f:actionListener binding>.

<h:commandXxx ... actionListener="#{bean.actionListener1}">
    <f:actionListener binding="#{bean.actionListener2()}" />
    <f:actionListener binding="#{bean.actionListener3()}" />
</h:commandXxx>
public void actionListener1(ActionEvent event) {}
public void actionListener2() {}
public void actionListener3() {}

Note the importance of the parentheses in the binding attribute. If they were absent, EL would confusingly throw a javax.el.PropertyNotFoundException: Property 'actionListener1' not found on type com.example.Bean, because the binding attribute is by default interpreted as a value expression, not as a method expression. Adding EL 2.2+ style parentheses transparently turns a value expression into a method expression. See also a.o. Why am I able to bind <f:actionListener> to an arbitrary method if it's not supported by JSF?


action

Use action if you want to execute a business action and if necessary handle navigation. The action method can (thus, not must) return a String which will be used as navigation case outcome (the target view). A return value of null or void will let it return to the same page and keep the current view scope alive. A return value of an empty string or the same view ID will also return to the same page, but recreate the view scope and thus destroy any currently active view scoped beans and, if applicable, recreate them.

The action method can be any valid MethodExpression, also the ones which uses EL 2.2 arguments such as below:

<h:commandXxx value="submit" action="#{bean.edit(item)}" />

With this method:

public void edit(Item item) {
    // ...
}

Note that when your action method solely returns a string, then you can also just specify exactly that string in the action attribute. Thus, this is totally clumsy:

<h:commandLink value="Go to next page" action="#{bean.goToNextpage}" />

With this senseless method returning a hardcoded string:

public String goToNextpage() {
    return "nextpage";
}

Instead, just put that hardcoded string directly in the attribute:

<h:commandLink value="Go to next page" action="nextpage" />

Please note that this in turn indicates a bad design: navigating by POST. This is not user nor SEO friendly. This all is explained in When should I use h:outputLink instead of h:commandLink? and is supposed to be solved as

<h:link value="Go to next page" outcome="nextpage" />

See also How to navigate in JSF? How to make URL reflect current page (and not previous one).


f:ajax listener

Since JSF 2.x there's a third way, the <f:ajax listener>.

<h:commandXxx ...>
    <f:ajax listener="#{bean.ajaxListener}" />
</h:commandXxx>

The ajaxListener method has by default the following signature:

import javax.faces.event.AjaxBehaviorEvent;
// ...

public void ajaxListener(AjaxBehaviorEvent event) {
    // ...
}

In Mojarra, the AjaxBehaviorEvent argument is optional, below works as good.

public void ajaxListener() {
    // ...
}

But in MyFaces, it would throw a MethodNotFoundException. Below works in both JSF implementations when you want to omit the argument.

<h:commandXxx ...>
    <f:ajax execute="@form" listener="#{bean.ajaxListener()}" render="@form" />
</h:commandXxx>

Ajax listeners are not really useful on command components. They are more useful on input and select components <h:inputXxx>/<h:selectXxx>. In command components, just stick to action and/or actionListener for clarity and better self-documenting code. Moreover, like actionListener, the f:ajax listener does not support returning a navigation outcome.

<h:commandXxx ... action="#{bean.action}">
    <f:ajax execute="@form" render="@form" />
</h:commandXxx>

For explanation on execute and render attributes, head to Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.


Invocation order

The actionListeners are always invoked before the action in the same order as they are been declared in the view and attached to the component. The f:ajax listener is always invoked before any action listener. So, the following example:

<h:commandButton value="submit" actionListener="#{bean.actionListener}" action="#{bean.action}">
    <f:actionListener type="com.example.ActionListenerType" />
    <f:actionListener binding="#{bean.actionListenerBinding()}" />
    <f:setPropertyActionListener target="#{bean.property}" value="some" />
    <f:ajax listener="#{bean.ajaxListener}" />
</h:commandButton>

Will invoke the methods in the following order:

  1. Bean#ajaxListener()
  2. Bean#actionListener()
  3. ActionListenerType#processAction()
  4. Bean#actionListenerBinding()
  5. Bean#setProperty()
  6. Bean#action()

Exception handling

The actionListener supports a special exception: AbortProcessingException. If this exception is thrown from an actionListener method, then JSF will skip any remaining action listeners and the action method and proceed to render response directly. You won't see an error/exception page, JSF will however log it. This will also implicitly be done whenever any other exception is being thrown from an actionListener. So, if you intend to block the page by an error page as result of a business exception, then you should definitely be performing the job in the action method.

If the sole reason to use an actionListener is to have a void method returning to the same page, then that's a bad one. The action methods can perfectly also return void, on the contrary to what some IDEs let you believe via EL validation. Note that the PrimeFaces showcase examples are littered with this kind of actionListeners over all place. This is indeed wrong. Don't use this as an excuse to also do that yourself.

In ajax requests, however, a special exception handler is needed. This is regardless of whether you use listener attribute of <f:ajax> or not. For explanation and an example, head to Exception handling in JSF ajax requests.

Use jQuery to navigate away from page

Other answers rightly point out that there is no need to use jQuery in order to navigate to another URL; that's why there's no jQuery function which does so!

If you're asking how to click a link via jQuery then assuming you have markup which looks like:

<a id="my-link" href="/relative/path.html">Click Me!</a>

You could click() it by executing:

$('#my-link').click();

avrdude: stk500v2_ReceiveMessage(): timeout

I was running this code from Arduino setup , got same error resolve after changing
serial port to COM13
GO TO Option
tool>> serial port>> COM132

Bootstrap 3 modal responsive

Old post. I ended up setting media queries and using max-width: YYpx; and width:auto; for each breakpoint. This will scale w/ images as well (per say you have an image that's 740px width on the md screen), the modal will scale down to 740px (excluding padding for the .modal-body, if applied)

<div class="modal fade" id="bs-button-info-modal" tabindex="-1" role="dialog" aria-labelledby="Button Information Modal">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <div class="modal-body"></div>
        </div>
    </div>
</div>

Note that I'm using SCSS, bootstrap 3.3.7, and did not make any additional edits to the _modals.scss file that _bootstrap.scss imports. The CSS below is added to an additional SCSS file and imported AFTER _bootstrap.scss.

It is also important to note that the original bootstrap styles for .modal-dialog is not set for the default 992px breakpoint, only as high as the 768px breakpoint (which has a hard set width applied width: 600px;, hence why I overrode it w/ width: auto;.

@media (min-width: $screen-sm-min) { // this is the 768px breakpoint
    .modal-dialog {
        max-width: 600px;
        width: auto;
    }
}

@media (min-width: $screen-md-min) { // this is the 992px breakpoint
    .modal-dialog { 
        max-width: 800px;
    }
}

Example below of modal being responsive with an image.

enter image description here

how to show only even or odd rows in sql server 2008?

Try this :

odd :

select * from( 
SELECT col1, col2, ROW_NUMBER() OVER(ORDER BY col1 DESC) AS 'RowNumber', 
FROM table1
) d where (RowNumber % 2) = 1 

even :

select * from( 
SELECT col1, col2, ROW_NUMBER() OVER(ORDER BY col1 DESC) AS 'RowNumber', 
FROM table1
) d where (RowNumber % 2) = 0

Using jQuery, Restricting File Size Before Uploading

It's not possible to verify the image size, width or height on the client side. You need to have this file uploaded on the server and use PHP to verify all this info. PHP has special functions like: getimagesize()

list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";

How to replace an entire line in a text file by line number

Not the greatest, but this should work:

sed -i 'Ns/.*/replacement-line/' file.txt

where N should be replaced by your target line number. This replaces the line in the original file. To save the changed text in a different file, drop the -i option:

sed 'Ns/.*/replacement-line/' file.txt > new_file.txt

Spring data jpa- No bean named 'entityManagerFactory' is defined; Injection of autowired dependencies failed

Had this issue when migrated spring boot 1.5.2 to 2.0.4. Instead of creating bean I've used @EnableAutoConfiguration in the main class and it solved my problem.

Search for a string in all tables, rows and columns of a DB

This uses no cursors or anything like that, just one dynamic query.

Also note that this uses LIKE. Since that happened to be what I needed. It works for all schemas, all tables and only query's those columns that are NVARCHAR or VARCHAR even if they have UDDT.

DECLARE @searchstring  NVARCHAR(255)
SET @searchstring = '%searchstring%'

DECLARE @sql NVARCHAR(max)

SELECT @sql = STUFF((
    SELECT ' UNION ALL SELECT ''' + TABLE_NAME + ''' AS tablename, ''' + COLUMN_NAME + ''' AS columnname, ' + COLUMN_NAME + ' AS valuename' + 
    ' FROM ' + TABLE_SCHEMA + '.' + TABLE_NAME + 
    ' WHERE ' + COLUMN_NAME + ' LIKE ''' + @searchstring + ''''
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE DATA_TYPE in ('nvarchar', 'varchar')
    FOR XML PATH('')
) ,1, 11, '')

EXEC(@sql)

The output gives you the table, column and value. Time to execute on a small database was ~3 seconds, had about 3000 results.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

The only way to do explicit scaling in CSS is to use tricks such as found here.

IE6 only, you could also use filters (check out PNGFix). But applying them automatically to the page will need javascript, though that javascript could be embedded in the CSS file.

If you are going to require javascript, then you might want to just have javascript fill in the missing value for the height by inspecting the image once the content has loaded. (Sorry I do not have a reference for this technique).

Finally, and pardon me for this soapbox, you might want to eschew IE6 support in this matter. You could add _width: auto after your width: 75px rule, so that IE6 at least renders the image reasonably, even if it is the wrong size.

I recommend the last solution simply because IE6 is on the way out: 20% and going down almost a percent a month. Also, I note that your site is recreational and in the UK. Both of these help the demographic lean to be away from IE6: IE6 usage drops nearly 40% during weekends (no citation sorry), and UK has a much lower IE6 demographic (again no citation, sorry).

Good luck!

How to determine if object is in array

I would use a generic iterator of property/value over the array. No jQuery required.

arr = [{prop1: 'val1', prop2: 'val2'}, {prop1: 'val3', prop2: 'val4'}];

objectPropInArray(arr, 'prop1', 'val3'); // <-- returns true

function objectPropInArray(list, prop, val) {
  if (list.length > 0 ) {
    for (i in list) {
      if (list[i][prop] === val) {
        return true;
      }
    }
  }
  return false;  
}

How to get equal width of input and select fields

Add this code in css:

 select, input[type="text"]{
      width:100%;
      box-sizing:border-box;
    }

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

I'd like to add one additional piece of information since the accepted answer above didn't fix my errors completely.

In my scenario, I have a parent component, which holds a child component. And that child component also contains another component.

So, my parent component's spec file need to have the declaration of the child component, AS WELL AS THE CHILD'S CHILD COMPONENT. That finally fixed the issue for me.

How to test an Internet connection with bash?

The top answer misses the fact that you can have a perfectly stable connection to your default gateway but that does not automatically mean you can actually reach something on the internet. The OP asks how he/she can test a connection with the world. So I suggest to alter the top answer by changing the gateway IP to a known IP (x.y.z.w) that is outside your LAN.

So the answer would become:

ping -q -w 1 -c 1 x.y.z.w > /dev/null && echo ok || echo error

Also removing the unfavored backticks for command substitution[1].

If you just want to make sure you are connected to the world before executing some code you can also use:

if ping -q -w 1 -c 1 x.y.z.w > /dev/null; then
    # more code
fi

Oracle find a constraint

maybe this can help..

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

jQuery: Check if special characters exists in string

You could also use the whitelist method -

var str = $('#Search').val();
var regex = /[^\w\s]/gi;

if(regex.test(str) == true) {
    alert('Your search string contains illegal characters.');
}

The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

Print the stack trace of an exception

Throwable.printStackTrace(..) can take a PrintWriter or PrintStream argument:

} catch (Exception ex) {
    ex.printStackTrace(new java.io.PrintStream(yourOutputStream));
}

That said, consider using a logger interface like SLF4J with an logging implementation like LOGBack or log4j.

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

How to Implement

It looks like iOS 8 opens up this API. Hints of such functionality are present in Beta 2.

To get something working, implement the following two methods on your UITableView's delegate to get the desired effect (see gist for an example).

- tableView:editActionsForRowAtIndexPath:
- tableView:commitEditingStyle:forRowAtIndexPath:


Known Issues

The documentation says tableView:commitEditingStyle:forRowAtIndexPath is:

"Not called for edit actions using UITableViewRowAction - the action's handler will be invoked instead."

However, the swiping doesn't work without it. Even if the method stub is blank, it still needs it, for now. This is most obviously a bug in beta 2.


Sources

https://twitter.com/marksands/status/481642991745265664 https://gist.github.com/marksands/76558707f583dbb8f870

Original Answer: https://stackoverflow.com/a/24540538/870028


Update:

Sample code with this working (In Swift): http://dropbox.com/s/0fvxosft2mq2v5m/DeleteRowExampleSwift.zip

The sample code contains this easy-to-follow method in MasterViewController.swift, and with just this method you get the behavior shown in the OP screenshot:

override func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {

    var moreRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "More", handler:{action, indexpath in
        println("MORE•ACTION");
    });
    moreRowAction.backgroundColor = UIColor(red: 0.298, green: 0.851, blue: 0.3922, alpha: 1.0);

    var deleteRowAction = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: "Delete", handler:{action, indexpath in
        println("DELETE•ACTION");
    });

    return [deleteRowAction, moreRowAction];
}

How to update Ruby with Homebrew?

To upgrade Ruby with rbenv: Per the rbenv README

  • Update first: brew upgrade rbenv ruby-build
  • See list of Ruby versions: versions available: rbenv install -l
  • Install: rbenv install <selected version>

How do I debug jquery AJAX calls?

if you are using mozilla firefox than just install an add-on called firebug.

In your page press f12 in mozilla and firebug will open.

go for the net tab in firebug and in this tab go in the xhr tab. and reload your page. you will get 5 options in xhr Params Headers Response HTML and Cookies

so by going in response and html you can see which response you are getting after your ajax call.

Please let me know if you have any issue.

How to check 'undefined' value in jQuery

I am not sure it is the best solution, but it works fine:

if($someObject['length']!=0){
    //do someting
}

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

Important note: You should only apply plugin at bottom of build.gradle (App level)

apply plugin: 'com.google.gms.google-services'

I mistakenly apply this plugin at top of the build.gradle. So I get error.

One more tips : You no need to remove even you use the 3.1.0 or above. Because google not officially announced

   classpath 'com.google.gms:google-services:3.1.0' 

How to convert map to url query string?

To improve a little bit upon @eclipse's answer: In Javaland a request parameter map is usually represented as a Map<String, String[]>, a Map<String, List<String>> or possibly some kind of MultiValueMap<String, String> which is sort of the same thing. In any case: a parameter can usually have multiple values. A Java 8 solution would therefore be something along these lines:

public String getQueryString(HttpServletRequest request, String encoding) {
    Map<String, String[]> parameters = request.getParameterMap();

    return parameters.entrySet().stream()
            .flatMap(entry -> encodeMultiParameter(entry.getKey(), entry.getValue(), encoding))
            .reduce((param1, param2) -> param1 + "&" + param2)
            .orElse("");
}

private Stream<String> encodeMultiParameter(String key, String[] values, String encoding) {
    return Stream.of(values).map(value -> encodeSingleParameter(key, value, encoding));
}

private String encodeSingleParameter(String key, String value, String encoding) {
    return urlEncode(key, encoding) + "=" + urlEncode(value, encoding);
}

private String urlEncode(String value, String encoding) {
    try {
        return URLEncoder.encode(value, encoding);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException("Cannot url encode " + value, e);
    }
}

Batch file include external file for variables

Note: I'm assuming Windows batch files as most people seem to be unaware that there are significant differences and just blindly call everything with grey text on black background DOS. Nevertheless, the first variant should work in DOS as well.

Executable configuration

The easiest way to do this is to just put the variables in a batch file themselves, each with its own set statement:

set var1=value1
set var2=value2
...

and in your main batch:

call config.cmd

Of course, that also enables variables to be created conditionally or depending on aspects of the system, so it's pretty versatile. However, arbitrary code can run there and if there is a syntax error, then your main batch will exit too. In the UNIX world this seems to be fairly common, especially for shells. And if you think about it, autoexec.bat is nothing else.

Key/value pairs

Another way would be some kind of var=value pairs in the configuration file:

var1=value1
var2=value2
...

You can then use the following snippet to load them:

for /f "delims=" %%x in (config.txt) do (set "%%x")

This utilizes a similar trick as before, namely just using set on each line. The quotes are there to escape things like <, >, &, |. However, they will themselves break when quotes are used in the input. Also you always need to be careful when further processing data in variables stored with such characters.

Generally, automatically escaping arbitrary input to cause no headaches or problems in batch files seems pretty impossible to me. At least I didn't find a way to do so yet. Of course, with the first solution you're pushing that responsibility to the one writing the config file.

How do you share code between projects/solutions in Visual Studio?

You would simply create a separate Class Library project to contain the common code. It need not be part of any solution that uses it. Reference the class library from any project that needs it.

The only trick at all is that you will need to use a file reference to reference the project, since it will not be part of the solutions that refer to it. This means that the actual output assembly will have to be placed in a location that can be accessed by anyone building a project that references it. This can be done by placing the assembly on a share, for instance.

How to link an image and target a new window

<a href="http://www.google.com" target="_blank"> //gives blank window
<img width="220" height="250" border="0" align="center"  src=""/> // show image into new window
</a>

See the code

Django ManyToMany filter()

Just restating what Tomasz said.

There are many examples of FOO__in=... style filters in the many-to-many and many-to-one tests. Here is syntax for your specific problem:

users_in_1zone = User.objects.filter(zones__id=<id1>)
# same thing but using in
users_in_1zone = User.objects.filter(zones__in=[<id1>])

# filtering on a few zones, by id
users_in_zones = User.objects.filter(zones__in=[<id1>, <id2>, <id3>])
# and by zone object (object gets converted to pk under the covers)
users_in_zones = User.objects.filter(zones__in=[zone1, zone2, zone3])

The double underscore (__) syntax is used all over the place when working with querysets.

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

EDIT: The new Design Support Library supports this and the previous method is no longer required.

This can now be achieved using the new Android Design Support Library.

You can see the Cheesesquare sample app by Chris Banes which demos all the new features.


Previous method:

Since there is no complete solution posted, here is the way I achieved the desired result.

First include a ScrimInsetsFrameLayout in your project.

/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* A layout that draws something in the insets passed to 
* {@link #fitSystemWindows(Rect)}, i.e. the area above UI chrome
* (status and navigation bars, overlay action bars).
*/
public class ScrimInsetsFrameLayout extends FrameLayout {
    private Drawable mInsetForeground;

    private Rect mInsets;
    private Rect mTempRect = new Rect();
    private OnInsetsCallback mOnInsetsCallback;

    public ScrimInsetsFrameLayout(Context context) {
        super(context);
        init(context, null, 0);
    }

    public ScrimInsetsFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public ScrimInsetsFrameLayout(
        Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.ScrimInsetsView, defStyle, 0);
        if (a == null) {
            return;
        }
        mInsetForeground = a.getDrawable(
            R.styleable.ScrimInsetsView_insetForeground);
        a.recycle();

        setWillNotDraw(true);
    }

    @Override
    protected boolean fitSystemWindows(Rect insets) {
        mInsets = new Rect(insets);
        setWillNotDraw(mInsetForeground == null);
        ViewCompat.postInvalidateOnAnimation(this);
        if (mOnInsetsCallback != null) {
            mOnInsetsCallback.onInsetsChanged(insets);
        }
        return true; // consume insets
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        int width = getWidth();
        int height = getHeight();
        if (mInsets != null && mInsetForeground != null) {
            int sc = canvas.save();
            canvas.translate(getScrollX(), getScrollY());

            // Top
            mTempRect.set(0, 0, width, mInsets.top);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Bottom
            mTempRect.set(0, height - mInsets.bottom, width, height);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Left
            mTempRect.set(
                0, 
                mInsets.top, 
                mInsets.left, 
                height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Right
            mTempRect.set(
                width - mInsets.right, 
                mInsets.top, width, 
                height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            canvas.restoreToCount(sc);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(this);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(null);
        }
    }

    /**
     * Allows the calling container to specify a callback for custom 
     * processing when insets change (i.e. when {@link #fitSystemWindows(Rect)}
     * is called. This is useful for setting padding on UI elements 
     * based on UI chrome insets (e.g. a Google Map or a ListView). 
     * When using with ListView or GridView, remember to set
     * clipToPadding to false.
     */
    public void setOnInsetsCallback(OnInsetsCallback onInsetsCallback) {
        mOnInsetsCallback = onInsetsCallback;
    }

    public static interface OnInsetsCallback {
        public void onInsetsChanged(Rect insets);
    }
}

Then create a styleable so that the insetForeground can be set.

values/attrs.xml

<declare-styleable name="ScrimInsetsView">
    <attr name="insetForeground" format="reference|color" />
</declare-styleable>

Update your activity's xml file and make sure android:fitsSystemWindows is set to true on both the DrawerLayout as well as the ScrimInsetsFrameLayout.

layout/activity_main.xml

<android.support.v4.widget.DrawerLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <!-- The main content view -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- Your main content -->

    </LinearLayout>

    <!-- The navigation drawer -->
    <com.example.app.util.ScrimInsetsFrameLayout 
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/scrimInsetsFrameLayout"
        android:layout_width="320dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/white"
        android:elevation="10dp"
        android:fitsSystemWindows="true"
        app:insetForeground="#4000">

        <!-- Your drawer content -->

    </com.example.app.util.ScrimInsetsFrameLayout>

</android.support.v4.widget.DrawerLayout>

Inside the onCreate method of your activity set the status bar background color on the drawer layout.

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // ...

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mDrawerLayout.setStatusBarBackgroundColor(
        getResources().getColor(R.color.primary_dark));
}

Finally update your app's theme so that the DrawerLayout is behind the status bar.

values-v21/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

Result:

JavaScript Nested function

Function-instantiation is allowed inside and outside of functions. Inside those functions, just like variables, the nested functions are local and therefore cannot be obtained from the outside scope.

function foo() {
    function bar() {
        return 1;
    }
    return bar();
}

foo manipulates bar within itself. bar cannot be touched from the outer scope unless it is defined in the outer scope.

So this will not work:

function foo() {
    function bar() {
        return 1;
    }
}

bar(); // throws error: bar is not defined

Meaning of ${project.basedir} in pom.xml

There are a set of available properties to all Maven projects.

From Introduction to the POM:

project.basedir: The directory that the current project resides in.

This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml file. If your POM is located inside /path/to/project/pom.xml then this property will evaluate to /path/to/project.

Some properties are also inherited from the Super POM, which is the case for project.build.directory. It is the value inside the <project><build><directory> element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory, it is:

The directory where all files generated by the build are placed. The default value is target.

This is the directory that will hold every generated file by the build.