Programs & Examples On #Ngen

The Native Image Generator (Ngen.exe) is a tool for the .NET framework that improves the performance of managed applications by creating and caching processor-specific machine code, so that just-in-time compilation is no longer necessary.

ASP.NET Core - Swashbuckle not creating swagger.json file

I had the same problem. Check http://localhost:XXXX/swagger/v1/swagger.json. If you get any a errors, fix them.

For example, I had an ambiguous route in a base controller class and I got the error: "Ambiguous HTTP method for action. Actions require an explicit HttpMethod binding for Swagger 2.0.". If you use base controllers make sure your public methods use the HttpGet/HttpPost/HttpPut/HttpDelete OR Route attributes to avoid ambiguous routes.

Then, also, I had defined both HttpGet("route") AND Route("route") attributes in the same method, which was the last issue for swagger.

Getting value from appsettings.json in .net core

    public static void GetSection()
    {
        Configuration = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json")
            .Build();

        string BConfig = Configuration.GetSection("ConnectionStrings")["BConnection"];

    }

Cannot find control with name: formControlName in angular reactive form

You should specify formGroupName for nested controls

<div class="panel panel-default" formGroupName="address"> <== add this
    <div class="panel-heading">Contact Info</div>

Plunker Example

How to enable CORS in ASP.net Core WebAPI

To expand on user8266077's answer, I found that I still needed to supply OPTIONS response for preflight requests in .NET Core 2.1-preview for my use case:

// https://stackoverflow.com/a/45844400
public class CorsMiddleware
{
  private readonly RequestDelegate _next;

  public CorsMiddleware(RequestDelegate next)
  {
    _next = next;
  }

  public async Task Invoke(HttpContext context)
  {
    context.Response.Headers.Add("Access-Control-Allow-Origin", "*");
    context.Response.Headers.Add("Access-Control-Allow-Credentials", "true");
    // Added "Accept-Encoding" to this list
    context.Response.Headers.Add("Access-Control-Allow-Headers", "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Accept-Encoding, Content-Length, Content-MD5, Date, X-Api-Version, X-File-Name");
    context.Response.Headers.Add("Access-Control-Allow-Methods", "POST,GET,PUT,PATCH,DELETE,OPTIONS");
    // New Code Starts here
    if (context.Request.Method == "OPTIONS")
    {
      context.Response.StatusCode = (int)HttpStatusCode.OK;
      await context.Response.WriteAsync(string.Empty);
    }
    // New Code Ends here

    await _next(context);
  }
}

and then enabled the middleware like so in Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
  app.UseMiddleware(typeof(CorsMiddleware));
  // ... other middleware inclusion such as ErrorHandling, Caching, etc
  app.UseMvc();
}

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.

My problem on the Browser Console:

Image Problem on Browser Console

PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)

In my case my code fix was:

//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';

@Injectable()
export class ProductosService {

  productos:any[] = [];
  cargando:boolean = true;

  constructor( private http:Http) {
    this.cargar_productos();
  }

  public cargar_productos(){

    this.cargando = true;

    this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
      .subscribe( res => {
        console.log(res.json());
        this.cargando = false;
        this.productos = res.json().productos; // Before this.productos = res.json(); 
      });
  }

}

How do I access Configuration in any class in ASP.NET Core?

I looked into the options pattern sample and saw this:

public class Startup
{
    public Startup(IConfiguration config)
    {
        // Configuration from appsettings.json has already been loaded by
        // CreateDefaultBuilder on WebHost in Program.cs. Use DI to load
        // the configuration into the Configuration property.
        Configuration = config;
    }
...
}

When adding Iconfiguration in the constructor of my class, I could access the configuration options through DI.

Example:

public class MyClass{

    private Iconfiguration _config;

    public MyClass(Iconfiguration config){
        _config = config;
    }

    ... // access _config["myAppSetting"] anywhere in this class
}

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

The error message says your DbContext(LogManagerContext ) needs a constructor which accepts a DbContextOptions. But i couldn't find such a constructor in your DbContext. So adding below constructor probably solves your problem.

    public LogManagerContext(DbContextOptions options) : base(options)
    {
    }

Edit for comment

If you don't register IHttpContextAccessor explicitly, use below code:

services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); 

This view is not constrained

Right Click in then designing part on that component in which you got error and follow these steps:

  • [for ex. if error occur in Plain Text]

[1]

Plain Text Constraint Layout > Infer Constraints:

finally error has gone

Firebase cloud messaging notification not received by device

I faced the same issue of Firebase cloud messaging not received by device.

In my case package name defined on Firebase Console Project was diferent than that the one defined on Manifest & Gradle of my Android Project.

As a result I received token correctly but no messages at all.

To sumarize, it's mandatory that Firebase Console package name and Manifest & Gradle matchs.

You must also keep in mind that to receive Messages sent from Firebase Console, App must be in background, not started neither hidden.

Add Favicon with React and Webpack

Here is all you need:

new HtmlWebpackPlugin({
    favicon: "./src/favicon.gif"
})

That is definitely after adding "favicon.gif" to the folder "src".

This will transfer the icon to your build folder and include it in your tag like this <link rel="shortcut icon" href="favicon.gif">. This is safer than just importing with copyWebpackPLugin

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

For iOS 10.x and Swift 3.x [below versions are also supported] just add the following lines in 'info.plist'

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

How to send a POST request with BODY in swift

If you are using swift4 and Alamofire v4.0 then the accepted code would look like this :

            let parameters: Parameters = [ "username" : email.text!, "password" : password.text! ]
            let urlString = "https://api.harridev.com/api/v1/login"
            let url = URL.init(string: urlString)
            Alamofire.request(url!, method: .put, parameters: parameters, encoding: JSONEncoding.default, headers: nil).responseJSON { response in
                 switch response.result
                {
                case .success(let json):
                    let jsonData = json as! Any
                    print(jsonData)
                case .failure(let error):
                    self.errorFailer(error: error)
                }
            }

How to convert a JSON string to a dictionary?

I've updated Eric D's answer for Swift 5:

 func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.data(using: .utf8) {
        do {
            let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String:AnyObject]
            return json
        } catch {
            print("Something went wrong")
        }
    }
    return nil
}

Get current scroll position of ScrollView in React Native

To get the x/y after scroll ended as the original questions was requesting, the easiest way is probably this:

<ScrollView
   horizontal={true}
   pagingEnabled={true}
   onMomentumScrollEnd={(event) => { 
      // scroll animation ended
      console.log(e.nativeEvent.contentOffset.x);
      console.log(e.nativeEvent.contentOffset.y);
   }}>
   ...content
</ScrollView>

How to disable or enable viewpager swiping in android

Disable swipe progmatically by-

    final View touchView = findViewById(R.id.Pager); 
    touchView.setOnTouchListener(new View.OnTouchListener() 
    {         
        @Override
        public boolean onTouch(View v, MotionEvent event)
        { 
           return true; 
        }
     });

and use this to swipe manually

touchView.setCurrentItem(int index);

How can I encode a string to Base64 in Swift?

Swift 4.0.3

import UIKit

extension String {

func fromBase64() -> String? {
    guard let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions(rawValue: 0)) else {
        return nil
    }

    return String(data: data as Data, encoding: String.Encoding.utf8)
}

func toBase64() -> String? {
    guard let data = self.data(using: String.Encoding.utf8) else {
        return nil
    }

    return data.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0))
    }
}

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

Swift 5

you need to use UINib method to register cell in viewDidLoad

override func viewDidLoad() 
{
    super.viewDidLoad()
    // Do any additional setup after loading the view.

    //register table view cell        
    tableView.register(UINib.init(nibName: "CustomTableViewCell", bundle: nil), forCellReuseIdentifier: "CustomTableViewCell")
}

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
            //    relationship.DeleteBehavior = DeleteBehavior.Restrict;

            modelBuilder.Entity<User>().ToTable("Users");

            modelBuilder.Entity<IdentityRole<string>>().ToTable("Roles");
            modelBuilder.Entity<IdentityUserToken<string>>().ToTable("UserTokens");
            modelBuilder.Entity<IdentityUserClaim<string>>().ToTable("UserClaims");
            modelBuilder.Entity<IdentityUserLogin<string>>().ToTable("UserLogins");
            modelBuilder.Entity<IdentityRoleClaim<string>>().ToTable("RoleClaims");
            modelBuilder.Entity<IdentityUserRole<string>>().ToTable("UserRoles");

        }
    }

Convert array to JSON string in swift

Hint: To convert an NSArray containing JSON compatible objects to an NSData object containing a JSON document, use the appropriate method of NSJSONSerialization. JSONObjectWithData is not it.

Hint 2: You rarely want that data as a string; only for debugging purposes.

Can not deserialize instance of java.lang.String out of START_ARRAY token

The error is:

Can not deserialize instance of java.lang.String out of START_ARRAY token at [Source: line: 1, column: 1095] (through reference chain: JsonGen["platforms"])

In JSON, platforms look like this:

"platforms": [
    {
        "platform": "iphone"
    },
    {
        "platform": "ipad"
    },
    {
        "platform": "android_phone"
    },
    {
        "platform": "android_tablet"
    }
]

So try change your pojo to something like this:

private List platforms;

public List getPlatforms(){
    return this.platforms;
}

public void setPlatforms(List platforms){
    this.platforms = platforms;
}

EDIT: you will need change mobile_networks too. Will look like this:

private List mobile_networks;

public List getMobile_networks() {
    return mobile_networks;
}

public void setMobile_networks(List mobile_networks) {
    this.mobile_networks = mobile_networks;
}

NSRange from Swift Range?

Possible Solution

Swift provides distance() which measures the distance between start and end that can be used to create an NSRange:

let text = "Long paragraph saying something goes here!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)

text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
    let start = distance(text.startIndex, substringRange.startIndex)
    let length = distance(substringRange.startIndex, substringRange.endIndex)
    let range = NSMakeRange(start, length)

//    println("word: \(substring) - \(d1) to \(d2)")

        if (substring == "saying") {
            attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: range)
        }
})

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

Check for the presence of words like "ad", "banner" or "popup" within your file. I removed these and it worked. Based on this post here: Failed to load resource under Chrome it seems like Ad Block Plus was the culprit in my case.

How to call a method function from another class?

In class WeatherRecord:

First import the class if they are in different package else this statement is not requires

Import <path>.ClassName



Then, just referene or call your object like:

Date d;
TempratureRange tr;
d = new Date();
tr = new TempratureRange;
//this can be done in Single Line also like :
// Date d = new Date();



But in your code you are not required to create an object to call function of Date and TempratureRange. As both of the Classes contain Static Function , you cannot call the thoes function by creating object.

Date.date(date,month,year);   // this is enough to call those static function 


Have clear concept on Object and Static functions. Click me

How to determine the current iPhone/device model?

Swift 5.3, both device & simulator updated to end of 2020

with the new iPhone 12 Mini, iPhone 12, iPhone 12 Pro , iPhone 12 Pro Max and the new latest iPad Air 9.7'' 4th gen, iPad 9.7'' 8th gen, iPad Pro 12.9'' 4th gen and iPad Pro 11'' 2nd gen. (new update with also all iPods, Apple Watches and Apple TVs)

This method detects the correct model even if it's a simulator. (The exact name for the simulator device model running in your simulator)

public enum Model : String {

//Simulator
case simulator     = "simulator/sandbox",

//iPod
iPod1              = "iPod 1",
iPod2              = "iPod 2",
iPod3              = "iPod 3",
iPod4              = "iPod 4",
iPod5              = "iPod 5",
iPod6              = "iPod 6",
iPod7              = "iPod 7",

//iPad
iPad2              = "iPad 2",
iPad3              = "iPad 3",
iPad4              = "iPad 4",
iPadAir            = "iPad Air ",
iPadAir2           = "iPad Air 2",
iPadAir3           = "iPad Air 3",
iPadAir4           = "iPad Air 4",
iPad5              = "iPad 5", //iPad 2017
iPad6              = "iPad 6", //iPad 2018
iPad7              = "iPad 7", //iPad 2019
iPad8              = "iPad 8", //iPad 2020

//iPad Mini
iPadMini           = "iPad Mini",
iPadMini2          = "iPad Mini 2",
iPadMini3          = "iPad Mini 3",
iPadMini4          = "iPad Mini 4",
iPadMini5          = "iPad Mini 5",

//iPad Pro
iPadPro9_7         = "iPad Pro 9.7\"",
iPadPro10_5        = "iPad Pro 10.5\"",
iPadPro11          = "iPad Pro 11\"",
iPadPro2_11        = "iPad Pro 11\" 2nd gen",
iPadPro12_9        = "iPad Pro 12.9\"",
iPadPro2_12_9      = "iPad Pro 2 12.9\"",
iPadPro3_12_9      = "iPad Pro 3 12.9\"",
iPadPro4_12_9      = "iPad Pro 4 12.9\"",

//iPhone
iPhone4            = "iPhone 4",
iPhone4S           = "iPhone 4S",
iPhone5            = "iPhone 5",
iPhone5S           = "iPhone 5S",
iPhone5C           = "iPhone 5C",
iPhone6            = "iPhone 6",
iPhone6Plus        = "iPhone 6 Plus",
iPhone6S           = "iPhone 6S",
iPhone6SPlus       = "iPhone 6S Plus",
iPhoneSE           = "iPhone SE",
iPhone7            = "iPhone 7",
iPhone7Plus        = "iPhone 7 Plus",
iPhone8            = "iPhone 8",
iPhone8Plus        = "iPhone 8 Plus",
iPhoneX            = "iPhone X",
iPhoneXS           = "iPhone XS",
iPhoneXSMax        = "iPhone XS Max",
iPhoneXR           = "iPhone XR",
iPhone11           = "iPhone 11",
iPhone11Pro        = "iPhone 11 Pro",
iPhone11ProMax     = "iPhone 11 Pro Max",
iPhoneSE2          = "iPhone SE 2nd gen",
iPhone12Mini       = "iPhone 12 Mini",
iPhone12           = "iPhone 12",
iPhone12Pro        = "iPhone 12 Pro",
iPhone12ProMax     = "iPhone 12 Pro Max",

// Apple Watch
AppleWatch1         = "Apple Watch 1gen",
AppleWatchS1        = "Apple Watch Series 1",
AppleWatchS2        = "Apple Watch Series 2",
AppleWatchS3        = "Apple Watch Series 3",
AppleWatchS4        = "Apple Watch Series 4",
AppleWatchS5        = "Apple Watch Series 5",
AppleWatchSE        = "Apple Watch Special Edition",
AppleWatchS6        = "Apple Watch Series 6",

//Apple TV
AppleTV1           = "Apple TV 1gen",
AppleTV2           = "Apple TV 2gen",
AppleTV3           = "Apple TV 3gen",
AppleTV4           = "Apple TV 4gen",
AppleTV_4K         = "Apple TV 4K",

unrecognized       = "?unrecognized?"
}

// #-#-#-#-#-#-#-#-#-#-#-#-#
// MARK: UIDevice extensions
// #-#-#-#-#-#-#-#-#-#-#-#-#

public extension UIDevice {

var type: Model {
    var systemInfo = utsname()
    uname(&systemInfo)
    let modelCode = withUnsafePointer(to: &systemInfo.machine) {
        $0.withMemoryRebound(to: CChar.self, capacity: 1) {
            ptr in String.init(validatingUTF8: ptr)
        }
    }

    let modelMap : [String: Model] = [

        //Simulator
        "i386"      : .simulator,
        "x86_64"    : .simulator,

        //iPod
        "iPod1,1"   : .iPod1,
        "iPod2,1"   : .iPod2,
        "iPod3,1"   : .iPod3,
        "iPod4,1"   : .iPod4,
        "iPod5,1"   : .iPod5,
        "iPod7,1"   : .iPod6,
        "iPod9,1"   : .iPod7,

        //iPad
        "iPad2,1"   : .iPad2,
        "iPad2,2"   : .iPad2,
        "iPad2,3"   : .iPad2,
        "iPad2,4"   : .iPad2,
        "iPad3,1"   : .iPad3,
        "iPad3,2"   : .iPad3,
        "iPad3,3"   : .iPad3,
        "iPad3,4"   : .iPad4,
        "iPad3,5"   : .iPad4,
        "iPad3,6"   : .iPad4,
        "iPad6,11"  : .iPad5, //iPad 2017
        "iPad6,12"  : .iPad5,
        "iPad7,5"   : .iPad6, //iPad 2018
        "iPad7,6"   : .iPad6,
        "iPad7,11"  : .iPad7, //iPad 2019
        "iPad7,12"  : .iPad7,
        "iPad11,6"  : .iPad8, //iPad 2020
        "iPad11,7"  : .iPad8,

        //iPad Mini
        "iPad2,5"   : .iPadMini,
        "iPad2,6"   : .iPadMini,
        "iPad2,7"   : .iPadMini,
        "iPad4,4"   : .iPadMini2,
        "iPad4,5"   : .iPadMini2,
        "iPad4,6"   : .iPadMini2,
        "iPad4,7"   : .iPadMini3,
        "iPad4,8"   : .iPadMini3,
        "iPad4,9"   : .iPadMini3,
        "iPad5,1"   : .iPadMini4,
        "iPad5,2"   : .iPadMini4,
        "iPad11,1"  : .iPadMini5,
        "iPad11,2"  : .iPadMini5,

        //iPad Pro
        "iPad6,3"   : .iPadPro9_7,
        "iPad6,4"   : .iPadPro9_7,
        "iPad7,3"   : .iPadPro10_5,
        "iPad7,4"   : .iPadPro10_5,
        "iPad6,7"   : .iPadPro12_9,
        "iPad6,8"   : .iPadPro12_9,
        "iPad7,1"   : .iPadPro2_12_9,
        "iPad7,2"   : .iPadPro2_12_9,
        "iPad8,1"   : .iPadPro11,
        "iPad8,2"   : .iPadPro11,
        "iPad8,3"   : .iPadPro11,
        "iPad8,4"   : .iPadPro11,
        "iPad8,9"   : .iPadPro2_11,
        "iPad8,10"  : .iPadPro2_11,
        "iPad8,5"   : .iPadPro3_12_9,
        "iPad8,6"   : .iPadPro3_12_9,
        "iPad8,7"   : .iPadPro3_12_9,
        "iPad8,8"   : .iPadPro3_12_9,
        "iPad8,11"  : .iPadPro4_12_9,
        "iPad8,12"  : .iPadPro4_12_9,

        //iPad Air
        "iPad4,1"   : .iPadAir,
        "iPad4,2"   : .iPadAir,
        "iPad4,3"   : .iPadAir,
        "iPad5,3"   : .iPadAir2,
        "iPad5,4"   : .iPadAir2,
        "iPad11,3"  : .iPadAir3,
        "iPad11,4"  : .iPadAir3,
        "iPad13,1"  : .iPadAir4,
        "iPad13,2"  : .iPadAir4,
        

        //iPhone
        "iPhone3,1" : .iPhone4,
        "iPhone3,2" : .iPhone4,
        "iPhone3,3" : .iPhone4,
        "iPhone4,1" : .iPhone4S,
        "iPhone5,1" : .iPhone5,
        "iPhone5,2" : .iPhone5,
        "iPhone5,3" : .iPhone5C,
        "iPhone5,4" : .iPhone5C,
        "iPhone6,1" : .iPhone5S,
        "iPhone6,2" : .iPhone5S,
        "iPhone7,1" : .iPhone6Plus,
        "iPhone7,2" : .iPhone6,
        "iPhone8,1" : .iPhone6S,
        "iPhone8,2" : .iPhone6SPlus,
        "iPhone8,4" : .iPhoneSE,
        "iPhone9,1" : .iPhone7,
        "iPhone9,3" : .iPhone7,
        "iPhone9,2" : .iPhone7Plus,
        "iPhone9,4" : .iPhone7Plus,
        "iPhone10,1" : .iPhone8,
        "iPhone10,4" : .iPhone8,
        "iPhone10,2" : .iPhone8Plus,
        "iPhone10,5" : .iPhone8Plus,
        "iPhone10,3" : .iPhoneX,
        "iPhone10,6" : .iPhoneX,
        "iPhone11,2" : .iPhoneXS,
        "iPhone11,4" : .iPhoneXSMax,
        "iPhone11,6" : .iPhoneXSMax,
        "iPhone11,8" : .iPhoneXR,
        "iPhone12,1" : .iPhone11,
        "iPhone12,3" : .iPhone11Pro,
        "iPhone12,5" : .iPhone11ProMax,
        "iPhone12,8" : .iPhoneSE2,
        "iPhone13,1" : .iPhone12Mini,
        "iPhone13,2" : .iPhone12,
        "iPhone13,3" : .iPhone12Pro,
        "iPhone13,4" : .iPhone12ProMax,
        
        // Apple Watch
        "Watch1,1" : .AppleWatch1,
        "Watch1,2" : .AppleWatch1,
        "Watch2,6" : .AppleWatchS1,
        "Watch2,7" : .AppleWatchS1,
        "Watch2,3" : .AppleWatchS2,
        "Watch2,4" : .AppleWatchS2,
        "Watch3,1" : .AppleWatchS3,
        "Watch3,2" : .AppleWatchS3,
        "Watch3,3" : .AppleWatchS3,
        "Watch3,4" : .AppleWatchS3,
        "Watch4,1" : .AppleWatchS4,
        "Watch4,2" : .AppleWatchS4,
        "Watch4,3" : .AppleWatchS4,
        "Watch4,4" : .AppleWatchS4,
        "Watch5,1" : .AppleWatchS5,
        "Watch5,2" : .AppleWatchS5,
        "Watch5,3" : .AppleWatchS5,
        "Watch5,4" : .AppleWatchS5,
        "Watch5,9" : .AppleWatchSE,
        "Watch5,10" : .AppleWatchSE,
        "Watch5,11" : .AppleWatchSE,
        "Watch5,12" : .AppleWatchSE,
        "Watch6,1" : .AppleWatchS6,
        "Watch6,2" : .AppleWatchS6,
        "Watch6,3" : .AppleWatchS6,
        "Watch6,4" : .AppleWatchS6,

        //Apple TV
        "AppleTV1,1" : .AppleTV1,
        "AppleTV2,1" : .AppleTV2,
        "AppleTV3,1" : .AppleTV3,
        "AppleTV3,2" : .AppleTV3,
        "AppleTV5,3" : .AppleTV4,
        "AppleTV6,2" : .AppleTV_4K
    ]

    if let model = modelMap[String.init(validatingUTF8: modelCode!)!] {
        if model == .simulator {
            if let simModelCode = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] {
                if let simModel = modelMap[String.init(validatingUTF8: simModelCode)!] {
                    return simModel
                }
            }
        }
        return model
    }
    return Model.unrecognized
  }
}

Usage: You can simply get the device model with:

let deviceType = UIDevice().type

or print the exact string with:

print("Running on: \(UIDevice().type)")
Output -> "iPhone X"

Another example with cases:

var myDefaultFontSize: CGFloat = 26.0
switch UIDevice().type {
    case .iPhoneSE, .iPhone5, .iPhone5S: print("default value")
    case .iPhone6, .iPhone7, .iPhone8, .iPhone6S, .iPhoneX: myDefaultFontSize += 4
    default: break
}

For Apple devices models visit: https://www.theiphonewiki.com/wiki/Models

Swift - encode URL

None of these answers worked for me. Our app was crashing when a url contained non-English characters.

 let unreserved = "-._~/?%$!:"
 let allowed = NSMutableCharacterSet.alphanumeric()
     allowed.addCharacters(in: unreserved)

 let escapedString = urlString.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)

Depending on the parameters of what you are trying to do, you may want to just create your own character set. The above allows for english characters, and -._~/?%$!:

How to make an HTTP request + basic auth in Swift

You provide credentials in a URLRequest instance, like this in Swift 3:

let username = "user"
let password = "pass"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()

// create the request
let url = URL(string: "http://www.example.com/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)

Or in an NSMutableURLRequest in Swift 2:

// set up the base64-encoded credentials
let username = "user"
let password = "pass"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])

// create the request
let url = NSURL(string: "http://www.example.com/")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)

NSNotificationCenter addObserver in Swift

Swift 5 & Xcode 10.2:

NotificationCenter.default.addObserver(
            self,
            selector: #selector(batteryLevelDidChangeNotification),
            name: UIDevice.batteryLevelDidChangeNotification,
            object: nil)

How to initialise a string from NSData in Swift

Objective - C

NSData *myStringData = [@"My String" dataUsingEncoding:NSUTF8StringEncoding]; 
NSString *myStringFromData = [[NSString alloc] initWithData:myStringData encoding:NSUTF8StringEncoding];
NSLog(@"My string value: %@",myStringFromData);

Swift

//This your data containing the string
   let myStringData = "My String".dataUsingEncoding(NSUTF8StringEncoding)

   //Use this method to convert the data into String
   let myStringFromData =  String(data:myStringData!, encoding: NSUTF8StringEncoding)

   print("My string value:" + myStringFromData!)

http://objectivec2swift.blogspot.in/2016/03/coverting-nsdata-to-nsstring-or-convert.html

bootstrap 3 wrap text content within div for horizontal alignment

Now Update word-wrap is replace by :

overflow-wrap:break-word;

Compatible old navigator and css 3 it's good alternative !

it's evolution of word-wrap ( since 2012... )

See more information : https://www.w3.org/TR/css-text-3/#overflow-wrap

See compatibility full : http://caniuse.com/#search=overflow-wrap

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

I have also encountered this error . Just i opened the new window ie Window -> New Window in eclipse .Then , I closed my old window. This solved my problem.

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

Stop handler.postDelayed()

You can use:

 Handler handler = new Handler()
 handler.postDelayed(new Runnable())

Or you can use:

 handler.removeCallbacksAndMessages(null);

Docs

public final void removeCallbacksAndMessages (Object token)

Added in API level 1 Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.

Or you could also do like the following:

Handler handler =  new Handler()
Runnable myRunnable = new Runnable() {
public void run() {
    // do something
}
};
handler.postDelayed(myRunnable,zeit_dauer2);

Then:

handler.removeCallbacks(myRunnable);

Docs

public final void removeCallbacks (Runnable r)

Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.

public final void removeCallbacks (Runnable r, Object token)

Edit:

Change this:

@Override
public void onClick(View v) {
    Handler handler =  new Handler();
    Runnable myRunnable = new Runnable() {

To:

@Override
public void onClick(View v) {
    handler = new Handler();
    myRunnable = new Runnable() { /* ... */}

Because you have the below. Declared before onCreate but you re-declared and then initialized it in onClick leading to a NPE.

Handler handler; // declared before onCreate
Runnable myRunnable;

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

I hit this problem because I had: project A (a desktop .exe) refer to project B (a portable .dll). A & B had different versions of JSON.Net, and so there was a loader conflict. Once I made all the versions of JSON.net the same, it worked. (This is in effect what some of the solutions above are doing - I'm just calling out why it works)

Why does my Spring Boot App always shutdown immediately after starting?

If you don't want to make your spring a web application then just add @EnableAsync or @EnableScheduling to your Starter

@EnableAsync
@SpringBootApplication
public class App {
    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

}

How can I send large messages with Kafka (over 15MB)?

You need to override the following properties:

Broker Configs($KAFKA_HOME/config/server.properties)

  • replica.fetch.max.bytes
  • message.max.bytes

Consumer Configs($KAFKA_HOME/config/consumer.properties)
This step didn't work for me. I add it to the consumer app and it was working fine

  • fetch.message.max.bytes

Restart the server.

look at this documentation for more info: http://kafka.apache.org/08/configuration.html

Error type 3 Error: Activity class {} does not exist

The App is already installed for Another user. Please try to uninstall the same app for all the user. Then try.

Or you can try after running adb command.

adb uninstall PACKAGE_NAME

where PACKAGE_NAME is the full name such as com.example.myapp

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

Check in Deployment Assembly,

I have the same error, when i generate the war file with the "maven clean install" way and deploy manualy, it works fine, but when i use the runtime enviroment (eclipse) the problems come.

The solution for me (for eclipse IDE) go to: "proyect properties" --> "Deployment Assembly" --> "Add" --> "the jar you need", in my case java "build path entries". Maybe can help a litle!

pip install from git repo branch

You used the egg files install procedure. This procedure supports installing over git, git+http, git+https, git+ssh, git+git and git+file. Some of these are mentioned.

It's good you can use branches, tags, or hashes to install.

@Steve_K noted it can be slow to install with "git+" and proposed installing via zip file:

pip install https://github.com/user/repository/archive/branch.zip

Alternatively, I suggest you may install using the .whl file if this exists.

pip install https://github.com/user/repository/archive/branch.whl

It's pretty new format, newer than egg files. It requires wheel and setuptools>=0.8 packages. You can find more in here.

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

same thing JUST happened to me with NUGET.

the following tag helped

<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="System.Web.WebPages.Razor" PublicKeyToken="31bf3856ad364e35"/>
    <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
  </dependentAssembly>

Also if this is happening on the server, I had to make sure I was running the application pool on a more "privileged account" to the file system, but I don think that's your issue here

WCF Exception: Could not find a base address that matches scheme http for the endpoint

My issue was also caused by missing https binding in IIS: Selected default website > On the far right pane selected Bindings > add > https

Choose 'IIS Express Development Certificate' and set port to 443

Send POST request using NSURLSession

You can use https://github.com/mxcl/OMGHTTPURLRQ

id config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:someID];
id session = [NSURLSession sessionWithConfiguration:config delegate:someObject delegateQueue:[NSOperationQueue new]];

OMGMultipartFormData *multipartFormData = [OMGMultipartFormData new];
[multipartFormData addFile:data1 parameterName:@"file1" filename:@"myimage1.png" contentType:@"image/png"];

NSURLRequest *rq = [OMGHTTPURLRQ POST:url:multipartFormData];

id path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"upload.NSData"];
[rq.HTTPBody writeToFile:path atomically:YES];

[[session uploadTaskWithRequest:rq fromFile:[NSURL fileURLWithPath:path]] resume];

Base64 Decoding in iOS 7+

In case you want to write fallback code, decoding from base64 has been present in iOS since the very beginning by caveat of NSURL:

NSURL *URL = [NSURL URLWithString:
      [NSString stringWithFormat:@"data:application/octet-stream;base64,%@",
           base64String]];

return [NSData dataWithContentsOfURL:URL];

HTML5 Canvas Resize (Downscale) Image High Quality?

DEMO: Resizing images with JS and HTML Canvas Demo fiddler.

You may find 3 different methods to do this resize, that will help you understand how the code is working and why.

https://jsfiddle.net/1b68eLdr/93089/

Full code of both demo, and TypeScript method that you may want to use in your code, can be found in the GitHub project.

https://github.com/eyalc4/ts-image-resizer

This is the final code:

export class ImageTools {
base64ResizedImage: string = null;

constructor() {
}

ResizeImage(base64image: string, width: number = 1080, height: number = 1080) {
    let img = new Image();
    img.src = base64image;

    img.onload = () => {

        // Check if the image require resize at all
        if(img.height <= height && img.width <= width) {
            this.base64ResizedImage = base64image;

            // TODO: Call method to do something with the resize image
        }
        else {
            // Make sure the width and height preserve the original aspect ratio and adjust if needed
            if(img.height > img.width) {
                width = Math.floor(height * (img.width / img.height));
            }
            else {
                height = Math.floor(width * (img.height / img.width));
            }

            let resizingCanvas: HTMLCanvasElement = document.createElement('canvas');
            let resizingCanvasContext = resizingCanvas.getContext("2d");

            // Start with original image size
            resizingCanvas.width = img.width;
            resizingCanvas.height = img.height;


            // Draw the original image on the (temp) resizing canvas
            resizingCanvasContext.drawImage(img, 0, 0, resizingCanvas.width, resizingCanvas.height);

            let curImageDimensions = {
                width: Math.floor(img.width),
                height: Math.floor(img.height)
            };

            let halfImageDimensions = {
                width: null,
                height: null
            };

            // Quickly reduce the size by 50% each time in few iterations until the size is less then
            // 2x time the target size - the motivation for it, is to reduce the aliasing that would have been
            // created with direct reduction of very big image to small image
            while (curImageDimensions.width * 0.5 > width) {
                // Reduce the resizing canvas by half and refresh the image
                halfImageDimensions.width = Math.floor(curImageDimensions.width * 0.5);
                halfImageDimensions.height = Math.floor(curImageDimensions.height * 0.5);

                resizingCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
                    0, 0, halfImageDimensions.width, halfImageDimensions.height);

                curImageDimensions.width = halfImageDimensions.width;
                curImageDimensions.height = halfImageDimensions.height;
            }

            // Now do final resize for the resizingCanvas to meet the dimension requirments
            // directly to the output canvas, that will output the final image
            let outputCanvas: HTMLCanvasElement = document.createElement('canvas');
            let outputCanvasContext = outputCanvas.getContext("2d");

            outputCanvas.width = width;
            outputCanvas.height = height;

            outputCanvasContext.drawImage(resizingCanvas, 0, 0, curImageDimensions.width, curImageDimensions.height,
                0, 0, width, height);

            // output the canvas pixels as an image. params: format, quality
            this.base64ResizedImage = outputCanvas.toDataURL('image/jpeg', 0.85);

            // TODO: Call method to do something with the resize image
        }
    };
}}

Converting NSString to NSDictionary / JSON

Swift 3:

if let jsonString = styleDictionary as? String {
    let objectData = jsonString.data(using: String.Encoding.utf8)
    do {
        let json = try JSONSerialization.jsonObject(with: objectData!, options: JSONSerialization.ReadingOptions.mutableContainers) 
        print(String(describing: json)) 

    } catch {
        // Handle error
        print(error)
    }
}

UICollectionView current visible cell index

This is old question but in my case...

- (void) scrollViewWillBeginDragging:(UIScrollView *)scrollView {

    _m_offsetIdx = [m_cv indexPathForCell:m_cv.visibleCells.firstObject].row;
}

- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    _m_offsetIdx = [m_cv indexPathForCell:m_cv.visibleCells.lastObject].row;
}

Exception of type 'System.OutOfMemoryException' was thrown.

This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command

start -> run -> %temp%

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

Forge's SHA-256 implementation is fast and reliable.

To run tests on several SHA-256 JavaScript implementations, go to http://brillout.github.io/test-javascript-hash-implementations/.

The results on my machine suggests forge to be the fastest implementation and also considerably faster than the Stanford Javascript Crypto Library (sjcl) mentioned in the accepted answer.

Forge is 256 KB big, but extracting the SHA-256 related code reduces the size to 4.5 KB, see https://github.com/brillout/forge-sha256

Entity Framework The underlying provider failed on Open

I got this problem while continuing execution of a unit test that calls a method that is using parallel processing.I know there are parts of EF that are not thread-safe, so I am wondering if it is a conflict where the connection is being open and closed out of sync with the operations.

My stack trace showed this:

     at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at System.Threading.Tasks.Parallel.ForWorker[TLocal](Int32 fromInclusive, Int32 toExclusive, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Func`4 bodyWithLocal, Func`1 localInit, Action`1 localFinally)
   at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IList`1 list, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
   at System.Threading.Tasks.Parallel.ForEachWorker[TSource,TLocal](IEnumerable`1 source, ParallelOptions parallelOptions, Action`1 body, Action`2 bodyWithState, Action`3 bodyWithStateAndIndex, Func`4 bodyWithStateAndLocal, Func`5 bodyWithEverything, Func`1 localInit, Action`1 localFinally)
   at System.Threading.Tasks.Parallel.ForEach[TSource](IEnumerable`1 source, Action`1 body)

So that's the clue I followed. When I went back to a single-thread foreach instead of Parallel.ForEach the issue went away.

Joey

fix java.net.SocketTimeoutException: Read timed out

Here are few pointers/suggestions for investigation

  1. I see that every time you vote, you call vote method which creates a fresh HTTP connection.
  2. This might be a problem. I would suggest to use a single HttpClient instance to post to the server. This way it wont create too many connections from the client side.
  3. At the end of everything, HttpClient needs to be shut and hence call httpclient.getConnectionManager().shutdown(); to release the resources used by the connections.

Specified argument was out of the range of valid values. Parameter name: site

When you start with a Specific Page while debugging your project, and you are using Local IIS, you might have filled a wrong value in the Specific Page textbox.

(via Project Properties > Web > Start Action > Specific Page)

Wrong configuration:

Specific Page: "http://localhost/MyApplication/Start/SpecificPage.aspx"
Project Url: "http://localhost/MyApplication"

Right configuration:

Specific Page: "/Start/SpecificPage.aspx"
Project Url: "http://localhost/MyApplication"

Note: Ignore the quotation marks.

How can I enable Assembly binding logging?

A good place to start your investigation into any failed binding is to use the "fuslogvw.exe" utility. This may give you the information you need related to the binding failure so that you don't have to go messing around with any registry values to turn binding logging on.

Fuslogvw MSDN page

The utility should be in your Microsoft SDKs folder, which would be something like this, depending on your operating system: "C:\Program Files (x86)\Microsoft SDKs\Windows\v{SDK version}A\Bin\FUSLOGVW.exe"

  1. Run this utility as Administrator, from Developer Command Prompt (as Admin) type FUSLOGVW a new screen appears

  2. Go to Settings to and select Enable all binds to disk also select Enable custom log path and select the path of the folder of your choice to store the binding log.

  3. Restart IIS.

  4. From the FUSLOGVW window click Delete all to clear the list of any previous bind failures

  5. Reproduce the binding failure in your application

  6. In the utility, click Refresh. You should then see the bind failure logged in the list.

  7. You can view information about the bind failure by selecting it in the list and clicking View Log

The first thing I look for is the path in which the application is looking for the assembly. You should also make sure the version number of the assembly in question is what you expect.

WCF Service, the type provided as the service attribute values…could not be found

Right click on the .svc file in Solution Explorer and click View Markup

 <%@ ServiceHost Language="C#" Debug="true" 
     Service="MyService.**GetHistoryInfo**" 
     CodeBehind="GetHistoryInfo.svc.cs" %>

Update the service reference where you are referring to.

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

You could also disable the cascade delete convention in global scope of your application by doing this:

modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>()
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>()

Procedure or function !!! has too many arguments specified

You invoke the function with 2 parameters (@GenId and @Description):

EXEC etl.etl_M_Update_Promo @GenID, @Description

However you have declared the function to take 1 argument:

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0

SQL Server is telling you that [etl_M_Update_Promo] only takes 1 parameter (@GenId)

You can alter the procedure to take two parameters by specifying @Description.

ALTER PROCEDURE [etl].[etl_M_Update_Promo]
    @GenId bigint = 0,
    @Description NVARCHAR(50)
AS 

.... Rest of your code.

How to use sed to extract substring

Explaining how you can use cut:

cat yourxmlfile | cut -d'"' -f2

It will 'cut' all the lines in the file based on " delimiter, and will take the 2nd field , which is what you wanted.

Create JSON object dynamically via JavaScript (Without concate strings)

JavaScript

var myObj = {
   id: "c001",
   name: "Hello Test"
}

Result(JSON)

{
   "id": "c001",
   "name": "Hello Test"
}

Jackson serialization: ignore empty values (or null)

You need to add import com.fasterxml.jackson.annotation.JsonInclude;

Add

@JsonInclude(JsonInclude.Include.NON_NULL)

on top of POJO

If you have nested POJO then

@JsonInclude(JsonInclude.Include.NON_NULL)

need to add on every values.

NOTE: JAXRS (Jersey) automatically handle this scenario 2.6 and above.

Sending an HTTP POST request on iOS

The following code describes a simple example using POST method.(How one can pass data by POST method)

Here, I describe how one can use of POST method.

1. Set post string with actual username and password.

NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"username",@"password"]; 

2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

You need to send the actual length of your data. Calculate the length of the post string.

NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 

3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string. Create URLRequest object and initialize it.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

Set the Url for which your going to send the data to that request.

[request setURL:[NSURL URLWithString:@"http://www.abcde.com/xyz/login.aspx"]]; 

Now, set HTTP method (POST or GET). Write this lines as it is in your code.

[request setHTTPMethod:@"POST"]; 

Set HTTP header field with length of the post data.

[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

Also set the Encoded value for HTTP header Field.

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

Set the HTTPBody of the urlrequest with postData.

[request setHTTPBody:postData];

4. Now, create URLConnection object. Initialize it with the URLRequest.

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

It returns the initialized url connection and begins to load the data for the url request. You can check that whether you URL connection is done properly or not using just if/else statement as below.

if(conn) {
    NSLog(@"Connection Successful");
} else {
    NSLog(@"Connection could not be made");
}

5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference. Delegate methods are as below.

// This method is used to receive the data which we get using post method.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data

// This method receives the error report in case of connection is not made to server. 
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 

// This method is used to process the data after connection has made successfully.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

Also Refer This and This documentation for POST method.

And here is best example with source code of HTTPPost Method.

How can I run code on a background thread on Android?

I want some code to run in the background continuously. I don't want to do it in a service. Is there any other way possible?

Most likely mechanizm that you are looking for is AsyncTask. It directly designated for performing background process on background Thread. Also its main benefit is that offers a few methods which run on Main(UI) Thread and make possible to update your UI if you want to annouce user about some progress in task or update UI with data retrieved from background process.

If you don't know how to start here is nice tutorial:

Note: Also there is possibility to use IntentService with ResultReceiver that works as well.

jackson deserialization json to java-objects

Your product class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.

As a side note: You should use Pascal casing for your class names. That is Product, and not product.

Can't access Eclipse marketplace

Here's the solution,

If you are a constant proxy changer like me for various reasons (university, home , workplace and so on..) you are mostly likely to get this error due to improper configuration of connection settings in the eclipse IDE. all you have to do it play around with the current settings and get it to working state. Here's how,,

1. GO TO

Window-> Preferences -> General -> Network Connection.

2. Change the Settings

Active Provider-> Manual-> and check---> HTTP, HTTPS and SOCKS

If your active provider is already set to Manual, try restoring the default (native)


That's all, restart Eclipse and you are good to go!


Remove certain characters from a string

You can use Replace function as;

REPLACE ('Your String with cityname here', 'cityname', 'xyz')
--Results
'Your String with xyz here'

If you apply this to a table column where stringColumnName, cityName both are columns of YourTable

SELECT REPLACE(stringColumnName, cityName, '')
FROM YourTable

Or if you want to remove 'cityName' string from out put of a column then

SELECT REPLACE(stringColumnName, 'cityName', '')
FROM yourTable

EDIT: Since you have given more details now, REPLACE function is not the best method to sort your problem. Following is another way of doing it. Also @MartinSmith has given a good answer. Now you have the choice to select again.

SELECT RIGHT (O.Ort, LEN(O.Ort) - LEN(C.CityName)-1) As WithoutCityName
FROM   tblOrtsteileGeo O
       JOIN dbo.Cities C
         ON C.foo = O.foo
WHERE  O.GKZ = '06440004'

How to change already compiled .class file without decompile?

Use java assist Java library for manipulating the Java bytecode (.class file) of an application.

-> Spring , Hibernate , EJB using this for proxy implementation

-> we can bytecode manipulation to do some program analysis

-> we can use Javassist to implement a transparent cache for method return values, by intercepting all method invocations and only delegating to the super implementation on the first invocation.

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

I had to delete all objects and re-add them. This seemed to have fixed the issue.

Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib

I just ran into this annoying problem today. We use SmartAssembly to pack/obfuscate our .NET assemblies, but suddenly the final product wasn't working on our test systems. I didn't even think I had .NET 4.5, but apparently something installed it about a month ago.

I uninstalled 4.5 and reinstalled 4.0, and now everything is working again. Not too impressed with having blown an afternoon on this.

Jackson - best way writes a java list to a json array

I can't find toByteArray() as @atrioom said, so I use StringWriter, please try:

public void writeListToJsonArray() throws IOException {  

    //your list
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));


    final StringWriter sw =new StringWriter();
    final ObjectMapper mapper = new ObjectMapper();
    mapper.writeValue(sw, list);
    System.out.println(sw.toString());//use toString() to convert to JSON

    sw.close(); 
}

Or just use ObjectMapper#writeValueAsString:

    final ObjectMapper mapper = new ObjectMapper();
    System.out.println(mapper.writeValueAsString(list));

Could not load file or assembly 'Microsoft.Web.Infrastructure,

I had to set "Copy Local" in the Reference Properties to False, then back to True. Doing this added the Private True setting to the .csproj file.

<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">      <HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
      <Private>True</Private>
    </Reference>

I had assumed this was already set, since the "Copy Local" showed as True.

Spring REST Service: how to configure to remove null objects in json response

If you are using Jackson 2, the message-converters tag is:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="prefixJson" value="true"/>
            <property name="supportedMediaTypes" value="application/json"/>
            <property name="objectMapper">
                <bean class="com.fasterxml.jackson.databind.ObjectMapper">
                    <property name="serializationInclusion" value="NON_NULL"/>
                </bean>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

Error Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35

I found the problem. Instead of adding a class (.cs) file by mistake I had added a Web API Controller class which added a configuration file in my solution. And that configuration file was looking for the mentioned DLL (Microsoft.Web.Infrastructure 1.0.0.0). It worked when I removed that file, cleaned the application and then published.

Best way to increase heap size in catalina.bat file

increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin

enter image description here

heap size can be changed based on Requirements.

  set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

The module was expected to contain an assembly manifest

BadImageFormatException, in my experience, is almost always to do with x86 versus x64 compiled assemblies. It sounds like your C++ assembly is compiled for x86 and you are running on an x64 process. Is that correct?

Instead of using AnyCPU/Mixed as the platform. Try to manually set it to x86 and see if it will run after that.

Hope this helps.

Detecting iOS orientation change instantly

@vimal answer did not provide solution for me. It seems the orientation is not the current orientation, but from previous orientation. To fix it, I use [[UIDevice currentDevice] orientation]

- (void)orientationChanged:(NSNotification *)notification{
    [self adjustViewsForOrientation:[[UIDevice currentDevice] orientation]];
}

Then

- (void) adjustViewsForOrientation:(UIDeviceOrientation) orientation { ... }

With this code I get the current orientation position.

string in namespace std does not name a type

You need to add:

#include <string>

In your header file.

Pass a simple string from controller to a view MVC3

Just define your action method like this

public string ThemePath()

and simply return the string itself.

Modify tick label text

One can also do this with pylab and xticks

import matplotlib
import matplotlib.pyplot as plt
x = [0,1,2]
y = [90,40,65]
labels = ['high', 'low', 37337]
plt.plot(x,y, 'r')
plt.xticks(x, labels, rotation='vertical')
plt.show()

http://matplotlib.org/examples/ticks_and_spines/ticklabels_demo_rotation.html

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

I was getting the same error after adding an unnecessary reference to System.Web.Mvc. I removed all the references I could find, but nothing seemed to work. I finally deleted the project's bin folder and the error went away after a rebuild.

Sending HTTP Post request with SOAP action using org.apache.http

... using org.apache.http api. ...

You need to include SOAPAction as a header in the request. As you have httpPost and requestWrapper handles, there are three ways adding the header.

 1. httpPost.addHeader( "SOAPAction", strReferenceToSoapActionValue );
 2. httpPost.setHeader( "SOAPAction", strReferenceToSoapActionValue );
 3. requestWrapper.setHeader( "SOAPAction", strReferenceToSoapActionValue );

Only difference is that addHeader allows multiple values with same header name and setHeader allows unique header names only. setHeader(... over writes first header with the same name.

You can go with any of these on your requirement.

SVN "Already Locked Error"

I had to do a Clean Up and elect to "Break Locks" for it to work for me.

Extend contigency table with proportions (percentages)

I made this for when doing aggregate functions and similar

per.fun <- function(x) {
    if(length(x)>1){
        denom <- length(x);
        num <- sum(x);
        percentage <- num/denom;
        percentage*100
        }
        else NA
    }

Converting from byte to int in java

if you want to combine the 4 bytes into a single int you need to do

int i= (rno[0]<<24)&0xff000000|
       (rno[1]<<16)&0x00ff0000|
       (rno[2]<< 8)&0x0000ff00|
       (rno[3]<< 0)&0x000000ff;

I use 3 special operators | is the bitwise logical OR & is the logical AND and << is the left shift

in essence I combine the 4 8-bit bytes into a single 32 bit int by shifting the bytes in place and ORing them together

I also ensure any sign promotion won't affect the result with & 0xff

Exception : javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated

Expired certificate was the cause of our "javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated".

keytool -list -v -keystore filetruststore.ts

    Enter keystore password:
    Keystore type: JKS
    Keystore provider: SUN
    Your keystore contains 1 entry
    Alias name: somealias
    Creation date: Jul 26, 2012
    Entry type: PrivateKeyEntry
    Certificate chain length: 1
    Certificate[1]:
    Owner: CN=Unknown, OU=SomeOU, O="Some Company, Inc.", L=SomeCity, ST=GA, C=US
    Issuer: CN=Unknown, OU=SomeOU, O=Some Company, Inc.", L=SomeCity, ST=GA, C=US
    Serial number: 5011a47b
    Valid from: Thu Jul 26 16:11:39 EDT 2012 until: Wed Oct 24 16:11:39 EDT 2012

How to use AND in IF Statement

If you are simply looking for the occurrence of "Miami" or "Florida" inside a string (since you put * at both ends), it's probably better to use the InStr function instead of Like. Not only are the results more predictable, but I believe you'll get better performance.

Also, VBA is not short-circuited so when you use the AND keyword, it will test both sides of the AND, regardless if the first test failed or not. In VBA, it is more optimal to use 2 if-statements in these cases, that way you aren't checking for "Florida" if you don't find "Miami".

The other advice I have is that a for-each loop is faster than a for-loop. Using .offset, you can achieve the same thing, but with better effeciency. Of course there are even better ways (like variant arrays), but those will add a layer of complexity not needed in this example.

Here is some sample code:

Sub test()

Application.ScreenUpdating = False
Dim lastRow As Long
Dim cell As Range
lastRow = Range("A" & Rows.Count).End(xlUp).Row

For Each cell In Range("A1:A" & lastRow)
    If InStr(1, cell.Value, "Miami") <> 0 Then
        If InStr(1, cell.Offset(, 3).Value, "Florida") <> 0 Then
            cell.Offset(, 2).Value = "BA"
        End If
    End If
Next

Application.ScreenUpdating = True
End Sub

I hope you find some of this helpful, and keep at it with VBA! ^^

Serializing with Jackson (JSON) - getting "No serializer found"?

Add a

getter

and a

setter

and the problem is solved.

How to use parameters with HttpPost

Generally speaking an HTTP POST assumes the content of the body contains a series of key/value pairs that are created (most usually) by a form on the HTML side. You don't set the values using setHeader, as that won't place them in the content body.

So with your second test, the problem that you have here is that your client is not creating multiple key/value pairs, it only created one and that got mapped by default to the first argument in your method.

There are a couple of options you can use. First, you could change your method to accept only one input parameter, and then pass in a JSON string as you do in your second test. Once inside the method, you then parse the JSON string into an object that would allow access to the fields.

Another option is to define a class that represents the fields of the input types and make that the only input parameter. For example

class MyInput
{
    String str1;
    String str2;

    public MyInput() { }
      //  getters, setters
 }

@POST
@Consumes({"application/json"})
@Path("create/")
public void create(MyInput in){
System.out.println("value 1 = " + in.getStr1());
System.out.println("value 2 = " + in.getStr2());
}

Depending on the REST framework you are using it should handle the de-serialization of the JSON for you.

The last option is to construct a POST body that looks like:

str1=value1&str2=value2

then add some additional annotations to your server method:

public void create(@QueryParam("str1") String str1, 
                  @QueryParam("str2") String str2)

@QueryParam doesn't care if the field is in a form post or in the URL (like a GET query).

If you want to continue using individual arguments on the input then the key is generate the client request to provide named query parameters, either in the URL (for a GET) or in the body of the POST.

How to solve error message: "Failed to map the path '/'."

These samples run in server. So either the Windows user must have READ/WRITE permissions or must run the sample in Administrator mode.

Try running the sample in Administrator mode.

How do I use a custom Serializer with Jackson?

I tried doing this too, and there is a mistake in the example code on the Jackson web page that fails to include the type (.class) in the call to addSerializer() method, which should read like this:

simpleModule.addSerializer(Item.class, new ItemSerializer());

In other words, these are the lines that instantiate the simpleModule and add the serializer (with the prior incorrect line commented out):

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule("SimpleModule", 
                                          new Version(1,0,0,null));
// simpleModule.addSerializer(new ItemSerializer());
simpleModule.addSerializer(Item.class, new ItemSerializer());
mapper.registerModule(simpleModule);

FYI: Here is the reference for the correct example code: http://wiki.fasterxml.com/JacksonFeatureModules

Http Post With Body

You can use HttpClient and HttpPost to send a json string as body:

public void post(String completeUrl, String body) {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(completeUrl);
    httpPost.setHeader("Content-type", "application/json");
    try {
        StringEntity stringEntity = new StringEntity(body);
        httpPost.getRequestLine();
        httpPost.setEntity(stringEntity);

        httpClient.execute(httpPost);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Json body example:

{
  "param1": "value 1",
  "param2": 123,
  "testStudentArray": [
    {
      "name": "Test Name 1",
      "gpa": 3.5
    },
    {
      "name": "Test Name 2",
      "gpa": 3.8
    }
  ]
}

PHP Warning: Invalid argument supplied for foreach()

Try this.

if(is_array($value) || is_object($value)){
    foreach($value as $item){
     //somecode
    }
}

Convert NSData to String?

A simple way to convert arbitrary NSData to NSString is to base64 encode it.

NSString *base64EncodedKey = [keydata base64EncodedStringWithOptions: NSDataBase64Encoding64CharacterLineLength];

You can then store it into your database for reuse later. Just decode it back to NSData.

Load resources from relative path using local html in uiwebview

This is how to load/use a local html with relative references.

  1. Drag the resource into your xcode project (I dragged a folder named www from my finder window), you will get two options "create groups for any added folders" and "create folders references for any added folders".
  2. Select the "create folder references.." option.
  3. Use the below given code. It should work like a charm.

    NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html" inDirectory:@"www"]];
    [webview loadRequest:[NSURLRequest requestWithURL:url]];

Now all your relative links(like img/.gif, js/.js) in the html should get resolved.

Swift 3

    if let path = Bundle.main.path(forResource: "dados", ofType: "html", inDirectory: "root") {
        webView.load( URLRequest(url: URL(fileURLWithPath: path)) )
    }

Converting NSData to NSString in Objective c

in objective C:

NSData *tmpData;
NSString *tmpString = [NSString stringWithFormat:@"%@", tmpData];
NSLog(tmpString)

iOS UIImagePickerController result image orientation after upload

@an0, thanks for the answer!
The only thing is autoreleasepool: 

func fixOrientation(img: UIImage) -> UIImage? {

    let result: UIImage?
    if img.imageOrientation == .up {
        result = img
    } else {

        result = autoreleasepool { () -> UIImage? in
            UIGraphicsBeginImageContextWithOptions(img.size, false, img.scale)
            let rect = CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height)
            img.draw(in: rect)

            let normalizedImage = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()

            return normalizedImage
        }
    }

    return result
}

WCF change endpoint address at runtime

We store our URLs in a database and load them at runtime.

public class ServiceClientFactory<TChannel> : ClientBase<TChannel> where TChannel : class
{
    public TChannel Create(string url)
    {
        this.Endpoint.Address = new EndpointAddress(new Uri(url));
        return this.Channel;
    }
}

Implementation

var client = new ServiceClientFactory<yourServiceChannelInterface>().Create(newUrl);

Spring configure @ResponseBody JSON format

Yes but what happens if you start using mixins for example, you cant be having ObjectMapper as a singleton because you will be applying the configuration globally. So you will be adding or setting the mixin classes on the same ObjectMapper instance?

How to format DateTime columns in DataGridView?

string stringtodate = ((DateTime)row.Cells[4].Value).ToString("MM-dd-yyyy");
textBox9.Text = stringtodate;

Trusting all certificates using HttpClient over HTTPS

There a many answers above but I wasn't able to get any of them working correctly (with my limited time), so for anyone else in the same situation you can try the code below which worked perfectly for my java testing purposes:

    public static HttpClient wrapClient(HttpClient base) {
    try {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException { }

            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    } catch (Exception ex) {
        return null;
    }
}

and call like:

DefaultHttpClient baseClient = new DefaultHttpClient();
HttpClient httpClient = wrapClient(baseClient );

Reference: http://tech.chitgoks.com/2011/04/24/how-to-avoid-javax-net-ssl-sslpeerunverifiedexception-peer-not-authenticated-problem-using-apache-httpclient/

git status shows modifications, git checkout -- <file> doesn't remove them

One proposed solution here didn't work, I found out the file was actually a link to some special characters:

% ls -l StoreLogo.png
lrwxrwxrwx 1 janus janus 8 Feb 21 10:37 StoreLogo.png -> ''$'\211''PNG'$'\r\n\032\n'

% git status    
Changes not staged for commit:
    modified:   StoreLogo.png

% git rm --cached -r StoreLogo.png
rm 'src/GWallet.Frontend.XF.UWP/Assets/StoreLogo.png'

% git reset StoreLogo.png         
Unstaged changes after reset:
M   src/GWallet.Frontend.XF.UWP/Assets/StoreLogo.png

% git status                      
Changes not staged for commit:
    modified:   StoreLogo.png

When should I use Memcache instead of Memcached?

Memcached is a newer API, it also provides memcached as a session provider which could be great if you have a farm of server.

After the version is still really low 0.2 but I have used both and I didn't encounter major problem, so I would go to memcached since it's new.

What are the most widely used C++ vector/matrix math/linear algebra libraries, and their cost and benefit tradeoffs?

I found this library quite simple and functional (http://kirillsprograms.com/top_Vectors.php). These are bare bone vectors implemented via C++ templates. No fancy stuff - just what you need to do with vectors (add, subtract multiply, dot, etc).

Could not load file or assembly 'System.Data.SQLite'

I came up with 2 quick solutions. Either work for me. I think the problem is because of permissions.

1) Instead of using the Elmah.dll file from the net-2.0 directory, I used Elmah.dll from net-1.1 .

2) Instead of keeping Elmah.dll in the project bin directory. I make a dll directory to put it in.

How to call a Web Service Method?

The current way to do this is by using the "Add Service Reference" command. If you specify "TestUploaderWebService" as the service reference name, that will generate the type TestUploaderWebService.Service1. That class will have a method named GetFileListOnWebServer, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this:

string[] files = null;
TestUploaderWebService.Service1 proxy = null;
bool success = false;
try
{
    proxy = new TestUploaderWebService.Service1();
    files = proxy.GetFileListOnWebServer();
    proxy.Close();
    success = true;
}
finally
{
    if (!success)
    {
        proxy.Abort();
    }
}

P.S. Tell your instructor to look at "Microsoft: ASMX Web Services are a “Legacy Technology”", and ask why he's teaching out of date technology.

Using Server.MapPath in external C# Classes in ASP.NET

System.Reflection.Assembly.GetAssembly(type).Location

IF the file you are trying to get is the assembly location for a type. But if the files are relative to the assembly location then you can use this with System.IO namespace to get the exact path of the file.

Objective-C: Reading a file line by line

You can use NSInputStream which has a basic implementation for file streams. You can read bytes into a buffer (read:maxLength: method). You have to scan the buffer for newlines yourself.

Use success() or complete() in AJAX call

complete executes after either the success or error callback were executed.

Maybe you should check the second parameter complete offers too. It's a String holding the type of success the ajaxCall had.

The different callbacks are described a little more in detail here jQuery.ajax( options )


I guess you missed the fact that the complete and the success function (I know inconsistent API) get different data passed in. success gets only the data, complete gets the whole XMLHttpRequest object. Of course there is no responseText property on the data string.

So if you replace complete with success you also have to replace data.responseText with data only.

success

The function gets passed two arguments: The data returned from the server, formatted according to the 'dataType' parameter, and a string describing the status.

complete

The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request.

If you need to have access to the whole XMLHttpRequest object in the success callback I suggest trying this.

var myXHR = $.ajax({
    ...
    success: function(data, status) {
        ...do whatever with myXHR; e.g. myXHR.responseText...
    },
    ...
});

How to fix "could not find a base address that matches schema http"... in WCF

There should be a way to solve this pretty easily with external config sections and an extra deployment step that drops a deployment specific external .config file into a known location. We typically use this solution to handle the different server configurations for our different deployment environments (Staging, QA, production, etc) with our "dev box" being the default if no special copy occurs.

How to wrap text of HTML button with fixed width?

I found that you can make use of the white-space CSS property:

white-space: normal;

And it will break the words as normal text.

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

In case if you are using WPF application using PRISM framework then configuration should exist in your start up project (i.e. in the project where your bootstrapper resides.)

In short just remove it from the class library and put into a start up project.

Write Array to Excel Range

add ExcelUtility class to your project and enjoy it.

ExcelUtility.cs File content:

using System;
using Microsoft.Office.Interop.Excel;

static class ExcelUtility
{
    public static void WriteArray<T>(this _Worksheet sheet, int startRow, int startColumn, T[,] array)
    {
        var row = array.GetLength(0);
        var col = array.GetLength(1);
        Range c1 = (Range) sheet.Cells[startRow, startColumn];
        Range c2 = (Range) sheet.Cells[startRow + row - 1, startColumn + col - 1];
        Range range = sheet.Range[c1, c2];
        range.Value = array;
    }

    public static bool SaveToExcel<T>(T[,] data, string path)
    {
        try
        {
            //Start Excel and get Application object.
            var oXl = new Application {Visible = false};

            //Get a new workbook.
            var oWb = (_Workbook) (oXl.Workbooks.Add(""));
            var oSheet = (_Worksheet) oWb.ActiveSheet;
            //oSheet.WriteArray(1, 1, bufferData1);

            oSheet.WriteArray(1, 1, data);

            oXl.Visible = false;
            oXl.UserControl = false;
            oWb.SaveAs(path, XlFileFormat.xlWorkbookDefault, Type.Missing,
                Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            oWb.Close(false);
            oXl.Quit();
        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }
}

usage :

var data = new[,]
{
    {11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
    {21, 22, 23, 24, 25, 26, 27, 28, 29, 30},
    {31, 32, 33, 34, 35, 36, 37, 38, 39, 40}
};

ExcelUtility.SaveToExcel(data, "test.xlsx");

Best Regards!

String representation of an Enum

Update: Visiting this page, 8 years later, after not touching C# for a long while, looks like my answer is no longer the best solution. I really like the converter solution tied with attribute-functions.

If you are reading this, please make sure you also check out other answers.
(hint: they are above this one)


As most of you, I really liked the selected answer by Jakub Šturc, but I also really hate to copy-paste code, and try to do it as little as I can.

So I decided I wanted an EnumBase class from which most of the functionality is inherited/built-in, leaving me to focus on the content instead of behavior.

The main problem with this approach is based on the fact that although Enum values are type-safe instances, the interaction is with the Static implementation of the Enum Class type. So with a little help of generics magic, I think I finally got the correct mix. Hope someone finds this as useful as I did.

I'll start with Jakub's example, but using inheritance and generics:

public sealed class AuthenticationMethod : EnumBase<AuthenticationMethod, int>
{
    public static readonly AuthenticationMethod FORMS =
        new AuthenticationMethod(1, "FORMS");
    public static readonly AuthenticationMethod WINDOWSAUTHENTICATION =
        new AuthenticationMethod(2, "WINDOWS");
    public static readonly AuthenticationMethod SINGLESIGNON =
        new AuthenticationMethod(3, "SSN");

    private AuthenticationMethod(int Value, String Name)
        : base( Value, Name ) { }
    public new static IEnumerable<AuthenticationMethod> All
    { get { return EnumBase<AuthenticationMethod, int>.All; } }
    public static explicit operator AuthenticationMethod(string str)
    { return Parse(str); }
}

And here is the base class:

using System;
using System.Collections.Generic;
using System.Linq; // for the .AsEnumerable() method call

// E is the derived type-safe-enum class
// - this allows all static members to be truly unique to the specific
//   derived class
public class EnumBase<E, T> where E: EnumBase<E, T>
{
    #region Instance code
    public T Value { get; private set; }
    public string Name { get; private set; }

    protected EnumBase(T EnumValue, string Name)
    {
        Value = EnumValue;
        this.Name = Name;
        mapping.Add(Name, this);
    }

    public override string ToString() { return Name; }
    #endregion

    #region Static tools
    static private readonly Dictionary<string, EnumBase<E, T>> mapping;
    static EnumBase() { mapping = new Dictionary<string, EnumBase<E, T>>(); }
    protected static E Parse(string name)
    {
        EnumBase<E, T> result;
        if (mapping.TryGetValue(name, out result))
        {
            return (E)result;
        }

        throw new InvalidCastException();
    }
    // This is protected to force the child class to expose it's own static
    // method.
    // By recreating this static method at the derived class, static
    // initialization will be explicit, promising the mapping dictionary
    // will never be empty when this method is called.
    protected static IEnumerable<E> All
    { get { return mapping.Values.AsEnumerable().Cast<E>(); } }
    #endregion
}

How to improve Netbeans performance?

  • Download the latest Netbeans
  • Remove all the plugins you don't need.
  • Use the latest version of Java

How do I watch a file for changes?

Simplest solution for me is using watchdog's tool watchmedo

From https://pypi.python.org/pypi/watchdog I now have a process that looks up the sql files in a directory and executes them if necessary.

watchmedo shell-command \
--patterns="*.sql" \
--recursive \
--command='~/Desktop/load_files_into_mysql_database.sh' \
.

How to resolve "Could not find schema information for the element/attribute <xxx>"?

An XSD is included with EntLib 5, and is installed in the Visual Studio schema directory. In my case, it could be found at:

"C:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas\EnterpriseLibrary.Configuration.xsd"

CONTEXT

  • Visual Studio 2010
  • Enterprise Library 5

STEPS TO REMOVE THE WARNINGS

  1. open app.config in your Visual Studio project
  2. right click in the XML Document editor, select "Properties"
  3. add the fully qualified path to the "EnterpriseLibrary.Configuration.xsd"

ASIDE

It is worth repeating that these "Error List" "Messages" ("Could not find schema information for the element") are only visible when you open the app.config file. If you "Close All Documents" and compile... no messages will be reported.

How to implement and do OCR in a C# project?

If anyone is looking into this, I've been trying different options and the following approach yields very good results. The following are the steps to get a working example:

  1. Add .NET Wrapper for tesseract to your project. It can be added via NuGet package Install-Package Tesseract(https://github.com/charlesw/tesseract).
  2. Go to the Downloads section of the official Tesseract project (https://code.google.com/p/tesseract-ocr/ EDIT: It's now located here: https://github.com/tesseract-ocr/langdata).
  3. Download the preferred language data, example: tesseract-ocr-3.02.eng.tar.gz English language data for Tesseract 3.02.
  4. Create tessdata directory in your project and place the language data files in it.
  5. Go to Properties of the newly added files and set them to copy on build.
  6. Add a reference to System.Drawing.
  7. From .NET Wrapper repository, in the Samples directory copy the sample phototest.tif file into your project directory and set it to copy on build.
  8. Create the following two files in your project (just to get started):

Program.cs

using System;
using Tesseract;
using System.Diagnostics;

namespace ConsoleApplication
{
    class Program
    {
        public static void Main(string[] args)
        {
            var testImagePath = "./phototest.tif";
            if (args.Length > 0)
            {
                testImagePath = args[0];
            }

            try
            {
                var logger = new FormattedConsoleLogger();
                var resultPrinter = new ResultPrinter(logger);
                using (var engine = new TesseractEngine(@"./tessdata", "eng", EngineMode.Default))
                {
                    using (var img = Pix.LoadFromFile(testImagePath))
                    {
                        using (logger.Begin("Process image"))
                        {
                            var i = 1;
                            using (var page = engine.Process(img))
                            {
                                var text = page.GetText();
                                logger.Log("Text: {0}", text);
                                logger.Log("Mean confidence: {0}", page.GetMeanConfidence());

                                using (var iter = page.GetIterator())
                                {
                                    iter.Begin();
                                    do
                                    {
                                        if (i % 2 == 0)
                                        {
                                            using (logger.Begin("Line {0}", i))
                                            {
                                                do
                                                {
                                                    using (logger.Begin("Word Iteration"))
                                                    {
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Block))
                                                        {
                                                            logger.Log("New block");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.Para))
                                                        {
                                                            logger.Log("New paragraph");
                                                        }
                                                        if (iter.IsAtBeginningOf(PageIteratorLevel.TextLine))
                                                        {
                                                            logger.Log("New line");
                                                        }
                                                        logger.Log("word: " + iter.GetText(PageIteratorLevel.Word));
                                                    }
                                                } while (iter.Next(PageIteratorLevel.TextLine, PageIteratorLevel.Word));
                                            }
                                        }
                                        i++;
                                    } while (iter.Next(PageIteratorLevel.Para, PageIteratorLevel.TextLine));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError(e.ToString());
                Console.WriteLine("Unexpected Error: " + e.Message);
                Console.WriteLine("Details: ");
                Console.WriteLine(e.ToString());
            }
            Console.Write("Press any key to continue . . . ");
            Console.ReadKey(true);
        }



        private class ResultPrinter
        {
            readonly FormattedConsoleLogger logger;

            public ResultPrinter(FormattedConsoleLogger logger)
            {
                this.logger = logger;
            }

            public void Print(ResultIterator iter)
            {
                logger.Log("Is beginning of block: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Block));
                logger.Log("Is beginning of para: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Para));
                logger.Log("Is beginning of text line: {0}", iter.IsAtBeginningOf(PageIteratorLevel.TextLine));
                logger.Log("Is beginning of word: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Word));
                logger.Log("Is beginning of symbol: {0}", iter.IsAtBeginningOf(PageIteratorLevel.Symbol));

                logger.Log("Block text: \"{0}\"", iter.GetText(PageIteratorLevel.Block));
                logger.Log("Para text: \"{0}\"", iter.GetText(PageIteratorLevel.Para));
                logger.Log("TextLine text: \"{0}\"", iter.GetText(PageIteratorLevel.TextLine));
                logger.Log("Word text: \"{0}\"", iter.GetText(PageIteratorLevel.Word));
                logger.Log("Symbol text: \"{0}\"", iter.GetText(PageIteratorLevel.Symbol));
            }
        }
    }
}

FormattedConsoleLogger.cs

using System;
using System.Collections.Generic;
using System.Text;
using Tesseract;

namespace ConsoleApplication
{
    public class FormattedConsoleLogger
    {
        const string Tab = "    ";
        private class Scope : DisposableBase
        {
            private int indentLevel;
            private string indent;
            private FormattedConsoleLogger container;

            public Scope(FormattedConsoleLogger container, int indentLevel)
            {
                this.container = container;
                this.indentLevel = indentLevel;
                StringBuilder indent = new StringBuilder();
                for (int i = 0; i < indentLevel; i++)
                {
                    indent.Append(Tab);
                }
                this.indent = indent.ToString();
            }

            public void Log(string format, object[] args)
            {
                var message = String.Format(format, args);
                StringBuilder indentedMessage = new StringBuilder(message.Length + indent.Length * 10);
                int i = 0;
                bool isNewLine = true;
                while (i < message.Length)
                {
                    if (message.Length > i && message[i] == '\r' && message[i + 1] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i += 2;
                    }
                    else if (message[i] == '\r' || message[i] == '\n')
                    {
                        indentedMessage.AppendLine();
                        isNewLine = true;
                        i++;
                    }
                    else
                    {
                        if (isNewLine)
                        {
                            indentedMessage.Append(indent);
                            isNewLine = false;
                        }
                        indentedMessage.Append(message[i]);
                        i++;
                    }
                }

                Console.WriteLine(indentedMessage.ToString());

            }

            public Scope Begin()
            {
                return new Scope(container, indentLevel + 1);
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    var scope = container.scopes.Pop();
                    if (scope != this)
                    {
                        throw new InvalidOperationException("Format scope removed out of order.");
                    }
                }
            }
        }

        private Stack<Scope> scopes = new Stack<Scope>();

        public IDisposable Begin(string title = "", params object[] args)
        {
            Log(title, args);
            Scope scope;
            if (scopes.Count == 0)
            {
                scope = new Scope(this, 1);
            }
            else
            {
                scope = ActiveScope.Begin();
            }
            scopes.Push(scope);
            return scope;
        }

        public void Log(string format, params object[] args)
        {
            if (scopes.Count > 0)
            {
                ActiveScope.Log(format, args);
            }
            else
            {
                Console.WriteLine(String.Format(format, args));
            }
        }

        private Scope ActiveScope
        {
            get
            {
                var top = scopes.Peek();
                if (top == null) throw new InvalidOperationException("No current scope");
                return top;
            }
        }
    }
}

C++ STL Vectors: Get iterator from index?

Actutally std::vector are meant to be used as C tab when needed. (C++ standard requests that for vector implementation , as far as I know - replacement for array in Wikipedia) For instance it is perfectly legal to do this folowing, according to me:

int main()
{

void foo(const char *);

sdt::vector<char> vec;
vec.push_back('h');
vec.push_back('e');
vec.push_back('l');
vec.push_back('l');
vec.push_back('o');
vec.push_back('/0');

foo(&vec[0]);
}

Of course, either foo must not copy the address passed as a parameter and store it somewhere, or you should ensure in your program to never push any new item in vec, or requesting to change its capacity. Or risk segmentation fault...

Therefore in your exemple it leads to

vector.insert(pos, &vec[first_index], &vec[last_index]);

Return string Input with parse.string

If you're really bent upon converting Integer to String value, I suggest use String.valueOf(YourIntegerVariable). More details can be found at: http://www.tutorialspoint.com/java/java_string_valueof.htm

Where is Developer Command Prompt for VS2013?

I'm using VS 2012, so I navigated to "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft Visual Studio 2012\Visual Studio Tools" and ran as administrator this "Developer Command Prompt for VS2012" shortcut. In command shell I pasted the suggested

aspnet_regiis -i

and as I suspected this did not yield any success on Windows 10: enter image description here

So all I needed to do was "Turn Windows Features On/Off" at Control Panel and restart my machine to effect the changes. That did resolve the issue. Thanks.

Get a list of all the files in a directory (recursive)

Newer versions of Groovy (1.7.2+) offer a JDK extension to more easily traverse over files in a directory, for example:

import static groovy.io.FileType.FILES
def dir = new File(".");
def files = [];
dir.traverse(type: FILES, maxDepth: 0) { files.add(it) };

See also [1] for more examples.

[1] http://mrhaki.blogspot.nl/2010/04/groovy-goodness-traversing-directory.html

Are there bookmarks in Visual Studio Code?

Visual Studio Code currently does not support bookmarks natively. Please add this as feature request to our Git Hub issue list (https://github.com/Microsoft/vscode).

In the meantime there are some ways to navigate around the code based on your navigation history. You can Ctrl+Tab to quickly jump to previously opened files. You can also navigate within your code based on cursor positions using Goto | Back and Goto | Forward.

How to install APK from PC?

Airdroid , android market install the app on android then go onto the computer type in the address given, type in the password given (or scan the QR code). Go to settings and under security (if your running the new ICS or Jellybean) or go to settings->apps->managment and select unknown sources(for gingerbread) then click on (I think) speed install, or something along those lines. it will be on the top of the page slightly towards the left. drag and drop as many .apks as you want then on you android just tap the install buttons that appear. Airdroid is wonderful and does a lot more than just apks.

Create a folder inside documents folder in iOS apps

I don't like "[paths objectAtIndex:0]" because if Apple adds a new folder starting with "A", "B" oder "C", the "Documents"-folder isn't the first folder in the directory.

Better:

NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

Comparison of DES, Triple DES, AES, blowfish encryption for data

enter image description here

DES is the old "data encryption standard" from the seventies.

Type of expression is ambiguous without more context Swift

The compiler can't figure out what type to make the Dictionary, because it's not homogenous. You have values of different types. The only way to get around this is to make it a [String: Any], which will make everything clunky as all hell.

return [
    "title": title,
    "is_draft": isDraft,
    "difficulty": difficulty,
    "duration": duration,
    "cost": cost,
    "user_id": userId,
    "description": description,
    "to_sell": toSell,
    "images": [imageParameters, imageToDeleteParameters].flatMap { $0 }
] as [String: Any]

This is a job for a struct. It'll vastly simplify working with this data structure.

MySQL CREATE TABLE IF NOT EXISTS in PHPmyadmin import

Depending on what you want to accomplish, you might replace INSERT with INSERT IGNORE in your file. This will avoid generating an error for the rows that you are trying to insert and already exist.

See http://dev.mysql.com/doc/refman/5.5/en/insert.html.

How to configure Docker port mapping to use Nginx as an upstream proxy?

AJB's "Option B" can be made to work by using the base Ubuntu image and setting up nginx on your own. (It didn't work when I used the Nginx image from Docker Hub.)

Here is the Docker file I used:

FROM ubuntu
RUN apt-get update && apt-get install -y nginx
RUN ln -sf /dev/stdout /var/log/nginx/access.log
RUN ln -sf /dev/stderr /var/log/nginx/error.log
RUN rm -rf /etc/nginx/sites-enabled/default
EXPOSE 80 443
COPY conf/mysite.com /etc/nginx/sites-enabled/mysite.com
CMD ["nginx", "-g", "daemon off;"]

My nginx config (aka: conf/mysite.com):

server {
    listen 80 default;
    server_name mysite.com;

    location / {
        proxy_pass http://website;
    }
}

upstream website {
    server website:3000;
}

And finally, how I start my containers:

$ docker run -dP --name website website
$ docker run -dP --name nginx --link website:website nginx

This got me up and running so my nginx pointed the upstream to the second docker container which exposed port 3000.

PHP - print all properties of an object

var_dump($obj); 

If you want more info you can use a ReflectionClass:

http://www.phpro.org/manual/language.oop5.reflection.html

installing requests module in python 2.7 windows

There are four options here:

  1. Get virtualenv set up. Each virtual environment you create will automatically have pip.

  2. Get pip set up globally.

  3. Learn how to install Python packages manually—in most cases it's as simple as download, unzip, python setup.py install, but not always.

  4. Use Christoph Gohlke's binary installers.

Attach to a processes output for viewing

I was looking for this exact same thing and found that you can do:

strace -ewrite -p $PID

It's not exactly what you needed, but it's quite close.

I tried the redirecting output, but that didn't work for me. Maybe because the process was writing to a socket, I don't know.

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

Go to "next" iteration in JavaScript forEach loop

You can simply return if you want to skip the current iteration.

Since you're in a function, if you return before doing anything else, then you have effectively skipped execution of the code below the return statement.

Python: Is there an equivalent of mid, right, and left from BASIC?

There are built-in functions in Python for "right" and "left", if you are looking for a boolean result.

str = "this_is_a_test"
left = str.startswith("this")
print(left)
> True

right = str.endswith("test")
print(right)
> True

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

YES, PUT, DELETE, HEAD etc HTTP methods are available in all modern browsers.

To be compliant with XMLHttpRequest Level 2 browsers must support these methods. To check which browsers support XMLHttpRequest Level 2 I recommend CanIUse:

http://caniuse.com/#feat=xhr2

Only Opera Mini is lacking support atm (juli '15), but Opera Mini lacks support for everything. :)

How can I change the color of AlertDialog title and the color of the line under it

If your using custom title layout then you can use it like alertDialog.setCustomTitle(customTitle);

Example

On UI thread use dialog like:

 LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
 View customTitle = inflater.inflate(R.layout.customtitlebar, null);
 AlertDialog.Builder d = new AlertDialog.Builder(this);
 d.setCustomTitle(customTitle);
 d.setMessage("Message");
 d.setNeutralButton("OK", null);
 d.show();

customtitlebar.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:background="#525f67">

    <ImageView
        android:id="@+id/icon"
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/ic_launcher"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true" >
    </ImageView>

    <TextView
        android:id="@+id/customtitlebar"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:textColor="#ffffff"
        android:text="Title Name"
        android:padding="3px"
        android:textStyle="bold" 
        android:layout_toRightOf="@id/icon"
        android:layout_alignParentTop="true"
        android:gravity="center_vertical"/>

     <ImageView
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="#ff0000" 
        android:layout_below="@id/icon"><!-- This is line below the title -->
    </ImageView>

</RelativeLayout>

change image opacity using javascript

In fact, you need to use CSS.

document.getElementById("myDivId").setAttribute("style","opacity:0.5; -moz-opacity:0.5; filter:alpha(opacity=50)");

It works on FireFox, Chrome and IE.

how to detect search engine bots with php?

I'm using this to detect bots:

if (preg_match('/bot|crawl|curl|dataprovider|search|get|spider|find|java|majesticsEO|google|yahoo|teoma|contaxe|yandex|libwww-perl|facebookexternalhit/i', $_SERVER['HTTP_USER_AGENT'])) {
    // is bot
}

In addition I use a whitelist to block unwanted bots:

if (preg_match('/apple|baidu|bingbot|facebookexternalhit|googlebot|-google|ia_archiver|msnbot|naverbot|pingdom|seznambot|slurp|teoma|twitter|yandex|yeti/i', $_SERVER['HTTP_USER_AGENT'])) {
    // allowed bot
}

An unwanted bot (= false-positive user) is then able to solve a captcha to unblock himself for 24 hours. And as no one solves this captcha, I know it does not produce false-positives. So the bot detection seem to work perfectly.

Note: My whitelist is based on Facebooks robots.txt.

Creating a copy of a database in PostgreSQL

If you want to copy whole schema you can make a pg_dump with following command:

pg_dump -h database.host.com -d database_name -n schema_name -U database_user --password

And when you want to import that dump, you can use:

psql "host=database.host.com user=database_user password=database_password dbname=database_name options=--search_path=schema_name" -f sql_dump_to_import.sql

More info about connection strings: https://www.postgresql.org/docs/current/libpq-connect.html#LIBPQ-CONNSTRING

Or then just combining it in one liner:

pg_dump -h database.host.com -d postgres -n schema_name -U database_user --password | psql "host=database.host.com user=database_user password=database_password dbname=database_name options=--search_path=schema_name”

How to set connection timeout with OkHttp

Adding in gradle file and sync project:

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.google.code.gson:gson:2.6.2'

Adding in Java class:

import okhttp3.OkHttpClient;
import okhttp3.OkHttpClient.Builder;


Builder b = new Builder();
b.readTimeout(200, TimeUnit.MILLISECONDS);
b.writeTimeout(600, TimeUnit.MILLISECONDS);
// set other properties

OkHttpClient client = b.build();

How to calculate age in T-SQL with years, months, and days

Are you trying to calculate the total days/months/years of an age? do you have a starting date? Or are you trying to dissect it (ex: 24 years, 1 month, 29 days)?

If you have a start date that you're working with, datediff will output the total days/months/years with the following commands:

Select DateDiff(d,'1984-07-12','2008-09-11')

Select DateDiff(m,'1984-07-12','2008-09-11')

Select DateDiff(yyyy,'1984-07-12','2008-09-11')

with the respective outputs being (8827/290/24).

Now, if you wanted to do the dissection method, you'd have to subtract the number of years in days (days - 365*years), and then do further math on that to get the months, etc.

make arrayList.toArray() return more specific types

It doesn't really need to return Object[], for example:-

    List<Custom> list = new ArrayList<Custom>();
    list.add(new Custom(1));
    list.add(new Custom(2));

    Custom[] customs = new Custom[list.size()];
    list.toArray(customs);

    for (Custom custom : customs) {
        System.out.println(custom);
    }

Here's my Custom class:-

public class Custom {
    private int i;

    public Custom(int i) {
        this.i = i;
    }

    @Override
    public String toString() {
        return String.valueOf(i);
    }
}

Behaviour of increment and decrement operators in Python

When you want to increment or decrement, you typically want to do that on an integer. Like so:

b++

But in Python, integers are immutable. That is you can't change them. This is because the integer objects can be used under several names. Try this:

>>> b = 5
>>> a = 5
>>> id(a)
162334512
>>> id(b)
162334512
>>> a is b
True

a and b above are actually the same object. If you incremented a, you would also increment b. That's not what you want. So you have to reassign. Like this:

b = b + 1

Or simpler:

b += 1

Which will reassign b to b+1. That is not an increment operator, because it does not increment b, it reassigns it.

In short: Python behaves differently here, because it is not C, and is not a low level wrapper around machine code, but a high-level dynamic language, where increments don't make sense, and also are not as necessary as in C, where you use them every time you have a loop, for example.

How to check if a variable is not null?

There is another possible scenario I have just come across.

I did an ajax call and got data back as null, in a string format. I had to check it like this:

if(value != 'null'){}

So, null was a string which read "null" rather than really being null.

EDIT: It should be understood that I'm not selling this as the way it should be done. I had a scenario where this was the only way it could be done. I'm not sure why... perhaps the guy who wrote the back-end was presenting the data incorrectly, but regardless, this is real life. It's frustrating to see this down-voted by someone who understands that it's not quite right, and then up-voted by someone it actually helps.

Reducing video size with same format and reducing frame size

There is an application for both Mac & Windows call Handbrake, i know this isn't command line stuff but for a quick open file - select output file format & rough output size whilst keeping most of the good stuff about the video then this is good, it's a just a graphical view of ffmpeg at its best ... It does support command line input for those die hard texters.. https://handbrake.fr/downloads.php

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

Load CSV file with Spark

If you are having any one or more row(s) with less or more number of columns than 2 in the dataset then this error may arise.

I am also new to Pyspark and trying to read CSV file. Following code worked for me:

In this code I am using dataset from kaggle the link is: https://www.kaggle.com/carrie1/ecommerce-data

1. Without mentioning the schema:

from pyspark.sql import SparkSession  
scSpark = SparkSession \
    .builder \
    .appName("Python Spark SQL basic example: Reading CSV file without mentioning schema") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

sdfData = scSpark.read.csv("data.csv", header=True, sep=",")
sdfData.show()

Now check the columns: sdfData.columns

Output will be:

['InvoiceNo', 'StockCode','Description','Quantity', 'InvoiceDate', 'CustomerID', 'Country']

Check the datatype for each column:

sdfData.schema
StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,StringType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,StringType,true),StructField(CustomerID,StringType,true),StructField(Country,StringType,true)))

This will give the data frame with all the columns with datatype as StringType

2. With schema: If you know the schema or want to change the datatype of any column in the above table then use this (let's say I am having following columns and want them in a particular data type for each of them)

from pyspark.sql import SparkSession  
from pyspark.sql.types import StructType, StructField
from pyspark.sql.types import DoubleType, IntegerType, StringType
    schema = StructType([\
        StructField("InvoiceNo", IntegerType()),\
        StructField("StockCode", StringType()), \
        StructField("Description", StringType()),\
        StructField("Quantity", IntegerType()),\
        StructField("InvoiceDate", StringType()),\
        StructField("CustomerID", DoubleType()),\
        StructField("Country", StringType())\
    ])

scSpark = SparkSession \
    .builder \
    .appName("Python Spark SQL example: Reading CSV file with schema") \
    .config("spark.some.config.option", "some-value") \
    .getOrCreate()

sdfData = scSpark.read.csv("data.csv", header=True, sep=",", schema=schema)

Now check the schema for datatype of each column:

sdfData.schema

StructType(List(StructField(InvoiceNo,IntegerType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(CustomerID,DoubleType,true),StructField(Country,StringType,true)))

Edited: We can use the following line of code as well without mentioning schema explicitly:

sdfData = scSpark.read.csv("data.csv", header=True, inferSchema = True)
sdfData.schema

The output is:

StructType(List(StructField(InvoiceNo,StringType,true),StructField(StockCode,StringType,true),StructField(Description,StringType,true),StructField(Quantity,IntegerType,true),StructField(InvoiceDate,StringType,true),StructField(UnitPrice,DoubleType,true),StructField(CustomerID,IntegerType,true),StructField(Country,StringType,true)))

The output will look like this:

sdfData.show()

+---------+---------+--------------------+--------+--------------+----------+-------+
|InvoiceNo|StockCode|         Description|Quantity|   InvoiceDate|CustomerID|Country|
+---------+---------+--------------------+--------+--------------+----------+-------+
|   536365|   85123A|WHITE HANGING HEA...|       6|12/1/2010 8:26|      2.55|  17850|
|   536365|    71053| WHITE METAL LANTERN|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|   84406B|CREAM CUPID HEART...|       8|12/1/2010 8:26|      2.75|  17850|
|   536365|   84029G|KNITTED UNION FLA...|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|   84029E|RED WOOLLY HOTTIE...|       6|12/1/2010 8:26|      3.39|  17850|
|   536365|    22752|SET 7 BABUSHKA NE...|       2|12/1/2010 8:26|      7.65|  17850|
|   536365|    21730|GLASS STAR FROSTE...|       6|12/1/2010 8:26|      4.25|  17850|
|   536366|    22633|HAND WARMER UNION...|       6|12/1/2010 8:28|      1.85|  17850|
|   536366|    22632|HAND WARMER RED P...|       6|12/1/2010 8:28|      1.85|  17850|
|   536367|    84879|ASSORTED COLOUR B...|      32|12/1/2010 8:34|      1.69|  13047|
|   536367|    22745|POPPY'S PLAYHOUSE...|       6|12/1/2010 8:34|       2.1|  13047|
|   536367|    22748|POPPY'S PLAYHOUSE...|       6|12/1/2010 8:34|       2.1|  13047|
|   536367|    22749|FELTCRAFT PRINCES...|       8|12/1/2010 8:34|      3.75|  13047|
|   536367|    22310|IVORY KNITTED MUG...|       6|12/1/2010 8:34|      1.65|  13047|
|   536367|    84969|BOX OF 6 ASSORTED...|       6|12/1/2010 8:34|      4.25|  13047|
|   536367|    22623|BOX OF VINTAGE JI...|       3|12/1/2010 8:34|      4.95|  13047|
|   536367|    22622|BOX OF VINTAGE AL...|       2|12/1/2010 8:34|      9.95|  13047|
|   536367|    21754|HOME BUILDING BLO...|       3|12/1/2010 8:34|      5.95|  13047|
|   536367|    21755|LOVE BUILDING BLO...|       3|12/1/2010 8:34|      5.95|  13047|
|   536367|    21777|RECIPE BOX WITH M...|       4|12/1/2010 8:34|      7.95|  13047|
+---------+---------+--------------------+--------+--------------+----------+-------+
only showing top 20 rows

How to get MAC address of client using PHP?

To get client's device ip and mac address

{
    if (isset($_SERVER['HTTP_CLIENT_IP']))
        $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
    else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_X_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
    else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
    else if(isset($_SERVER['HTTP_FORWARDED']))
        $ipaddress = $_SERVER['HTTP_FORWARDED'];
    else if(isset($_SERVER['REMOTE_ADDR']))
        $ipaddress = $_SERVER['REMOTE_ADDR'];
    else
        $ipaddress = 'UNKNOWN';

    $macCommandString   =   "arp " . $ipaddress . " | awk 'BEGIN{ i=1; } { i++; if(i==3) print $3 }'";

    $mac = exec($macCommandString);

    return ['ip' => $ipaddress, 'mac' => $mac];
}

How to generate a core dump in Linux on a segmentation fault?

As explained above the real question being asked here is how to enable core dumps on a system where they are not enabled. That question is answered here.

If you've come here hoping to learn how to generate a core dump for a hung process, the answer is

gcore <pid>

if gcore is not available on your system then

kill -ABRT <pid>

Don't use kill -SEGV as that will often invoke a signal handler making it harder to diagnose the stuck process

Format numbers in thousands (K) in Excel

The examples above use a 'K' an uppercase k used to represent kilo or 1000. According to wiki, kilo or 1000's should be represented in lower case. So, rather than £300K, use £300k or in a code example :-

[>=1000]£#,##0,"k";[red][<=-1000]-£#,##0,"k";0

How do I get just the date when using MSSQL GetDate()?

For SQL Server 2008, the best and index friendly way is

DELETE from Table WHERE Date > CAST(GETDATE() as DATE);

For prior SQL Server versions, date maths will work faster than a convert to varchar. Even converting to varchar can give you the wrong result, because of regional settings.

DELETE from Table WHERE Date > DATEDIFF(d, 0, GETDATE());

Note: it is unnecessary to wrap the DATEDIFF with another DATEADD

How to get a MemoryStream from a Stream in .NET?

You can simply do:

var ms = new MemoryStream(File.ReadAllBytes(filePath));

Stream position is 0 and ready to use.

How to print color in console using System.out.println?

Emoji

You can use colors for text as others mentioned in their answers.

But you can use emojis instead! for example you can use You can use ?? for warning messages and for error messages.

Or simply use these note books as a color:

: error message
: warning message
: ok status message
: action message
: canceled status message
: Or anything you like and want to recognize immediately by color

Bonus:

This method also helps you to quickly scan and find logs directly in the source code.

But linux and Windows CMD default emoji font is not colorful by default and you may want to make them colorful, first.

How can I tell if a Java integer is null?

Try this:

Integer startIn = null;

try {
  startIn = Integer.valueOf(startField.getText());
} catch (NumberFormatException e) {
  .
  .
  .
}

if (startIn == null) {
  // Prompt for value...
}

How to produce an csv output file from stored procedure in SQL Server

Just to answer a native way to do this that finally worked, everything had to be casted as a varchar

ALTER PROCEDURE [clickpay].[sp_GetDocuments] 

@Submid bigint

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
   DECLARE @raw_sql varchar(max)

DECLARE @columnHeader VARCHAR(max)
SELECT @columnHeader = COALESCE(@columnHeader+',' ,'')+ ''''+column_name +'''' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documents'

DECLARE @ColumnList VARCHAR(max)
SELECT @ColumnList = COALESCE(@ColumnList+',' ,'')+ 'CAST('+column_name +' AS VARCHAR)' FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Documents'

SELECT @raw_sql = 'SELECT '+ @columnHeader +' UNION ALL SELECT ' + @ColumnList + ' FROM ' + 'Documents where Submid = ' +  CAST(@Submid AS VARCHAR)

-- Insert statements for procedure here
exec(@raw_sql)
END

HTML text-overflow ellipsis detection

All the solutions did not really work for me, what did work was compare the elements scrollWidth to the scrollWidth of its parent (or child, depending on which element has the trigger).

When the child's scrollWidth is higher than its parents, it means .text-ellipsis is active.


When event is the parent element

function isEllipsisActive(event) {
    let el          = event.currentTarget;
    let width       = el.offsetWidth;
    let widthChild  = el.firstChild.offsetWidth;
    return (widthChild >= width);
}

When event is the child element

function isEllipsisActive(event) {
    let el          = event.currentTarget;
    let width       = el.offsetWidth;
    let widthParent = el.parentElement.scrollWidth;
    return (width >= widthParent);
}

Why don't self-closing script elements work?

Internet Explorer 8 and older don't support the proper MIME type for XHTML, application/xhtml+xml. If you're serving XHTML as text/html, which you have to for these older versions of Internet Explorer to do anything, it will be interpreted as HTML 4.01. You can only use the short syntax with any element that permits the closing tag to be omitted. See the HTML 4.01 Specification.

The XML 'short form' is interpreted as an attribute named /, which (because there is no equals sign) is interpreted as having an implicit value of "/". This is strictly wrong in HTML 4.01 - undeclared attributes are not permitted - but browsers will ignore it.

IE9 and later support XHTML 5 served with application/xhtml+xml.

How to compress an image via Javascript in the browser?

i improved the function a head to be this :

var minifyImg = function(dataUrl,newWidth,imageType="image/jpeg",resolve,imageArguments=0.7){
    var image, oldWidth, oldHeight, newHeight, canvas, ctx, newDataUrl;
    (new Promise(function(resolve){
      image = new Image(); image.src = dataUrl;
      log(image);
      resolve('Done : ');
    })).then((d)=>{
      oldWidth = image.width; oldHeight = image.height;
      log([oldWidth,oldHeight]);
      newHeight = Math.floor(oldHeight / oldWidth * newWidth);
      log(d+' '+newHeight);

      canvas = document.createElement("canvas");
      canvas.width = newWidth; canvas.height = newHeight;
      log(canvas);
      ctx = canvas.getContext("2d");
      ctx.drawImage(image, 0, 0, newWidth, newHeight);
      //log(ctx);
      newDataUrl = canvas.toDataURL(imageType, imageArguments);
      resolve(newDataUrl);
    });
  };

the use of it :

minifyImg(<--DATAURL_HERE-->,<--new width-->,<--type like image/jpeg-->,(data)=>{
   console.log(data); // the new DATAURL
});

enjoy ;)

How does the compilation/linking process work?

The compilation of a C++ program involves three steps:

  1. Preprocessing: the preprocessor takes a C++ source code file and deals with the #includes, #defines and other preprocessor directives. The output of this step is a "pure" C++ file without pre-processor directives.

  2. Compilation: the compiler takes the pre-processor's output and produces an object file from it.

  3. Linking: the linker takes the object files produced by the compiler and produces either a library or an executable file.

Preprocessing

The preprocessor handles the preprocessor directives, like #include and #define. It is agnostic of the syntax of C++, which is why it must be used with care.

It works on one C++ source file at a time by replacing #include directives with the content of the respective files (which is usually just declarations), doing replacement of macros (#define), and selecting different portions of text depending of #if, #ifdef and #ifndef directives.

The preprocessor works on a stream of preprocessing tokens. Macro substitution is defined as replacing tokens with other tokens (the operator ## enables merging two tokens when it makes sense).

After all this, the preprocessor produces a single output that is a stream of tokens resulting from the transformations described above. It also adds some special markers that tell the compiler where each line came from so that it can use those to produce sensible error messages.

Some errors can be produced at this stage with clever use of the #if and #error directives.

Compilation

The compilation step is performed on each output of the preprocessor. The compiler parses the pure C++ source code (now without any preprocessor directives) and converts it into assembly code. Then invokes underlying back-end(assembler in toolchain) that assembles that code into machine code producing actual binary file in some format(ELF, COFF, a.out, ...). This object file contains the compiled code (in binary form) of the symbols defined in the input. Symbols in object files are referred to by name.

Object files can refer to symbols that are not defined. This is the case when you use a declaration, and don't provide a definition for it. The compiler doesn't mind this, and will happily produce the object file as long as the source code is well-formed.

Compilers usually let you stop compilation at this point. This is very useful because with it you can compile each source code file separately. The advantage this provides is that you don't need to recompile everything if you only change a single file.

The produced object files can be put in special archives called static libraries, for easier reusing later on.

It's at this stage that "regular" compiler errors, like syntax errors or failed overload resolution errors, are reported.

Linking

The linker is what produces the final compilation output from the object files the compiler produced. This output can be either a shared (or dynamic) library (and while the name is similar, they haven't got much in common with static libraries mentioned earlier) or an executable.

It links all the object files by replacing the references to undefined symbols with the correct addresses. Each of these symbols can be defined in other object files or in libraries. If they are defined in libraries other than the standard library, you need to tell the linker about them.

At this stage the most common errors are missing definitions or duplicate definitions. The former means that either the definitions don't exist (i.e. they are not written), or that the object files or libraries where they reside were not given to the linker. The latter is obvious: the same symbol was defined in two different object files or libraries.

Python: Assign print output to a variable

To answer the question more generaly how to redirect standard output to a variable ?

do the following :

from io import StringIO
import sys

result = StringIO()
sys.stdout = result
result_string = result.getvalue()

If you need to do that only in some function do the following :

old_stdout = sys.stdout  

# your function containing the previous lines
my_function()

sys.stdout = old_stdout

CSS Background image not loading

I'd like to share my debugging process because I was stuck on this issue for at least an hour. Image could not be found when running local host. To add some context, I am styling within a rails app in the following directory:

apps/assets/stylesheets/main.scss

I wanted to render background image in header tag. The following was my original implementation.

header {
    text-align: center;
    background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
              url('../images/header.jpg') no-repeat;
              background-blend-mode: multiply;
              background-size: cover;
}

...as a result I was getting the following error in rails server and the console in Chrome dev tools, respectively:

ActionController::RoutingError (No route matches [GET] "/images/header.jpg")
GET http://localhost:3000/images/header.jpg 404 (Not Found)

I tried different variations of the url:

url('../images/header.jpg') # DID NOT WORK
url('/../images/header.jpg') # DID NOT WORK
url('./../images/header.jpg') # DID NOT WORK

and it still did not work. At that point, I was very confused...I decided to move the image folder from the assets directory (which is the default) to within the stylesheets directory, and tried the following variations of the url:

url('/images/header.jpg') # DID NOT WORK
url('./images/header.jpg') # WORKED
url('images/header.jpg') # WORKED

I no longer got the console and rails server error. But the image still was not showing for some reason. After temporarily giving up, I found out the solution to this was to add a height property in order for the image to be shown...

header {
    text-align: center;
    height: 390px;
    background: linear-gradient(90deg, #d4eece, #d4eece, #d4eece),
              url('images/header.jpg') no-repeat;
              background-blend-mode: multiply;
              background-size: cover;
}

Unfortunately, I am still not sure why the 3 initial url attempts with "../images/header.jpg" did not work on localhost, or when I should or shouldn't be adding a period at the beginning of the url.

It might have something to do with how the default link tag is setup in application.html.erb, or maybe it's a .scss vs .css thing. Or, maybe that's just how the background property with url() works (the image needs to be within same directory as the css file)? Anyhow, this is how I solved the issue with CSS background image not loading on localhost.

Use Ant for running program with command line arguments

Extending Richard Cook's answer.

Here's the ant task to run any program (including, but not limited to Java programs):

<target name="run">
   <exec executable="name-of-executable">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </exec>
</target>

Here's the task to run a Java program from a .jar file:

<target name="run-java">
   <java jar="path for jar">
      <arg value="${arg0}"/>
      <arg value="${arg1}"/>
   </java>
</target>

You can invoke either from the command line like this:

ant -Darg0=Hello -Darg1=World run

Make sure to use the -Darg syntax; if you ran this:

ant run arg0 arg1

then ant would try to run targets arg0 and arg1.

Playing MP4 files in Firefox using HTML5 video

This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.

Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:

http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/

How do I use spaces in the Command Prompt?

set "CMD=C:\Program Files (x86)\PDFtk\bin\pdftk"
echo cmd /K ""%CMD%" %D% output trimmed.pdf"
start cmd /K ""%CMD%" %D% output trimmed.pdf"

this worked for me in a batch file

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

How to select specific columns in laravel eloquent

You can use Table::select ('name', 'surname')->where ('id', 1)->get ().

Keep in mind that when selecting for only certain fields, you will have to make another query if you end up accessing those other fields later in the request (that may be obvious, just wanted to include that caveat). Including the id field is usually a good idea so laravel knows how to write back any updates you do to the model instance.

Create mysql table directly from CSV file using the CSV Storage engine?

There is an easier way if you are using phpMyAdmin as your MySQL front end:

  1. Create a database with the default settings.
  2. Select the database.
  3. Click "Import" at the top of the screen.
  4. Select "CSV" under "Format".
  5. Choose the options appropriate to your CSV file, open the CSV file in a text editor and reference it to get the "appropriate" options.

If you have problems, no problem, simply drop the database and try again.

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

Just make a PKCS12 keystore, Java can use it directly now. In fact, if you list a Java-style keystore, keytool itself alerts you to the fact that PKCS12 is now the preferred format.

openssl pkcs12 -export -in server.crt -inkey server.key \
               -out server.p12 -name [some-alias] \
               -CAfile ca.crt -caname root -chain

You should have received all three files (server.crt, server.key, ca.crt) from your certificate provider. I am not sure what "-caname root" actually means, but it seems to have to be specified that way.

In the Java code, make sure to specify the right keystore type.

KeyStore.getInstance("PKCS12")

I got my comodo.com-issued SSL certificate working fine in NanoHTTPD this way.

Swap x and y axis without manually swapping values

  1. Click somewhere on the chart to select it.

  2. You should now see 3 new tabs appear at the top of the screen called "Design", "Layout" and "Format".

  3. Click on the "Design" tab.

  4. There will be a button called "Switch Row/Column" within the "data" group, click it.

Why can't I change my input value in React even with the onChange listener

You can do shortcut via inline function if you want to simply change the state variable without declaring a new function at top:

<input type="text" onChange={e => this.setState({ text: e.target.value })}/>

jquery fill dropdown with json data

In most of the companies they required a common functionality for multiple dropdownlist for all the pages. Just call the functions or pass your (DropDownID,JsonData,KeyValue,textValue)

    <script>

        $(document).ready(function(){

            GetData('DLState',data,'stateid','statename');
        });

        var data = [{"stateid" : "1","statename" : "Mumbai"},
                    {"stateid" : "2","statename" : "Panjab"},
                    {"stateid" : "3","statename" : "Pune"},
                     {"stateid" : "4","statename" : "Nagpur"},
                     {"stateid" : "5","statename" : "kanpur"}];

        var Did=document.getElementById("DLState");

        function GetData(Did,data,valkey,textkey){
          var str= "";
          for (var i = 0; i <data.length ; i++){

            console.log(data);


            str+= "<option value='" + data[i][valkey] + "'>" + data[i][textkey] + "</option>";

          }
          $("#"+Did).append(str);
        };    </script>

</head>
<body>
  <select id="DLState">
  </select>
</body>
</html>

Argparse optional positional arguments?

parser.add_argument also has a switch required. You can use required=False. Here is a sample snippet with Python 2.7:

parser = argparse.ArgumentParser(description='get dir')
parser.add_argument('--dir', type=str, help='dir', default=os.getcwd(), required=False)
args = parser.parse_args()

SQL Server SELECT INTO @variable?

If you wanted to simply assign some variables for later use, you can do them in one shot with something along these lines:

declare @var1 int,@var2 int,@var3 int;

select 
    @var1 = field1,
    @var2 = field2,
    @var3 = field3
from
    table
where
    condition

If that's the type of thing you're after

jQuery select element in parent window

why not both to be sure?

if(opener.document){
  $("#testdiv",opener.document).doStuff();
}else{
  $("#testdiv",window.opener).doStuff();
}

Cast to generic type in C#

Type type = typeof(MessageProcessor<>).MakeGenericType(key);

That's the best you can do, however without actually knowing what type it is, there's really not much more you can do with it.

EDIT: I should clarify. I changed from var type to Type type. My point is, now you can do something like this:

object obj = Activator.CreateInstance(type);

obj will now be the correct type, but since you don't know what type "key" is at compile time, there's no way to cast it and do anything useful with it.

How to get index of object by its property in JavaScript?

If you want to get the value of the property token then you can also try this

    let data=[
      { id_list: 1, name: 'Nick', token: '312312' },
      { id_list: 2, name: 'John', token: '123123' },
    ]

    let resultingToken =  data[_.findKey(data,['name','John'])].token

where _.findKey is a lodash's function

Is there a Visual Basic 6 decompiler?

In my own experience where I needed to try and find out what some old VB6 programs were doing, I turned to Process Explorer (Sysinternals). I did the following:

  1. Run Process Explorer
  2. Run VB6 .exe
  3. Locate exe in Process Explorer
  4. Right click on process
  5. Check the "Strings" tab

This didn't show the actual functions, but it listed their names, folders of where files were being copied from and to and if it accessed a DB it would also display the connection string. Enough to help you get an idea, but may be useless for complex programs. The programs I was looking at were pretty basic (no pun intended).

YMMV.

How to pass parameters to a partial view in ASP.NET MVC?

Here is another way to do it if you want to use ViewData:

@Html.Partial("~/PathToYourView.cshtml", null, new ViewDataDictionary { { "VariableName", "some value" } })

And to retrieve the passed in values:

@{
    string valuePassedIn = this.ViewData.ContainsKey("VariableName") ? this.ViewData["VariableName"].ToString() : string.Empty;
}

Default SQL Server Port

The default port for SQL Server Database Engine is 1433.

And as a best practice it should always be changed after the installation. 1433 is widely known which makes it vulnerable to attacks.

How to know if a Fragment is Visible?

Try this if you have only one Fragment

if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
                    //TODO: Your Code Here
                }

Javascript checkbox onChange

Javascript

  // on toggle method
  // to check status of checkbox
  function onToggle() {
    // check if checkbox is checked
    if (document.querySelector('#my-checkbox').checked) {
      // if checked
      console.log('checked');
    } else {
      // if unchecked
      console.log('unchecked');
    }
  }

HTML

<input id="my-checkbox" type="checkbox" onclick="onToggle()">

What is JSON and why would I use it?

The difference between JSON and conventional syntax would be as follows (in Javascript)

Conventional

 function Employee(name, Id, Phone, email){

      this.name = name;
      this.Id = Id;
      this.Phone = Phone;
      this.email = email;
  }

  //access or call it as 

var Emp = new Employee("mike","123","9373849784","[email protected]");

With JSON

if we use JSON we can define in different way as

  function Employee(args){

   this.name = args.name;
   this.Id = args.Id;
   this.Phone = args.Phone;
   this.email = args.email;
}

//now access this as...

var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'[email protected]'});

The important thing we have to remember is that, if we have to build the "Employee" class or modal with 100 elements without JSON method we have to parse everything when creating class. But with JSON we can define the objects inline only when a new object for the class is defined.

so this line below is the way of doing things with JSON(just a simple way to define things)

 var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'[email protected]'});

Getting first and last day of the current month

An alternative way is to use DateTime.DaysInMonth to get the number of days in the current month as suggested by @Jade

Since we know the first day of the month will always 1 we can use it as default for the first day with the current Month & year as current.year,current.Month,1.

var now = DateTime.Now; // get the current DateTime 

//Get the number of days in the current month
int daysInMonth = DateTime.DaysInMonth (now.Year, now.Month); 
    
//First day of the month is always 1
var firstDay = new DateTime(now.Year,now.Month,1); 
    
//Last day will be similar to the number of days calculated above
var lastDay = new DateTime(now.Year,now.Month,daysInMonth);

//So
rdpStartDate.SelectedDate = firstDay;
rdpEndDate.SelectedDate = lastDay; 

How to hide code from cells in ipython notebook visualized with nbviewer?

The newest IPython notebook version do not allow executing javascript in markdown cells anymore, so adding a new markdown cell with the following javascript code will not work anymore to hide your code cells (refer to this link)

Change ~/.ipython/profile_default/static/custom/custom.js as below:

code_show=true;
function code_toggle() {
 if (code_show){
 $('div.input').hide();
 } else {
 $('div.input').show();
 }
 code_show = !code_show
}

$([IPython.events]).on("app_initialized.NotebookApp", function () {
  $("#view_menu").append("<li id=\"toggle_toolbar\" title=\"Show/Hide code cells\"><a href=\"javascript:code_toggle()\">Toggle Code Cells</a></li>")
});

How to add content to html body using JS?

You're probably using

document.getElementById('element').innerHTML = "New content"

Try this instead:

document.getElementById('element').innerHTML += "New content"

Or, preferably, use DOM Manipulation:

document.getElementById('element').appendChild(document.createElement("div"))

Dom manipulation would be preferred compared to using innerHTML, because innerHTML simply dumps a string into the document. The browser will have to reparse the entire document to get it's stucture.

Http Get using Android HttpURLConnection

I have created with callBack(delegate) response to Activity class.

public class WebService extends AsyncTask<String, Void, String> {

    private Context mContext;
    private OnTaskDoneListener onTaskDoneListener;
    private String urlStr = "";

    public WebService(Context context, String url, OnTaskDoneListener onTaskDoneListener) {
        this.mContext = context;
        this.urlStr = url;
        this.onTaskDoneListener = onTaskDoneListener;
    }

    @Override
    protected String doInBackground(String... params) {
        try {

            URL mUrl = new URL(urlStr);
            HttpURLConnection httpConnection = (HttpURLConnection) mUrl.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Content-length", "0");
            httpConnection.setUseCaches(false);
            httpConnection.setAllowUserInteraction(false);
            httpConnection.setConnectTimeout(100000);
            httpConnection.setReadTimeout(100000);

            httpConnection.connect();

            int responseCode = httpConnection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {
                BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    sb.append(line + "\n");
                }
                br.close();
                return sb.toString();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        if (onTaskDoneListener != null && s != null) {
            onTaskDoneListener.onTaskDone(s);
        } else
            onTaskDoneListener.onError();
    }
}

where

public interface OnTaskDoneListener {
    void onTaskDone(String responseData);

    void onError();
}

You can modify according to your needs. It's for get

IBOutlet and IBAction

The traditional way to flag a method so that it will appear in Interface Builder, and you can drag a connection to it, has been to make the method return type IBAction. However, if you make your method void, instead (IBAction is #define'd to be void), and provide an (id) argument, the method is still visible. This provides extra flexibility, al

All 3 of these are visible from Interface Builder:

-(void) someMethod1:(id) sender; 
-(IBAction) someMethod2; 
-(IBAction) someMethod3:(id) sender;

See Apple's Interface Builder User Guide for details, particularly the section entitled Xcode Integration.

org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformClassesWithDexForDebug'

I had the same issue and I could solve it like this:

1) If your minSdkVersion is set to 21 or a higher value, the only thing you need to do is to set multiDexEnabled in your build.gradle file at the module level, as shown below:

android {
    defaultConfig {
        ...
        minSdkVersion 21 
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

2) However, if your minSdkVersion is set to 20 or less, you should use the MultiDex compatibility library, as follows:

2.1) Modify the module-level build.gradle file to enable MultiDex and add the MultiDex library as dependency, as shown below

android {
    defaultConfig {
        ...
        minSdkVersion 15 
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

2.2) According to the Application class or not, do one of the following actions:

2.2.1) If you do not cancel the Application class, modify your manifest file to set android: name in the <application> tag as shown below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myapp">
    <application
            android:name="android.support.multidex.MultiDexApplication" >
        ...
    </application>
</manifest>

2.2.2) If you cancel the Application class, you must change it to extend MultiDexApplication (if possible) as shown below:

public class MyApplication extends MultiDexApplication { ... }

2.2.3) Also, if you override the Application class and can not change the base class, alternatively you can override the attachBaseContext () method and invoke MultiDex.install (this) to enable MultiDex:

public class MyApplication extends SomeOtherApplication {
  @Override
  protected void attachBaseContext(Context base) {
     super.attachBaseContext(base);
     MultiDex.install(this);
  }
}

Please use this link, it was really useful for me!

How to remove leading and trailing whitespace in a MySQL field?

I know its already accepted, but for thoses like me who look for "remove ALL whitespaces" (not just at the begining and endingof the string):

select SUBSTRING_INDEX('1234 243', ' ', 1);
// returns '1234'

EDIT 2019/6/20 : Yeah, that's not good. The function returns the part of the string since "when the character space occured for the first time". So, I guess that saying this remove the leading and trailling whitespaces and returns the first word :

select SUBSTRING_INDEX(TRIM(' 1234 243'), ' ', 1);

How to return a value from pthread threads in C?

You are returning a reference to ret which is a variable on the stack.

Does Google Chrome work with Selenium IDE (as Firefox does)?

No, Google Chrome does not work with Selenium IDE. As Selenium IDE is a Firefox plugin it works only with FF.

According to your last portion of question: Or is there any alternative tool which can work with Chrome? The possible answer is as follows:

You can use Sahi with Chrome. Sahi Test Automation tool supports Chrome, Firefox and IE. You can visit for details:

http://sahi.co.in/

Tools to generate database tables diagram with Postgresql?

Quick solution I found was inside the pgAdmin program for windows. Under Tools menu there is a "Query Tool". Inside the Query Tool there is a Graphical Query Builder that can quickly show the database tables details. Good for a basic view

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

enter image description here

As of verison 2.10, Genymotion can be installed using the toolbar in your emulator. Simply look for the Open GAPPS button.

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

Launch chrome like so to bypass this restriction: open -a "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome" --args --allow-file-access-from-files.

Derived from Josh Lee's comment but I needed to specify the full path to Google Chrome so as to avoid having Google Chrome opening from my Windows partition (in Parallels).

How do I parallelize a simple Python loop?

Let's say we have an async function

async def work_async(self, student_name: str, code: str, loop):
"""
Some async function
"""
    # Do some async procesing    

That needs to be run on a large array. Some attributes are being passed to the program and some are used from property of dictionary element in the array.

async def process_students(self, student_name: str, loop):
    market = sys.argv[2]
    subjects = [...] #Some large array
    batchsize = 5
    for i in range(0, len(subjects), batchsize):
        batch = subjects[i:i+batchsize]
        await asyncio.gather(*(self.work_async(student_name,
                                           sub['Code'],
                                           loop)
                       for sub in batch))

Git: can't undo local changes (error: path ... is unmerged)

You did it the wrong way around. You are meant to reset first, to unstage the file, then checkout, to revert local changes.

Try this:

$ git reset foo/bar.txt
$ git checkout foo/bar.txt

What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

suppose you need a label with text customername than you can achive it using 2 ways

[1]@Html.Label("CustomerName")

[2]@Html.LabelFor(a => a.CustomerName)  //strongly typed

2nd method used a property from your model. If your view implements a model then you can use the 2nd method.

More info please visit below link

http://weblogs.asp.net/scottgu/archive/2010/01/10/asp-net-mvc-2-strongly-typed-html-helpers.aspx

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

Do this if you are using GoDaddy, I'm using Lets Encrypt SSL if you want you can get it.

Here is the code - The code is in asp.net core 2.0 but should work in above versions.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MailKit.Net.Smtp;
using MimeKit;

namespace UnityAssets.Website.Services
{
    public class EmailSender : IEmailSender
    {
        public async Task SendEmailAsync(string toEmailAddress, string subject, string htmlMessage)
        {
            var email = new MimeMessage();
            email.From.Add(new MailboxAddress("Application Name", "[email protected]"));
            email.To.Add(new MailboxAddress(toEmailAddress, toEmailAddress));
            email.Subject = subject;

            var body = new BodyBuilder
            {
                HtmlBody = htmlMessage
            };

            email.Body = body.ToMessageBody();

            using (var client = new SmtpClient())
            {
                //provider specific settings
                await client.ConnectAsync("smtp.gmail.com", 465, true).ConfigureAwait(false);
                await client.AuthenticateAsync("[email protected]", "sketchunity").ConfigureAwait(false);

                await client.SendAsync(email).ConfigureAwait(false);
                await client.DisconnectAsync(true).ConfigureAwait(false);
            }
        }
    }
}

Map implementation with duplicate keys

Could you also explain the context for which you are trying to implement a map with duplicate keys? I am sure there could be a better solution. Maps are intended to keep unique keys for good reason. Though if you really wanted to do it; you can always extend the class write a simple custom map class which has a collision mitigation function and would enable you to keep multiple entries with same keys.

Note: You must implement collision mitigation function such that, colliding keys are converted to unique set "always". Something simple like, appending key with object hashcode or something?

Input type number "only numeric value" validation

Sometimes it is just easier to try something simple like this.

validateNumber(control: FormControl): { [s: string]: boolean } {

  //revised to reflect null as an acceptable value 
  if (control.value === null) return null;

  // check to see if the control value is no a number
  if (isNaN(control.value)) {
    return { 'NaN': true };
  }

  return null; 
}

Hope this helps.

updated as per comment, You need to to call the validator like this

number: new FormControl('',[this.validateNumber.bind(this)])

The bind(this) is necessary if you are putting the validator in the component which is how I do it.

How to correctly implement custom iterators and const_iterators?

Boost has something to help: the Boost.Iterator library.

More precisely this page: boost::iterator_adaptor.

What's very interesting is the Tutorial Example which shows a complete implementation, from scratch, for a custom type.

template <class Value>
class node_iter
  : public boost::iterator_adaptor<
        node_iter<Value>                // Derived
      , Value*                          // Base
      , boost::use_default              // Value
      , boost::forward_traversal_tag    // CategoryOrTraversal
    >
{
 private:
    struct enabler {};  // a private type avoids misuse

 public:
    node_iter()
      : node_iter::iterator_adaptor_(0) {}

    explicit node_iter(Value* p)
      : node_iter::iterator_adaptor_(p) {}

    // iterator convertible to const_iterator, not vice-versa
    template <class OtherValue>
    node_iter(
        node_iter<OtherValue> const& other
      , typename boost::enable_if<
            boost::is_convertible<OtherValue*,Value*>
          , enabler
        >::type = enabler()
    )
      : node_iter::iterator_adaptor_(other.base()) {}

 private:
    friend class boost::iterator_core_access;
    void increment() { this->base_reference() = this->base()->next(); }
};

The main point, as has been cited already, is to use a single template implementation and typedef it.

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

you must check if you implemented the page in the controller for example:

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

Dynamic WHERE clause in LINQ

You can also use the PredicateBuilder from LinqKit to chain multiple typesafe lambda expressions using Or or And.

http://www.albahari.com/nutshell/predicatebuilder.aspx

How do I add space between two variables after a print in Python

print str(count) + ' ' + str(conv) - This did not work. However, replacing + with , works for me

Converting map to struct

Hashicorp's https://github.com/mitchellh/mapstructure library does this out of the box:

import "github.com/mitchellh/mapstructure"

mapstructure.Decode(myData, &result)

The second result parameter has to be an address of the struct.

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

Connecting to local SQL Server database using C#

You try with this string connection

Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;

GDB: break if variable equal value

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

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

then just run you code with your favourite debugger

$ gdb ./ex1

show me the code.

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

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

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

checking breakpoints

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

running the program

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

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

HTML5 form required attribute. Set custom validation message?

The solution for preventing Google Chrome error messages on input each symbol:

_x000D_
_x000D_
<p>Click the 'Submit' button with empty input field and you will see the custom error message. Then put "-" sign in the same input field.</p>_x000D_
<form method="post" action="#">_x000D_
  <label for="text_number_1">Here you will see browser's error validation message on input:</label><br>_x000D_
  <input id="test_number_1" type="number" min="0" required="true"_x000D_
         oninput="this.setCustomValidity('')"_x000D_
         oninvalid="this.setCustomValidity('This is my custom message.')"/>_x000D_
  <input type="submit"/>_x000D_
</form>_x000D_
_x000D_
<form method="post" action="#">_x000D_
  <p></p>_x000D_
  <label for="text_number_1">Here you will see no error messages on input:</label><br>_x000D_
  <input id="test_number_2" type="number" min="0" required="true"_x000D_
         oninput="(function(e){e.setCustomValidity(''); return !e.validity.valid && e.setCustomValidity(' ')})(this)"_x000D_
         oninvalid="this.setCustomValidity('This is my custom message.')"/>_x000D_
  <input type="submit"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How do I undo 'git add' before commit?

One of the most intuitive solutions is using Sourcetree.

You can just drag and drop files from staged and unstaged

Enter image description here

Use PPK file in Mac Terminal to connect to remote connection over SSH

You can ssh directly from the Terminal on Mac, but you need to use a .PEM key rather than the putty .PPK key. You can use PuttyGen on Windows to convert from .PEM to .PPK, I'm not sure about the other way around though.

You can also convert the key using putty for Mac via port or brew:

sudo port install putty

or

brew install putty

This will also install puttygen. To get puttygen to output a .PEM file:

puttygen privatekey.ppk -O private-openssh -o privatekey.pem

Once you have the key, open a terminal window and:

ssh -i privatekey.pem [email protected]

The private key must have tight security settings otherwise SSH complains. Make sure only the user can read the key.

chmod go-rw privatekey.pem

How to subtract X day from a Date object in Java?

Java 8 Time API:

Instant now = Instant.now(); //current date
Instant before = now.minus(Duration.ofDays(300));
Date dateBefore = Date.from(before);

Error:Cause: unable to find valid certification path to requested target

Most of the times when I face this issue. I remove replace https with http. It solves the issue.

Get position/offset of element relative to a parent container?

in pure js just use offsetLeft and offsetTop properties.
Example fiddle: http://jsfiddle.net/WKZ8P/

_x000D_
_x000D_
var elm = document.querySelector('span');_x000D_
console.log(elm.offsetLeft, elm.offsetTop);
_x000D_
p   { position:relative; left:10px; top:85px; border:1px solid blue; }_x000D_
span{ position:relative; left:30px; top:35px; border:1px solid red; }
_x000D_
<p>_x000D_
    <span>paragraph</span>_x000D_
</p>
_x000D_
_x000D_
_x000D_

SELECT *, COUNT(*) in SQLite

count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

Open a new tab on button click in AngularJS

I solved this question this way.

<a class="btn btn-primary" target="_blank" ng-href="{{url}}" ng-mousedown="openTab()">newTab</a>

$scope.openTab = function() {
    $scope.url = 'www.google.com';
}

Get all LI elements in array

After some years have passed, you can do that now with ES6 Array.from (or spread syntax):

_x000D_
_x000D_
const navbar = Array.from(document.querySelectorAll('#navbar>ul>li'));_x000D_
console.log('Get first: ', navbar[0].textContent);_x000D_
_x000D_
// If you need to iterate once over all these nodes, you can use the callback function:_x000D_
console.log('Iterate with Array.from callback argument:');_x000D_
Array.from(document.querySelectorAll('#navbar>ul>li'),li => console.log(li.textContent))_x000D_
_x000D_
// ... or a for...of loop:_x000D_
console.log('Iterate with for...of:');_x000D_
for (const li of document.querySelectorAll('#navbar>ul>li')) {_x000D_
    console.log(li.textContent);_x000D_
}
_x000D_
.as-console-wrapper { max-height: 100% !important; top: 0; }
_x000D_
<div id="navbar">_x000D_
  <ul>_x000D_
    <li id="navbar-One">One</li>_x000D_
    <li id="navbar-Two">Two</li>_x000D_
    <li id="navbar-Three">Three</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Installing Homebrew on OS X

Open Terminal and put below command.
Install:

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

Uninstall:

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

Once install complete after entering brew commands:

brew install wget
brew install node
brew install watchman
...
...

How to select the rows with maximum values in each group with dplyr?

This more verbose solution provides greater control on what happens in case of duplicate maximum value (in this example, it will take one of the corresponding rows randomly)

library(dplyr)
df %>% group_by(A, B) %>%
  mutate(the_rank  = rank(-value, ties.method = "random")) %>%
  filter(the_rank == 1) %>% select(-the_rank)

Store a cmdlet's result value in a variable in Powershell

Use the -ExpandProperty flag of Select-Object

$var=Get-WSManInstance -enumerate wmicimv2/win32_process | select -expand Priority

Update to answer the other question:

Note that you can as well just access the property:

$var=(Get-WSManInstance -enumerate wmicimv2/win32_process).Priority

So to get multiple of these into variables:

$var=Get-WSManInstance -enumerate wmicimv2/win32_process
   $prio = $var.Priority
   $pid = $var.ProcessID

C# ASP.NET Send Email via TLS

On SmtpClient there is an EnableSsl property that you would set.

i.e.

SmtpClient client = new SmtpClient(exchangeServer);
client.EnableSsl = true;
client.Send(msg);

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

You will have to be careful binding the UI to your custom collection -- the Default CollectionView class only supports single notification of items.

How to calculate a Mod b in Casio fx-991ES calculator

You can calculate A mod B (for positive numbers) using this:

Pol( -Rec( 1/r , 2πr × A/B ) , Y ) ( πr - Y ) B

Then press [CALC], and enter your values for A and B, and any value for Y.

/ indicates using the fraction key, and r means radians ( [SHIFT] [Ans] [2] )

Interpreting segfault messages

This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).

If this were a program, not a shared library

Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d (and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.

Since it's a shared library

You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb.

What the error means

Here's the breakdown of the fields:

  • address (after the at) - the location in memory the code is trying to access (it's likely that 10 and 11 are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0)
  • ip - instruction pointer, ie. where the code which is trying to do this lives
  • sp - stack pointer
  • error - An error code for page faults; see below for what this means on x86.

    /*
     * Page fault error code bits:
     *
     *   bit 0 ==    0: no page found       1: protection fault
     *   bit 1 ==    0: read access         1: write access
     *   bit 2 ==    0: kernel-mode access  1: user-mode access
     *   bit 3 ==                           1: use of reserved bit detected
     *   bit 4 ==                           1: fault was an instruction fetch
     */
    

Has an event handler already been added?

If this is the only handler, you can check to see if the event is null, if it isn't, the handler has been added.

I think you can safely call -= on the event with your handler even if it's not added (if not, you could catch it) -- to make sure it isn't in there before adding.

SQL Server principal "dbo" does not exist,

Also had this error when accidentally fed a database connection string to the readonly mirror - not the primary database in a HA setup.

Go to beginning of line without opening new line in VI

You can use ^ or 0 (Zero) in normal mode to move to the beginning of a line.

^ moves the cursor to the first non-blank character of a line
0 always moves the cursor to the "first column"

You can also use Shifti to move and switch to Insert mode.

How do you print in a Go test using the "testing" package?

t.Log() will not show up until after the test is complete, so if you're trying to debug a test that is hanging or performing badly it seems you need to use fmt.

Yes: that was the case up to Go 1.13 (August 2019) included.

And that was followed in golang.org issue 24929

Consider the following (silly) automated tests:

func TestFoo(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(3 * time.Second)
    }
}

func TestBar(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(2 * time.Second)
    }
}

func TestBaz(t *testing.T) {
    t.Parallel()

  for i := 0; i < 15; i++ {
        t.Logf("%d", i)
        time.Sleep(1 * time.Second)
    }
}

If I run go test -v, I get no log output until all of TestFoo is done, then no output until all of TestBar is done, and again no more output until all of TestBaz is done.
This is fine if the tests are working, but if there is some sort of bug, there are a few cases where buffering log output is problematic:

  • When iterating locally, I want to be able to make a change, run my tests, see what's happening in the logs immediately to understand what's going on, hit CTRL+C to shut the test down early if necessary, make another change, re-run the tests, and so on.
    If TestFoo is slow (e.g., it's an integration test), I get no log output until the very end of the test. This significantly slows down iteration.
  • If TestFoo has a bug that causes it to hang and never complete, I'd get no log output whatsoever. In these cases, t.Log and t.Logf are of no use at all.
    This makes debugging very difficult.
  • Moreover, not only do I get no log output, but if the test hangs too long, either the Go test timeout kills the test after 10 minutes, or if I increase that timeout, many CI servers will also kill off tests if there is no log output after a certain amount of time (e.g., 10 minutes in CircleCI).
    So now my tests are killed and I have nothing in the logs to tell me what happened.

But for (possibly) Go 1.14 (Q1 2020): CL 127120

testing: stream log output in verbose mode

The output now is:

=== RUN   TestFoo
=== PAUSE TestFoo
=== RUN   TestBar
=== PAUSE TestBar
=== RUN   TestGaz
=== PAUSE TestGaz
=== CONT  TestFoo
    TestFoo: main_test.go:14: hello from foo
=== CONT  TestGaz
=== CONT  TestBar
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestFoo: main_test.go:14: hello from foo
    TestBar: main_test.go:26: hello from bar
    TestGaz: main_test.go:38: hello from gaz
    TestFoo: main_test.go:14: hello from foo
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestFoo: main_test.go:14: hello from foo
    TestGaz: main_test.go:38: hello from gaz
    TestBar: main_test.go:26: hello from bar
    TestGaz: main_test.go:38: hello from gaz
    TestFoo: main_test.go:14: hello from foo
    TestBar: main_test.go:26: hello from bar
--- PASS: TestFoo (1.00s)
--- PASS: TestGaz (1.00s)
--- PASS: TestBar (1.00s)
PASS
ok      dummy/streaming-test    1.022s

It is indeed in Go 1.14, as Dave Cheney attests in "go test -v streaming output":

In Go 1.14, go test -v will stream t.Log output as it happens, rather than hoarding it til the end of the test run.

Under Go 1.14 the fmt.Println and t.Log lines are interleaved, rather than waiting for the test to complete, demonstrating that test output is streamed when go test -v is used.

Advantage, according to Dave:

This is a great quality of life improvement for integration style tests that often retry for long periods when the test is failing.
Streaming t.Log output will help Gophers debug those test failures without having to wait until the entire test times out to receive their output.

Count number of occurrences by month

Recommend you use FREQUENCY rather than using COUNTIF.

In your front sheet; enter 01/04/2014 into E5, 01/05/2014 into E6 etc.

Select the range of adjacent cells you want to populate. Enter:

=FREQUENCY(2013!!$A$2:$A$50,'2013 Metrics'!E5:EN)

(where N is the final row reference in your range)

Hit Ctrl + Shift + Enter

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

In my case when i was using firebase services the google.json file was mismatched check once that also

WebService Client Generation Error with JDK8

For those using the ANT task wsimport, a way of passing the option as suggested by @CMFly and specified in the documentation is the following:

<wsimport
   <!-- ... -->
   fork="true"
  >
  <jvmarg value="-Djavax.xml.accessExternalSchema=all"/>
</wsimport>

How to emulate GPS location in the Android Emulator?

In Mac, Linux or Cygwin:

echo 'geo fix -99.133333 19.43333 2202' | nc localhost 5554

That will put you in Mexico City. Change your longitude/latitude/altitude accordingly. That should be enough if you are not interested in nmea.

Does Ruby have a string.startswith("abc") built in method?

Your question title and your question body are different. Ruby does not have a starts_with? method. Rails, which is a Ruby framework, however, does, as sepp2k states. See his comment on his answer for the link to the documentation for it.

You could always use a regular expression though:

if SomeString.match(/^abc/) 
   # SomeString starts with abc

^ means "start of string" in regular expressions

Does VBA have Dictionary Structure?

VBA does not have an internal implementation of a dictionary, but from VBA you can still use the dictionary object from MS Scripting Runtime Library.

Dim d
Set d = CreateObject("Scripting.Dictionary")
d.Add "a", "aaa"
d.Add "b", "bbb"
d.Add "c", "ccc"

If d.Exists("c") Then
    MsgBox d("c")
End If

Good tutorial for using HTML5 History API (Pushstate?)

I've written a very simple router abstraction on top of History.js, called StateRouter.js. It's in very early stages of development, but I am using it as the routing solution in a single-page application I'm writing. Like you, I found History.js very hard to grasp, especially as I'm quite new to JavaScript, until I understood that you really need (or should have) a routing abstraction on top of it, as it solves a low-level problem.

This simple example code should demonstrate how it's used:

var router = new staterouter.Router();
// Configure routes
router
  .route('/', getHome)
  .route('/persons', getPersons)
  .route('/persons/:id', getPerson);
// Perform routing of the current state
router.perform();

Here's a little fiddle I've concocted in order to demonstrate its usage.

Java Scanner class reading strings

The reason for the error is that the nextInt only pulls the integer, not the newline. If you add a in.nextLine() before your for loop, it will eat the empty new line and allow you to enter 3 names.

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();

names = new String[nnames];
in.nextLine();
for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();
}

or just read the line and parse the value as an Integer.

int nnames;
String names[];

System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = Integer.parseInt(in.nextLine().trim());

names = new String[nnames];
for (int i = 0; i < names.length; i++){
        System.out.print("Type a name: ");
        names[i] = in.nextLine();
}

Forbidden You don't have permission to access / on this server

WORKING Method { if there is no problem other than configuration }

By Default Appache is not restricting access from ipv4. (common external ip)

What may restrict is the configurations in 'httpd.conf' (or 'apache2.conf' depending on your apache configuration)

Solution:

Replace all:

<Directory />
     AllowOverride none
    Require all denied

</Directory>

with

<Directory />
     AllowOverride none
#    Require all denied

</Directory>

hence removing out all restriction given to Apache

Replace Require local with Require all granted at C:/wamp/www/ directory

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
#   Require local
</Directory>

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

In my case I was committing transaction when persist method was used. On changing persist to save method , it got resolved.

How to transition to a new view controller with code only using Swift

For anyone doing this on iOS8, this is what I had to do:

I have a swift class file titled SettingsView.swift and a .xib file named SettingsView.xib. I run this in MasterViewController.swift (or any view controller really to open a second view controller)

@IBAction func openSettings(sender: AnyObject) {
        var mySettings: SettingsView = SettingsView(nibName: "SettingsView", bundle: nil) /<--- Notice this "nibName" 
        var modalStyle: UIModalTransitionStyle = UIModalTransitionStyle.CoverVertical
        mySettings.modalTransitionStyle = modalStyle
        self.presentViewController(mySettings, animated: true, completion: nil)

    }

How to put labels over geom_bar for each bar in R with ggplot2

To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,

ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) + 
 geom_bar(position = "dodge", stat = 'identity') +
 geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)

How can I get a list of repositories 'apt-get' is checking?

All I needed was:

cd /etc/apt
nano source.list
deb http://http.kali.org/kali kali-rolling main non-free contrib
deb-src http://http.kali.org/kali kali-rolling main non-free contrib
apt upgrade && update

Source: Kali Network Repositories (/etc/apt/sources.list)

Adding iOS UITableView HeaderView (not section header)

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width,30)];
    headerView.backgroundColor=[[UIColor redColor]colorWithAlphaComponent:0.5f];
    headerView.layer.borderColor=[UIColor blackColor].CGColor;
    headerView.layer.borderWidth=1.0f;

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5,100,20)];

    headerLabel.textAlignment = NSTextAlignmentRight;
    headerLabel.text = @"LeadCode ";
    //headerLabel.textColor=[UIColor whiteColor];
    headerLabel.backgroundColor = [UIColor clearColor];


    [headerView addSubview:headerLabel];

    UILabel *headerLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, headerView.frame.size.width-120.0, headerView.frame.size.height)];

    headerLabel1.textAlignment = NSTextAlignmentRight;
    headerLabel1.text = @"LeadName";
    headerLabel.textColor=[UIColor whiteColor];
    headerLabel1.backgroundColor = [UIColor clearColor];

    [headerView addSubview:headerLabel1];

    return headerView;

}

How to receive JSON as an MVC 5 action method parameter

There are a couple issues here. First, you need to make sure to bind your JSON object back to the model in the controller. This is done by changing

data: JSON.stringify(usersRoles),

to

data: { model: JSON.stringify(usersRoles) },

Secondly, you aren't binding types correctly with your jquery call. If you remove

contentType: "application/json; charset=utf-8",

it will inherently bind back to a string.

All together, use the first ActionResult method and the following jquery ajax call:

    jQuery.ajax({
        type: "POST",
        url: "@Url.Action("AddUser")",
        dataType: "json",
        data: { model: JSON.stringify(usersRoles) },
        success: function (data) { alert(data); },
        failure: function (errMsg) {
        alert(errMsg);
        }
   });

replace special characters in a string python

You can replace the special characters with the desired characters as follows,

import string
specialCharacterText = "H#y #@w @re &*)?"
inCharSet = "!@#$%^&*()[]{};:,./<>?\|`~-=_+\""
outCharSet = "                               " #corresponding characters in inCharSet to be replaced
splCharReplaceList = string.maketrans(inCharSet, outCharSet)
splCharFreeString = specialCharacterText.translate(splCharReplaceList)

The equivalent of wrap_content and match_parent in flutter?

Use the widget Wrap.

For Column like behavior try:

  return Wrap(
          direction: Axis.vertical,
          spacing: 10,
          children: <Widget>[...],);

For Row like behavior try:

  return Wrap(
          direction: Axis.horizontal,
          spacing: 10,
          children: <Widget>[...],);

For more information: Wrap (Flutter Widget)

int *array = new int[n]; what is this function actually doing?

The new operator is allocating space for a block of n integers and assigning the memory address of that block to the int* variable array.

The general form of new as it applies to one-dimensional arrays appears as follows:

array_var = new Type[desired_size];

Java: Get month Integer from Date

If you can't use Joda time and you still live in the dark world :) ( Java 5 or lower ) you can enjoy this :

Note: Make sure your date is allready made by the format : dd/MM/YYYY

/**
Make an int Month from a date
*/
public static int getMonthInt(Date date) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
    return Integer.parseInt(dateFormat.format(date));
}

/**
Make an int Year from a date
*/
public static int getYearInt(Date date) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
    return Integer.parseInt(dateFormat.format(date));
}

How to override a JavaScript function

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

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

Now parseFloat(3) will alert 3.

WebAPI to Return XML

You should simply return your object, and shouldn't be concerned about whether its XML or JSON. It is the client responsibility to request JSON or XML from the web api. For example, If you make a call using Internet explorer then the default format requested will be Json and the Web API will return Json. But if you make the request through google chrome, the default request format is XML and you will get XML back.

If you make a request using Fiddler then you can specify the Accept header to be either Json or XML.

Accept: application/xml

You may wanna see this article: Content Negotiation in ASP.NET MVC4 Web API Beta – Part 1

EDIT: based on your edited question with code:

Simple return list of string, instead of converting it to XML. try it using Fiddler.

public List<string> Get(int tenantID, string dataType, string ActionName)
    {
       List<string> SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList();
       return SQLResult;
     }

For example if your list is like:

List<string> list = new List<string>();
list.Add("Test1");
list.Add("Test2");
list.Add("Test3");
return list;

and you specify Accept: application/xml the output will be:

<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
  <string>Test1</string>
  <string>Test2</string>
  <string>Test3</string>
</ArrayOfstring>

and if you specify 'Accept: application/json' in the request then the output will be:

[
  "Test1",
  "Test2",
  "Test3"
]

So let the client request the content type, instead of you sending the customized xml.

How to resolve merge conflicts in Git repository?

I follow the below process.

The process to fix merge conflict:

  1. First, pull the latest from the destination branch to which you want to merge git pull origin develop

  2. As you get the latest from the destination, now resolve the conflict manually in IDE by deleting those extra characters.

  3. Do a git add to add these edited files to the git queue so that it can be commit and push to the same branch you are working on.

  4. As git add is done, do a git commit to commit the changes.

  5. Now push the changes to your working branch by git push origin HEAD

This is it and you will see it resolved in your pull request if you are using Bitbucket or GitHub.

What is the difference between "Form Controls" and "ActiveX Control" in Excel 2010?

One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.

ActiveX is also more customizable.

how to call an ASP.NET c# method using javascript

There are several options. You can use the WebMethod attribute, for your purpose.

Typescript Date Type?

Every class or interface can be used as a type in TypeScript.

 const date = new Date();

will already know about the date type definition as Date is an internal TypeScript object referenced by the DateConstructor interface.

And for the constructor you used, it is defined as:

interface DateConstructor {
    new(): Date;
    ...
}

To make it more explicit, you can use:

 const date: Date = new Date();

You might be missing the type definitions though, the Date is coming for my example from the ES6 lib, and in my tsconfig.json I have defined:

"compilerOptions": {
    "target": "ES6",
    "lib": [
        "es6",
        "dom"
    ],

You might adapt these settings to target your wanted version of JavaScript.


The Date is by the way an Interface from lib.es6.d.ts:

/** Enables basic storage and retrieval of dates and times. */
interface Date {
    /** Returns a string representation of a date. The format of the string depends on the locale. */
    toString(): string;
    /** Returns a date as a string value. */
    toDateString(): string;
    /** Returns a time as a string value. */
    toTimeString(): string;
    /** Returns a value as a string value appropriate to the host environment's current locale. */
    toLocaleString(): string;
    /** Returns a date as a string value appropriate to the host environment's current locale. */
    toLocaleDateString(): string;
    /** Returns a time as a string value appropriate to the host environment's current locale. */
    toLocaleTimeString(): string;
    /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
    valueOf(): number;
    /** Gets the time value in milliseconds. */
    getTime(): number;
    /** Gets the year, using local time. */
    getFullYear(): number;
    /** Gets the year using Universal Coordinated Time (UTC). */
    getUTCFullYear(): number;
    /** Gets the month, using local time. */
    getMonth(): number;
    /** Gets the month of a Date object using Universal Coordinated Time (UTC). */
    getUTCMonth(): number;
    /** Gets the day-of-the-month, using local time. */
    getDate(): number;
    /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */
    getUTCDate(): number;
    /** Gets the day of the week, using local time. */
    getDay(): number;
    /** Gets the day of the week using Universal Coordinated Time (UTC). */
    getUTCDay(): number;
    /** Gets the hours in a date, using local time. */
    getHours(): number;
    /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */
    getUTCHours(): number;
    /** Gets the minutes of a Date object, using local time. */
    getMinutes(): number;
    /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */
    getUTCMinutes(): number;
    /** Gets the seconds of a Date object, using local time. */
    getSeconds(): number;
    /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */
    getUTCSeconds(): number;
    /** Gets the milliseconds of a Date, using local time. */
    getMilliseconds(): number;
    /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */
    getUTCMilliseconds(): number;
    /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */
    getTimezoneOffset(): number;
    /**
      * Sets the date and time value in the Date object.
      * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.
      */
    setTime(time: number): number;
    /**
      * Sets the milliseconds value in the Date object using local time.
      * @param ms A numeric value equal to the millisecond value.
      */
    setMilliseconds(ms: number): number;
    /**
      * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).
      * @param ms A numeric value equal to the millisecond value.
      */
    setUTCMilliseconds(ms: number): number;

    /**
      * Sets the seconds value in the Date object using local time.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setSeconds(sec: number, ms?: number): number;
    /**
      * Sets the seconds value in the Date object using Universal Coordinated Time (UTC).
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCSeconds(sec: number, ms?: number): number;
    /**
      * Sets the minutes value in the Date object using local time.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setMinutes(min: number, sec?: number, ms?: number): number;
    /**
      * Sets the minutes value in the Date object using Universal Coordinated Time (UTC).
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCMinutes(min: number, sec?: number, ms?: number): number;
    /**
      * Sets the hour value in the Date object using local time.
      * @param hours A numeric value equal to the hours value.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setHours(hours: number, min?: number, sec?: number, ms?: number): number;
    /**
      * Sets the hours value in the Date object using Universal Coordinated Time (UTC).
      * @param hours A numeric value equal to the hours value.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;
    /**
      * Sets the numeric day-of-the-month value of the Date object using local time.
      * @param date A numeric value equal to the day of the month.
      */
    setDate(date: number): number;
    /**
      * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).
      * @param date A numeric value equal to the day of the month.
      */
    setUTCDate(date: number): number;
    /**
      * Sets the month value in the Date object using local time.
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
      * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.
      */
    setMonth(month: number, date?: number): number;
    /**
      * Sets the month value in the Date object using Universal Coordinated Time (UTC).
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
      * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.
      */
    setUTCMonth(month: number, date?: number): number;
    /**
      * Sets the year of the Date object using local time.
      * @param year A numeric value for the year.
      * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.
      * @param date A numeric value equal for the day of the month.
      */
    setFullYear(year: number, month?: number, date?: number): number;
    /**
      * Sets the year value in the Date object using Universal Coordinated Time (UTC).
      * @param year A numeric value equal to the year.
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.
      * @param date A numeric value equal to the day of the month.
      */
    setUTCFullYear(year: number, month?: number, date?: number): number;
    /** Returns a date converted to a string using Universal Coordinated Time (UTC). */
    toUTCString(): string;
    /** Returns a date as a string value in ISO format. */
    toISOString(): string;
    /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */
    toJSON(key?: any): string;
}

MySQL SELECT DISTINCT multiple columns

I know that the question is too old, anyway:

select a, b from mytable group by a, b

will give your all the combinations.

How to get child element by index in Jquery?

$('.second').find('div:first')

How to create the most compact mapping n ? isprime(n) up to a limit N?

Let me suggest you the perfect solution for 64 bit integers. Sorry to use C#. You have not already specified it as python in your first post. I hope you can find a simple modPow function and analyze it easily.

public static bool IsPrime(ulong number)
{
    return number == 2 
        ? true 
        : (BigInterger.ModPow(2, number, number) == 2 
            ? (number & 1 != 0 && BinarySearchInA001567(number) == false) 
            : false)
}

public static bool BinarySearchInA001567(ulong number)
{
    // Is number in list?
    // todo: Binary Search in A001567 (https://oeis.org/A001567) below 2 ^ 64
    // Only 2.35 Gigabytes as a text file http://www.cecm.sfu.ca/Pseudoprimes/index-2-to-64.html
}

C error: Expected expression before int

This is actually a fairly interesting question. It's not as simple as it looks at first. For reference, I'm going to be basing this off of the latest C11 language grammar defined in N1570

I guess the counter-intuitive part of the question is: if this is correct C:

if (a == 1) {
  int b = 10;
}

then why is this not also correct C?

if (a == 1)
  int b = 10;

I mean, a one-line conditional if statement should be fine either with or without braces, right?

The answer lies in the grammar of the if statement, as defined by the C standard. The relevant parts of the grammar I've quoted below. Succinctly: the int b = 10 line is a declaration, not a statement, and the grammar for the if statement requires a statement after the conditional that it's testing. But if you enclose the declaration in braces, it becomes a statement and everything's well.

And just for the sake of answering the question completely -- this has nothing to do with scope. The b variable that exists inside that scope will be inaccessible from outside of it, but the program is still syntactically correct. Strictly speaking, the compiler shouldn't throw an error on it. Of course, you should be building with -Wall -Werror anyways ;-)

(6.7) declaration:
            declaration-speci?ers init-declarator-listopt ;
            static_assert-declaration

(6.7) init-declarator-list:
            init-declarator
            init-declarator-list , init-declarator

(6.7) init-declarator:
            declarator
            declarator = initializer

(6.8) statement:
            labeled-statement
            compound-statement
            expression-statement
            selection-statement
            iteration-statement
            jump-statement

(6.8.2) compound-statement:
            { block-item-listopt }

(6.8.4) selection-statement:
            if ( expression ) statement
            if ( expression ) statement else statement
            switch ( expression ) statement

Real time data graphing on a line chart with html5

Here's a gist I discovered for real-time charts in ChartJS:
https://gist.github.com/arisetyo/5985848

ChartJS looks like it's simple to use and looks nice.

Also there's FusionCharts, a more sophisticated library for enterprise use, with a demo of real time here:
http://www.fusioncharts.com/explore/real-time-charts

EDIT I also started using Rickshaw for real time graphs and it's easy to use and pretty customizable: http://code.shutterstock.com/rickshaw/

Can I escape a double quote in a verbatim string literal?

There is a proposal open in GitHub for the C# language about having better support for raw string literals. One valid answer, is to encourage the C# team to add a new feature to the language (such as triple quote - like Python).

see https://github.com/dotnet/csharplang/discussions/89#discussioncomment-257343

Finding the second highest number in array

Scanner sc = new Scanner(System.in);

System.out.println("\n number of input sets::");
int value=sc.nextInt();
System.out.println("\n input sets::");
int[] inputset; 

inputset = new int[value];
for(int i=0;i<value;i++)
{
    inputset[i]=sc.nextInt();
}
int maxvalue=inputset[0];
int secondval=inputset[0];
for(int i=1;i<value;i++)
{
    if(inputset[i]>maxvalue)
   {
        maxvalue=inputset[i];
    }
}
for(int i=1;i<value;i++)
{
    if(inputset[i]>secondval && inputset[i]<maxvalue)
    {
        secondval=inputset[i];
    }
}
System.out.println("\n maxvalue"+ maxvalue);
System.out.println("\n secondmaxvalue"+ secondval);

How to make readonly all inputs in some div in Angular2?

If you want to do a whole group, not just one field at a time, you can use the HTML5 <fieldset> tag.

<fieldset [disabled]="killfields ? 'disabled' : null">

    <!-- fields go here -->

</fieldset>

Java NIO FileChannel versus FileOutputstream performance / usefulness

If you are not using the transferTo feature or non-blocking features you will not notice a difference between traditional IO and NIO(2) because the traditional IO maps to NIO.

But if you can use the NIO features like transferFrom/To or want to use Buffers, then of course NIO is the way to go.

MySQL Delete all rows from table and reset ID to zero

Do not delete, use truncate:

Truncate table XXX

The table handler does not remember the last used AUTO_INCREMENT value, but starts counting from the beginning. This is true even for MyISAM and InnoDB, which normally do not reuse sequence values.

Source.

Delete all data in SQL Server database

It is usually much faster to script out all the objects in the database, and create an empty one, that to delete from or truncate tables.

getMinutes() 0-9 - How to display two digit numbers?

Elegant ES6 function to format a date into hh:mm:ss:

const leadingZero = (num) => `0${num}`.slice(-2);

const formatTime = (date) =>
  [date.getHours(), date.getMinutes(), date.getSeconds()]
  .map(leadingZero)
  .join(':');

How to parse XML using vba

Thanks for the pointers.

I don't know, whether this is the best approach to the problem or not, but here is how I got it to work. I referenced the Microsoft XML, v2.6 dll in my VBA, and then the following code snippet, gives me the required values

Dim objXML As MSXML2.DOMDocument

Set objXML = New MSXML2.DOMDocument

If Not objXML.loadXML(strXML) Then  'strXML is the string with XML'
    Err.Raise objXML.parseError.ErrorCode, , objXML.parseError.reason
End If
 
Dim point As IXMLDOMNode
Set point = objXML.firstChild

Debug.Print point.selectSingleNode("X").Text
Debug.Print point.selectSingleNode("Y").Text

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

How can I parse a time string containing milliseconds in it with python?

For python 2 i did this

print ( time.strftime("%H:%M:%S", time.localtime(time.time())) + "." + str(time.time()).split(".",1)[1])

it prints time "%H:%M:%S" , splits the time.time() to two substrings (before and after the .) xxxxxxx.xx and since .xx are my milliseconds i add the second substring to my "%H:%M:%S"

hope that makes sense :) Example output:

13:31:21.72 Blink 01


13:31:21.81 END OF BLINK 01


13:31:26.3 Blink 01


13:31:26.39 END OF BLINK 01


13:31:34.65 Starting Lane 01


Get Memory Usage in Android

An easy way to check the CPU usage is to use the adb tool w/ top. I.e.:

adb shell top -m 10

A method to count occurrences in a list

Your outer loop is looping over all the words in the list. It's unnecessary and will cause you problems. Remove it and it should work properly.

Ruby: Can I write multi-line string with no concatenation?

Other options:

#multi line string
multiline_string = <<EOM
This is a very long string
that contains interpolation
like #{4 + 5} \n\n
EOM

puts multiline_string

#another option for multiline string
message = <<-EOF
asdfasdfsador #{2+2} this month.
asdfadsfasdfadsfad.
EOF

puts message

SQL Server® 2016, 2017 and 2019 Express full download

When you can't apply Juki's answer then after selecting the desired version of media you can use Fiddler to determine where the files are located.

SQL Server 2019 Express Edition (English):

SQL Server 2017 Express Edition (English):

SQL Server 2016 with SP2 Express Edition (English):

SQL Server 2016 with SP1 Express Edition (English):

And here is how to use Fiddler.

Centos/Linux setting logrotate to maximum file size for all logs

It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

minsize size
              Log  files  are  rotated when they grow bigger than size bytes,
              but not before the additionally specified time interval (daily,
              weekly,  monthly, or yearly).  The related size option is simi-
              lar except that it is mutually exclusive with the time interval
              options,  and  it causes log files to be rotated without regard
              for the last rotation time.  When minsize  is  used,  both  the
              size and timestamp of a log file are considered.

size size
              Log files are rotated only if they grow bigger then size bytes.
              If size is followed by k, the size is assumed to  be  in  kilo-
              bytes.  If the M is used, the size is in megabytes, and if G is
              used, the size is in gigabytes. So size 100,  size  100k,  size
              100M and size 100G are all valid.
maxsize size
              Log files are rotated when they grow bigger than size bytes even before
              the additionally specified time interval (daily, weekly, monthly, 
              or yearly).  The related size option is  similar  except  that  it 
              is mutually exclusive with the time interval options, and it causes
              log files to be rotated without regard for the last rotation time.  
              When maxsize is used, both the size and timestamp of a log file are                  
              considered.

Here is an example:

"/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail [email protected]
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

Pushing value of Var into an Array

Perhaps $('#fruit').val(); is not returning an array and you need something like:

$("#fruit").val() || []

http://docs.jquery.com/Attributes/val

How can I generate an MD5 hash?

The MessageDigest class can provide you with an instance of the MD5 digest.

When working with strings and the crypto classes be sure to always specify the encoding you want the byte representation in. If you just use string.getBytes() it will use the platform default. (Not all platforms use the same defaults)

import java.security.*;

..

byte[] bytesOfMessage = yourString.getBytes("UTF-8");

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);

If you have a lot of data take a look at the .update(byte[]) method which can be called repeatedly. Then call .digest() to obtain the resulting hash.

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

See if your needs are met by a DialogFragment. DialogFragment has a dismiss() method. Much cleaner in my opinion.

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

If your data file is structured like this

col1, col2, col3
   1,    2,    3
  10,   20,   30
 100,  200,  300

then numpy.genfromtxt can interpret the first line as column headers using the names=True option. With this you can access the data very conveniently by providing the column header:

data = np.genfromtxt('data.txt', delimiter=',', names=True)
print data['col1']    # array([   1.,   10.,  100.])
print data['col2']    # array([   2.,   20.,  200.])
print data['col3']    # array([   3.,   30.,  300.])

Since in your case the data is formed like this

row1,   1,  10, 100
row2,   2,  20, 200
row3,   3,  30, 300

you can achieve something similar using the following code snippet:

labels = np.genfromtxt('data.txt', delimiter=',', usecols=0, dtype=str)
raw_data = np.genfromtxt('data.txt', delimiter=',')[:,1:]
data = {label: row for label, row in zip(labels, raw_data)}

The first line reads the first column (the labels) into an array of strings. The second line reads all data from the file but discards the first column. The third line uses dictionary comprehension to create a dictionary that can be used very much like the structured array which numpy.genfromtxt creates using the names=True option:

print data['row1']    # array([   1.,   10.,  100.])
print data['row2']    # array([   2.,   20.,  200.])
print data['row3']    # array([   3.,   30.,  300.])

how to refresh my datagridview after I add new data

wish this will help Create Function

        private sub loaddata()
        datagridview.Datasource=nothing
        datagridview.refresh
        dim str as string = "select * from database"
      using cmd As New OleDb.OleDbCommand(str,cnn)
        using da As new OleDbDataAdapter(cmd)
          using newtable as new datatable
            da.fill (newtable)
            datagridview.datasource=newtable
          end using
       end using
     end using
end sub

App can't be opened because it is from an unidentified developer

Terminal type:

Last login: Thu Dec 20 08:28:43 on console
 ~ ? sudo spctl --master-disable
Password:
 ~ ? spctl --status
assessments disabled
 ~ ?

System Preferences->Security & Privacy

enter image description here

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

This project references NuGet package(s) that are missing on this computer

In my case it had to do with the Microsoft.Build.Bcl version. My nuget package version was 1.0.21, but my project files were still pointing to version 1.0.14

So I changed my .csproj files from:

  <Import Project="..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets" Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" />
   <Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
    <Error Condition="!Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
    <Error Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.14\tools\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
  </Target>

to:

 <Import Project="..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets" Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" />
  <Target Name="EnsureBclBuildImported" BeforeTargets="BeforeBuild" Condition="'$(BclBuildImported)' == ''">
    <Error Condition="!Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
    <Error Condition="Exists('..\..\packages\Microsoft.Bcl.Build.1.0.21\build\Microsoft.Bcl.Build.targets')" Text="The build restored NuGet packages. Build the project again to include these packages in the build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />

And the build was working again.

asp.net mvc3 return raw html to view

public ActionResult Questionnaire()
{
    return Redirect("~/MedicalHistory.html");
}

How to set top-left alignment for UILabel for iOS application?

Swift 2.0: : Using UILabel Extension

Make constant enum values in a empty Swift file.

//  AppRef.swift

import UIKit
import Foundation

enum UILabelTextPositions : String {

 case VERTICAL_ALIGNMENT_TOP = "VerticalAlignmentTop"
 case VERTICAL_ALIGNMENT_MIDDLE = "VerticalAlignmentMiddle"
 case VERTICAL_ALIGNMENT_BOTTOM = "VerticalAlignmentBottom"

}

Using UILabel Extension:

Make a empty Swift class and name it. Add the following.

//  AppExtensions.swift

import Foundation
import UIKit

    extension UILabel{ 
     func makeLabelTextPosition (sampleLabel :UILabel?, positionIdentifier : String) -> UILabel
     {
      let rect = sampleLabel!.textRectForBounds(bounds, limitedToNumberOfLines: 0)

      switch positionIdentifier
      {
      case "VerticalAlignmentTop":
       sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y, rect.size.width, rect.size.height)
       break;

      case "VerticalAlignmentMiddle":
       sampleLabel!.frame = CGRectMake(bounds.origin.x+5,bounds.origin.y + (bounds.size.height - rect.size.height) / 2,
        rect.size.width, rect.size.height);
       break;

      case "VerticalAlignmentBottom":
       sampleLabel!.frame = CGRectMake(bounds.origin.x+5, bounds.origin.y + (bounds.size.height - rect.size.height),rect.size.width, rect.size.height);
       break;

      default:
       sampleLabel!.frame = bounds;
       break;
      }
      return sampleLabel!

     }
    }

Usage :

myMessageLabel.makeLabelTextPosition(messageLabel, positionIdentifier: UILabelTextPositions.VERTICAL_ALIGNMENT_TOP.rawValue)

How to access global js variable in AngularJS directive

I created a working CodePen example demonstrating how to do this the correct way in AngularJS. The Angular $window service should be used to access any global objects since directly accessing window makes testing more difficult.

HTML:

<section ng-app="myapp" ng-controller="MainCtrl">
  Value of global variable read by AngularJS: {{variable1}}
</section>

JavaScript:

// global variable outside angular
var variable1 = true;

var app = angular.module('myapp', []);

app.controller('MainCtrl', ['$scope', '$window', function($scope, $window) {
  $scope.variable1 = $window.variable1;
}]);

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

I would start by adding the following dependency:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>4.1.4.Final</version>
</dependency>

and

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>5.2.3.Final</version>
</dependency>

UPDATE: Or simply add the following dependency.

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.0</version>
</dependency>

How do I write JSON data to a file?

To write the JSON with indentation, "pretty print":

import json

outfile = open('data.json')
json.dump(data, outfile, indent=4)

Also, if you need to debug improperly formatted JSON, and want a helpful error message, use import simplejson library, instead of import json (functions should be the same)

Find in Files: Search all code in Team Foundation Server

If you install TFS 2008 PowerTools you will get a "Find in Source Control" action in the Team Explorer right click menu.

TFS2008 Power Tools

Import Maven dependencies in IntelliJ IDEA

i was able to fix mine by adding this lines of code after the build tag in the pom.xml file, i compared it from my running project and discovered that was the difference, now i'm all good.

<repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
        </pluginRepository>
    </pluginRepositories>

Count lines in large files

I know the question is a few years old now, but expanding on Ivella's last idea, this bash script estimates the line count of a big file within seconds or less by measuring the size of one line and extrapolating from it:

#!/bin/bash
head -2 $1 | tail -1 > $1_oneline
filesize=$(du -b $1 | cut -f -1)
linesize=$(du -b $1_oneline | cut -f -1)
rm $1_oneline
echo $(expr $filesize / $linesize)

If you name this script lines.sh, you can call lines.sh bigfile.txt to get the estimated number of lines. In my case (about 6 GB, export from database), the deviation from the true line count was only 3%, but ran about 1000 times faster. By the way, I used the second, not first, line as the basis, because the first line had column names and the actual data started in the second line.

Remove an item from array using UnderscoreJS

Just using plain JavaScript, this has been answered already: remove objects from array by object property.

Using underscore.js, you could combine .findWhere with .without:

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'a'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'b'_x000D_
}, {_x000D_
  id: 3,_x000D_
  name: 'c'_x000D_
}];_x000D_
_x000D_
//substract third_x000D_
arr = _.without(arr, _.findWhere(arr, {_x000D_
  id: 3_x000D_
}));_x000D_
console.log(arr);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

Although, since you are creating a new array in this case anyway, you could simply use _.filter or the native Array.prototype.filter function (just like shown in the other question). Then you would only iterate over array once instead of potentially twice like here.

If you want to modify the array in-place, you have to use .splice. This is also shown in the other question and undescore doesn't seem to provide any useful function for that.

git ignore exception

This is how I do it, with a README.md file in each directory:

/data/*
!/data/README.md

!/data/input/
/data/input/*
!/data/input/README.md

!/data/output/
/data/output/*
!/data/output/README.md

MySQL search and replace some text in a field

 UPDATE table SET field = replace(field, text_needs_to_be_replaced, text_required);

Like for example, if I want to replace all occurrences of John by Mark I will use below,

UPDATE student SET student_name = replace(student_name, 'John', 'Mark');

C++ delete vector, objects, free memory

You can call clear, and that will destroy all the objects, but that will not free the memory. Looping through the individual elements will not help either (what action would you even propose to take on the objects?) What you can do is this:

vector<tempObject>().swap(tempVector);

That will create an empty vector with no memory allocated and swap it with tempVector, effectively deallocating the memory.

C++11 also has the function shrink_to_fit, which you could call after the call to clear(), and it would theoretically shrink the capacity to fit the size (which is now 0). This is however, a non-binding request, and your implementation is free to ignore it.

How to change the new TabLayout indicator color and height

Foto indicator use this:

 tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.colorWhite));//put your color

Is it possible to validate the size and type of input=file in html5

I could do this (demo):

<!doctype html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
    <form >
        <input type="file" id="f" data-max-size="32154" />
        <input type="submit" />
    </form>
<script>
$(function(){
    $('form').submit(function(){
        var isOk = true;
        $('input[type=file][data-max-size]').each(function(){
            if(typeof this.files[0] !== 'undefined'){
                var maxSize = parseInt($(this).attr('max-size'),10),
                size = this.files[0].size;
                isOk = maxSize > size;
                return isOk;
            }
        });
        return isOk;
    });
});
</script>
</body>
</html>

What is the string length of a GUID?

The correct thing to do here is to store it as uniqueidentifier - this is then fully indexable, etc. at the database. The next-best option would be a binary(16) column: standard GUIDs are exactly 16 bytes in length.

If you must store it as a string, the length really comes down to how you choose to encode it. As hex (AKA base-16 encoding) without hyphens it would be 32 characters (two hex digits per byte), so char(32).

However, you might want to store the hyphens. If you are short on space, but your database doesn't support blobs / guids natively, you could use Base64 encoding and remove the == padding suffix; that gives you 22 characters, so char(22). There is no need to use Unicode, and no need for variable-length - so nvarchar(max) would be a bad choice, for example.

Naming Conventions: What to name a boolean variable?

My vote would be to name it IsLast and change the functionality. If that isn't really an option, I'd leave the name as IsNotLast.

I agree with Code Complete (Use positive boolean variable names), I also believe that rules are made to be broken. The key is to break them only when you absoluately have to. In this case, none of the alternative names are as clear as the name that "breaks" the rule. So this is one of those times where breaking the rule can be okay.

There are No resources that can be added or removed from the server

if your project maven based, you can also try updating your project maven config by selecting project. Right click project> Maven>Update Project option. it will update your project config.

What is JNDI? What is its basic use? When is it used?

The best explanation to me is given here

What is JNDI

It is an API to providing access to a directory service, that is, a service mapping name (strings) with objects, reference to remote objects or simple data. This is called binding. The set of bindings is called the context. Applications use the JNDI interface to access resources.

To put it very simply, it is like a hashmap with a String key and Object values representing resources on the web.

What Issues Does JNDI Solve

Without JNDI, the location or access information of remote resources would have to be hard-coded in applications or made available in a configuration. Maintaining this information is quite tedious and error prone.

If a resources has been relocated on another server, with another IP address, for example, all applications using this resource would have to be updated with this new information. With JNDI, this is not necessary. Only the corresponding resource binding has to be updated. Applications can still access it with its name and the relocation is transparent.

How to use onClick() or onSelect() on option tag in a JSP page?

Neither the onSelect() nor onClick() events are supported by the <option> tag. The former refers to selecting text (i.e. by clicking + dragging across a text field) so can only be used with the <text> and <textarea> tags. The onClick() event can be used with <select> tags - however, you probably are looking for functionality where it would be best to use the onChange() event, not onClick().

Furthermore, by the look of your <c:...> tags, you are also trying to use JSP syntax in a plain HTML document. That's just... incorrect.

In response to your comment to this answer - I can barely understand it. However, it sounds like what you want to do is get the value of the <option> tag that the user has just selected whenever they select one. In that case, you want to have something like:

<html>
 <head>
  <script type="text/javascript">

   function changeFunc() {
    var selectBox = document.getElementById("selectBox");
    var selectedValue = selectBox.options[selectBox.selectedIndex].value;
    alert(selectedValue);
   }

  </script>
 </head>
 <body>
  <select id="selectBox" onchange="changeFunc();">
   <option value="1">Option #1</option>
   <option value="2">Option #2</option>
  </select>
 </body>
</html>

SQL (MySQL) vs NoSQL (CouchDB)

Here's a quote from a recent blog post from Dare Obasanjo.

SQL databases are like automatic transmission and NoSQL databases are like manual transmission. Once you switch to NoSQL, you become responsible for a lot of work that the system takes care of automatically in a relational database system. Similar to what happens when you pick manual over automatic transmission. Secondly, NoSQL allows you to eke more performance out of the system by eliminating a lot of integrity checks done by relational databases from the database tier. Again, this is similar to how you can get more performance out of your car by driving a manual transmission versus an automatic transmission vehicle.

However the most notable similarity is that just like most of us can’t really take advantage of the benefits of a manual transmission vehicle because the majority of our driving is sitting in traffic on the way to and from work, there is a similar harsh reality in that most sites aren’t at Google or Facebook’s scale and thus have no need for a Bigtable or Cassandra.

To which I can add only that switching from MySQL, where you have at least some experience, to CouchDB, where you have no experience, means you will have to deal with a whole new set of problems and learn different concepts and best practices. While by itself this is wonderful (I am playing at home with MongoDB and like it a lot), it will be a cost that you need to calculate when estimating the work for that project, and brings unknown risks while promising unknown benefits. It will be very hard to judge if you can do the project on time and with the quality you want/need to be successful, if it's based on a technology you don't know.

Now, if you have on the team an expert in the NoSQL field, then by all means take a good look at it. But without any expertise on the team, don't jump on NoSQL for a new commercial project.

Update: Just to throw some gasoline in the open fire you started, here are two interesting articles from people on the SQL camp. :-)

I Can't Wait for NoSQL to Die (original article is gone, here's a copy)
Fighting The NoSQL Mindset, Though This Isn't an anti-NoSQL Piece
Update: Well here is an interesting article about NoSQL
Making Sense of NoSQL

error: package javax.servlet does not exist

maybe doesnt exists javaee-api-7.0.jar. download this jar and on your project right clik

  1. on your project right click
  2. build path
  3. Configure build path
  4. Add external Jars
  5. javaee-api-7.0.jar choose
  6. Apply and finish

Loop through each row of a range in Excel

Just stumbled upon this and thought I would suggest my solution. I typically like to use the built in functionality of assigning a range to an multi-dim array (I guess it's also the JS Programmer in me).

I frequently write code like this:

Sub arrayBuilder()

myarray = Range("A1:D4")

'unlike most VBA Arrays, this array doesn't need to be declared and will be automatically dimensioned

For i = 1 To UBound(myarray)

    For j = 1 To UBound(myarray, 2)

    Debug.Print (myarray(i, j))

    Next j

Next i

End Sub

Assigning ranges to variables is a very powerful way to manipulate data in VBA.

How to redirect to action from JavaScript method?

Youcan either send a Ajax request to server or use window.location to that url.

How to output HTML from JSP <%! ... %> block?

I suppose this would help:

<%! 
   String someOutput() {
     return "Some Output";
  }
%>
...
<%= someOutput() %>

Anyway, it isn't a good idea to have code in a view.

Easy way to turn JavaScript array into comma-separated list?

Papa Parse handles commas in values and other edge cases.

(Baby Parse for Node has been deprecated - you can now use Papa Parse in the Browser and in Node.)

Eg. (node)

const csvParser = require('papaparse'); // previously you might have used babyparse
var arr = [1,null,"a,b"] ;
var csv = csvParser.unparse([arr]) ;
console.log(csv) ;

1,,"a,b"

How do I ignore ampersands in a SQL script running from SQL Plus?

According to this nice FAQ there are a couple solutions.

You might also be able to escape the ampersand with the backslash character \ if you can modify the comment.

How can I detect the touch event of an UIImageView?

To add a touch event to a UIImageView, use the following in your .m file:

UITapGestureRecognizer *newTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(myTapMethod)];

[myImageView setUserInteractionEnabled:YES];

[myImageView addGestureRecognizer:newTap];


-(void)myTapMethod{
    // Treat image tap
}

How can I produce an effect similar to the iOS 7 blur view?

Here is a really easy way of doing it:https://github.com/JagCesar/iOS-blur

Just copy the layer of UIToolbar and you're done, AMBlurView does it for you. Okay, it's not as blurry as control center, but is's blurry enough.

Remember that iOS7 is under NDA.

Swift 3 - Comparing Date objects

I have tried this snippet (in Xcode 8 Beta 6), and it is working fine.

let date1 = Date()
let date2 = Date().addingTimeInterval(100)

if date1 == date2 { ... }
else if date1 > date2 { ... }
else if date1 < date2 { ... }

read subprocess stdout line by line

Indeed, if you sorted out the iterator then buffering could now be your problem. You could tell the python in the sub-process not to buffer its output.

proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)

becomes

proc = subprocess.Popen(['python','-u', 'fake_utility.py'],stdout=subprocess.PIPE)

I have needed this when calling python from within python.

How to Identify Microsoft Edge browser via CSS?

/* Microsoft Edge Browser 12-18 (All versions before Chromium) - one-liner method */

_:-ms-lang(x), _:-webkit-full-screen, .selector { property:value; }

That works great!

// for instance:
_:-ms-lang(x), _:-webkit-full-screen, .headerClass 
{ 
  border: 1px solid brown;
}

https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/

Can I use CASE statement in a JOIN condition?

I took your example and edited it:

SELECT  *
FROM    sys.indexes i
    JOIN sys.partitions p
        ON i.index_id = p.index_id 
    JOIN sys.allocation_units a
        ON a.container_id = (CASE
           WHEN a.type IN (1, 3)
               THEN p.hobt_id 
           WHEN a.type IN (2)
               THEN p.partition_id
           ELSE NULL
           END)

intelliJ IDEA 13 error: please select Android SDK

Delete all android SDKs from Intellij and add them again.

To do this open project structure, in SDK pane, delete all android SDK, click OK. open project structure and add them again.

Formula to check if string is empty in Crystal Reports

On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:

{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}