Programs & Examples On #H2

H2 is a relational database management system written in Java. It can be embedded in Java applications or run in the client-server mode. H2 supports regular disk-based as well as in-memory databases.

How to find rows in one table that have no corresponding row in another table

You have to check every ID in tableA against every ID in tableB. A fully featured RDBMS (such as Oracle) would be able to optimize that into an INDEX FULL FAST SCAN and not touch the table at all. I don't know whether H2's optimizer is as smart as that.

H2 does support the MINUS syntax so you should try this

select id from tableA
minus
select id from tableB
order by id desc

That may perform faster; it is certainly worth benchmarking.

Frontend tool to manage H2 database

I use DbVisualizer a lot for H2-db administration.

There exists a free version:

https://www.dbvis.com/download/

H2 in-memory database. Table not found

I have tried adding ;DATABASE_TO_UPPER=false parameter, which it did work a single test, but what did the trick for me was ;CASE_INSENSITIVE_IDENTIFIERS=TRUE.

At the I had: jdbc:h2:mem:testdb;CASE_INSENSITIVE_IDENTIFIERS=TRUE

Moreover, the problem for me was when I upgraded to Spring Boot 2.4.1.

Spring Boot default H2 jdbc connection (and H2 console)

I found that with spring boot 2.0.2.RELEASE, configuring spring-boot-starter-data-jpa and com.h2database in the POM file is not just enough to have H2 console working. You must configure spring-boot-devtools as below. Optionally you could follow the instruction from Aaron Zeckoski in this post

  <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
 </dependency>

H2 database error: Database may be already in use: "Locked by another process"

You can also visit the "Preferences" tab from the H2 Console and shutdown all active sessions by pressing the shutdown button.

Can I have H2 autocreate a schema in an in-memory database?

If you are using spring with application.yml the following will work for you

spring: datasource: url: jdbc:h2:mem:mydb;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS calendar

View content of H2 or HSQLDB in-memory database

I don't know why is it working fine at yours machines, but I had to spend a day in order to get it is working.

The server works with Intellij Idea U via url "jdbc:h2:tcp://localhost:9092/~/default".

"localhost:8082" in the browser alse works fine.

I added this into the mvc-dispatcher-servlet.xml

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" depends-on="h2Server">
    <property name="driverClassName" value="org.h2.Driver"/>
    <property name="url" value="jdbc:h2:tcp://localhost:9092/~/default"/>
    <property name="username" value="sa"/>
    <property name="password" value=""/>
</bean>

<bean id="h2Server" class="org.h2.tools.Server" factory-method="createTcpServer" init-method="start" destroy-method="stop" depends-on="h2WebServer">
    <constructor-arg>
        <array>
            <value>-tcp</value>
            <value>-tcpAllowOthers</value>
            <value>-tcpPort</value>
            <value>9092</value>
        </array>
    </constructor-arg>
</bean>

<bean id="h2WebServer" class="org.h2.tools.Server" factory-method="createWebServer" init-method="start" destroy-method="stop">
    <constructor-arg>
        <array>
            <value>-web</value>
            <value>-webAllowOthers</value>
            <value>-webPort</value>
            <value>8082</value>
        </array>
    </constructor-arg>
</bean>

Create HTTP post request and receive response using C# console application

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace WebserverInteractionClassLibrary
{
    public class RequestManager
    {
        public string LastResponse { protected set; get; }

        CookieContainer cookies = new CookieContainer();

        internal string GetCookieValue(Uri SiteUri,string name)
        {
            Cookie cookie = cookies.GetCookies(SiteUri)[name];
            return (cookie == null) ? null : cookie.Value;
        }

        public string GetResponseContent(HttpWebResponse response)
        {
            if (response == null)
            {
                throw new ArgumentNullException("response");
            }
            Stream dataStream = null;
            StreamReader reader = null;
            string responseFromServer = null;

            try
            {
                // Get the stream containing content returned by the server.
                dataStream = response.GetResponseStream();
                // Open the stream using a StreamReader for easy access.
                reader = new StreamReader(dataStream);
                // Read the content.
                responseFromServer = reader.ReadToEnd();
                // Cleanup the streams and the response.
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {                
                if (reader != null)
                {
                    reader.Close();
                }
                if (dataStream != null)
                {
                    dataStream.Close();
                }
                response.Close();
            }
            LastResponse = responseFromServer;
            return responseFromServer;
        }

        public HttpWebResponse SendPOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GeneratePOSTRequest(uri, content, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateGETRequest(uri, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebResponse SendRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            HttpWebRequest request = GenerateRequest(uri, content, method, login, password, allowAutoRedirect);
            return GetResponse(request);
        }

        public HttpWebRequest GenerateGETRequest(string uri, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, null, "GET", null, null, allowAutoRedirect);
        }

        public HttpWebRequest GeneratePOSTRequest(string uri, string content, string login, string password, bool allowAutoRedirect)
        {
            return GenerateRequest(uri, content, "POST", null, null, allowAutoRedirect);
        }

        internal HttpWebRequest GenerateRequest(string uri, string content, string method, string login, string password, bool allowAutoRedirect)
        {
            if (uri == null)
            {
                throw new ArgumentNullException("uri");
            }
            // Create a request using a URL that can receive a post. 
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            // Set the Method property of the request to POST.
            request.Method = method;
            // Set cookie container to maintain cookies
            request.CookieContainer = cookies;
            request.AllowAutoRedirect = allowAutoRedirect;
            // If login is empty use defaul credentials
            if (string.IsNullOrEmpty(login))
            {
                request.Credentials = CredentialCache.DefaultNetworkCredentials;
            }
            else
            {
                request.Credentials = new NetworkCredential(login, password);
            }
            if (method == "POST")
            {
                // Convert POST data to a byte array.
                byte[] byteArray = Encoding.UTF8.GetBytes(content);
                // Set the ContentType property of the WebRequest.
                request.ContentType = "application/x-www-form-urlencoded";
                // Set the ContentLength property of the WebRequest.
                request.ContentLength = byteArray.Length;
                // Get the request stream.
                Stream dataStream = request.GetRequestStream();
                // Write the data to the request stream.
                dataStream.Write(byteArray, 0, byteArray.Length);
                // Close the Stream object.
                dataStream.Close();
            }
            return request;
        }

        internal HttpWebResponse GetResponse(HttpWebRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse)request.GetResponse();                
                cookies.Add(response.Cookies);                
                // Print the properties of each cookie.
                Console.WriteLine("\nCookies: ");
                foreach (Cookie cook in cookies.GetCookies(request.RequestUri))
                {
                    Console.WriteLine("Domain: {0}, String: {1}", cook.Domain, cook.ToString());
                }
            }
            catch (WebException ex)
            {
                Console.WriteLine("Web exception occurred. Status code: {0}", ex.Status);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return response;
        }

    }
}

Converting a char to ASCII?

A char is an integral type. When you write

char ch = 'A';

you're setting the value of ch to whatever number your compiler uses to represent the character 'A'. That's usually the ASCII code for 'A' these days, but that's not required. You're almost certainly using a system that uses ASCII.

Like any numeric type, you can initialize it with an ordinary number:

char ch = 13;

If you want do do arithmetic on a char value, just do it: ch = ch + 1; etc.

However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char values as characters rather than numbers. There are a couple of ways to do that.

std::cout << +ch << '\n';
std::cout << int(ch) << '\n'

error: strcpy was not declared in this scope

This error sometimes occurs in a situation like this:

#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif

static void init_random(uint32_t initseed=0)
{
    if (initseed==0)
    {
        struct timeval tv;
        gettimeofday(&tv, NULL);
        seed=(uint32_t) (4223517*getpid()*tv.tv_sec*tv.tv_usec);
    }
    else
        seed=initseed;
#if !defined(CYGWIN) && !defined(__INTERIX)
    //seed=42
    //SG_SPRINT("initializing random number generator with %d (seed size %d)\n", seed, RNG_SEED_SIZE)
    initstate(seed, CMath::rand_state, RNG_SEED_SIZE);
#endif
}

If the following code lines not run in the run-time:

#ifndef NAN
#include <stdlib.h>
#define NAN (strtod("NAN",NULL))
#endif

you will face with an error in your code like something as follows; because initstate is placed in the stdlib.h file and it's not included:

In file included from ../../shogun/features/SubsetStack.h:14:0, 
                 from ../../shogun/features/Features.h:21, 
                 from ../../shogun/ui/SGInterface.h:7, 
                 from MatlabInterface.h:15, 
                 from matlabInterface.cpp:7: 
../../shogun/mathematics/Math.h: In static member function 'static void shogun::CMath::init_random(uint32_t)': 
../../shogun/mathematics/Math.h:459:52: error: 'initstate' was not declared in this scope

Finding diff between current and last version

You can do it this way too:

Compare with the previous commit

git diff --name-status HEAD~1..HEAD

Compare with the current and previous two commits

git diff --name-status HEAD~2..HEAD

C++ String Concatenation operator<<

nametext = "Your name is" + name;

I think this should do

Protect image download

There is no full-proof method to prevent your images being downloaded/stolen.

But, some solutions like: watermarking your images(from client side or server side), implement a background image, disable/prevent right clicks, slice images into small pieces and then present as a complete image to browser, you can also use flash to show images.

Personally, recommended methods are: Watermarking and flash. But it is a difficult and almost impossible mission to accomplish. As long as user is able to "see" that image, means they take "screenshot" to steal the image.

How to Disable landscape mode in Android?

Use this in onCreate() of the Activity

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

Setting custom UITableViewCells height

in a custom UITableViewCell -controller add this

-(void)layoutSubviews {  

    CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);

    self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame;
    self.frame = newCellViewFrame;

    [super layoutSubviews];
}

In the UITableView -controller add this

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [indexPath row] * 1.5; // your dynamic height...
}

Python main call within class

Remember, you are NOT allowed to do this.

class foo():
    def print_hello(self):
        print("Hello")       # This next line will produce an ERROR!
    self.print_hello()       # <---- it calls a class function, inside a class,
                             # but outside a class function. Not allowed.

You must call a class function from either outside the class, or from within a function in that class.

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

To allow guest access remotely, write this

[{rabbit, [{loopback_users, []}]}].

to here

c:\Users\[your user name]\AppData\Roaming\RabbitMQ\rabbitmq.config

then restart the rabbitmq windows service (Source https://www.rabbitmq.com/access-control.html)

Check for internet connection with Swift

I have checked out implementing Ashley Mill's Reachability class without Cocoa Pods/Dependancy Manager. The idea is to make the Reachability dependency free in the project.

Xcode 7.2 - Swift 2.1

1) https://github.com/ashleymills/Reachability.swift. Download add the Reachability class to the project .

Note: While adding, please make sure 'copy items if needed' is ticked.

2) Make an AppManager.swift class . This class will cater as Public Model class where public methods & data will be added and can be utilised in any VC.

//  AppManager.swift

import UIKit
import Foundation

class AppManager: NSObject{
    var delegate:AppManagerDelegate? = nil
    private var _useClosures:Bool = false
    private var reachability: Reachability?
    private var _isReachability:Bool = false
    private var _reachabiltyNetworkType :String?

    var isReachability:Bool {
        get {return _isReachability}
    }  
   var reachabiltyNetworkType:String {
    get {return _reachabiltyNetworkType! }
   }   




    // Create a shared instance of AppManager
    final  class var sharedInstance : AppManager {
        struct Static {
            static var instance : AppManager?
        }
        if !(Static.instance != nil) {
            Static.instance = AppManager()

        }
        return Static.instance!
    }

    // Reachability Methods
    func initRechabilityMonitor() {
        print("initialize rechability...")
        do {
            let reachability = try Reachability.reachabilityForInternetConnection()
            self.reachability = reachability
        } catch ReachabilityError.FailedToCreateWithAddress(let address) {
            print("Unable to create\nReachability with address:\n\(address)")
            return
        } catch {}
        if (_useClosures) {
            reachability?.whenReachable = { reachability in
                self.notifyReachability(reachability)
            }
            reachability?.whenUnreachable = { reachability in
                self.notifyReachability(reachability)
            }
        } else {
            self.notifyReachability(reachability!)
        }

        do {
            try reachability?.startNotifier()
        } catch {
            print("unable to start notifier")
            return
        }


    }        
    private func notifyReachability(reachability:Reachability) {
        if reachability.isReachable() {
            self._isReachability = true

//Determine Network Type 
      if reachability.isReachableViaWiFi() {   
        self._reachabiltyNetworkType = CONNECTION_NETWORK_TYPE.WIFI_NETWORK.rawValue
      } else {
        self._reachabiltyNetworkType = CONNECTION_NETWORK_TYPE.WWAN_NETWORK.rawValue
      }

        } else {
            self._isReachability = false
self._reachabiltyNetworkType = CONNECTION_NETWORK_TYPE.OTHER.rawValue

        }

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
    }
    func reachabilityChanged(note: NSNotification) {
        let reachability = note.object as! Reachability
        dispatch_async(dispatch_get_main_queue()) {
            if (self._useClosures) {
                self.reachability?.whenReachable = { reachability in
                    self.notifyReachability(reachability)
                }
                self.reachability?.whenUnreachable = { reachability in
                    self.notifyReachability(reachability)
                }
            } else {
                self.notifyReachability(reachability)
            }
            self.delegate?.reachabilityStatusChangeHandler(reachability)
        }
    }
    deinit {
        reachability?.stopNotifier()
        if (!_useClosures) {
            NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
        }
    }
}

3) Make a Delegate Class. I use delegate method to notify the connectivity status.

//  Protocols.swift

import Foundation
@objc protocol AppManagerDelegate:NSObjectProtocol {

    func reachabilityStatusChangeHandler(reachability:Reachability)
}

4) Make Parent class of UIViewController (Inheritance method). The parent class have methods which are accessible all child VCs.

//  UIappViewController.swift

    import UIKit

    class UIappViewController: UIViewController,AppManagerDelegate {
        var manager:AppManager = AppManager.sharedInstance

        override func viewDidLoad() {
            super.viewDidLoad()
            manager.delegate = self
        }
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
        }
        func reachabilityStatusChangeHandler(reachability: Reachability) {
            if reachability.isReachable() {
                print("isReachable")
            } else {
                print("notReachable")
            }
        }
    }

5) Start Real time Internet Connectivity Monitoring in AppDelegate.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    AppManager.sharedInstance.initRechabilityMonitor()
return true
}

6) I have added a Swift File Name AppReference to store constant enum values.

//  AppReference.swift

import Foundation

enum CONNECTION_NETWORK_TYPE : String {

  case WIFI_NETWORK = "Wifi"
  case WWAN_NETWORK = "Cellular"
  case OTHER = "Other"

}

7) On ViewController (ex. You want to call an API only if network is available)

//  ViewController.swift

        import UIKit

class ViewController: UIappViewController {
  var reachability:Reachability?

  override func viewDidLoad() {
    super.viewDidLoad()
    manager.delegate = self

    if(AppManager.sharedInstance.isReachability)
    {
      print("net available")
      //call API from here.

    } else {
      dispatch_async(dispatch_get_main_queue()) {
        print("net not available")
        //Show Alert
      }
    }


    //Determine Network Type
    if(AppManager.sharedInstance.reachabiltyNetworkType == "Wifi")
    {
      print(".Wifi")
    }
    else if (AppManager.sharedInstance.reachabiltyNetworkType == "Cellular")
    {
      print(".Cellular")
    }
    else {
      dispatch_async(dispatch_get_main_queue()) {
        print("Network not reachable")
      }
    }

  }
  override func viewWillAppear(animated: Bool) {
  }
  override func didReceiveMemoryWarning() {
  }
}

The sample can be downloaded @ https://github.com/alvinreuben/Reachability-Sample

Upgraded to Swift 3.1- https://github.com/alvinvgeorge/Reachability-UpgradedToSwift3

When should we call System.exit in Java

The method never returns because it's the end of the world and none of your code is going to be executed next.

Your application, in your example, would exit anyway at the same spot in the code, but, if you use System.exit. you have the option of returning a custom code to the enviroment, like, say

System.exit(42);

Who is going to make use of your exit code? A script that called the application. Works in Windows, Unix and all other scriptable environments.

Why return a code? To say things like "I did not succeed", "The database did not answer".

To see how to get the value od an exit code and use it in a unix shell script or windows cmd script, you might check this answer on this site

How to send an email with Gmail as provider using Python?

def send_email(user, pwd, recipient, subject, body):
    import smtplib

    FROM = user
    TO = recipient if isinstance(recipient, list) else [recipient]
    SUBJECT = subject
    TEXT = body

    # Prepare actual message
    message = """From: %s\nTo: %s\nSubject: %s\n\n%s
    """ % (FROM, ", ".join(TO), SUBJECT, TEXT)
    try:
        server = smtplib.SMTP("smtp.gmail.com", 587)
        server.ehlo()
        server.starttls()
        server.login(user, pwd)
        server.sendmail(FROM, TO, message)
        server.close()
        print 'successfully sent the mail'
    except:
        print "failed to send mail"

if you want to use Port 465 you have to create an SMTP_SSL object:

# SMTP_SSL Example
server_ssl = smtplib.SMTP_SSL("smtp.gmail.com", 465)
server_ssl.ehlo() # optional, called by login()
server_ssl.login(gmail_user, gmail_pwd)  
# ssl server doesn't support or need tls, so don't call server_ssl.starttls() 
server_ssl.sendmail(FROM, TO, message)
#server_ssl.quit()
server_ssl.close()
print 'successfully sent the mail'

Python: TypeError: object of type 'NoneType' has no len()

I was faces this issue but after change object into str, problem solved. str(fname).isalpha():

How to turn off gcc compiler optimization to enable buffer overflow

I won't quote the entire page but the whole manual on optimisation is available here: http://gcc.gnu.org/onlinedocs/gcc-4.4.3/gcc/Optimize-Options.html#Optimize-Options

From the sounds of it you want at least -O0, the default, and:

-fmudflap -fmudflapth -fmudflapir

For front-ends that support it (C and C++), instrument all risky pointer/array dereferencing operations, some standard library string/heap functions, and some other associated constructs with range/validity tests. Modules so instrumented should be immune to buffer overflows, invalid heap use, and some other classes of C/C++ programming errors. The instrumentation relies on a separate runtime library (libmudflap), which will be linked into a program if -fmudflap is given at link time. Run-time behavior of the instrumented program is controlled by the MUDFLAP_OPTIONS environment variable. See env MUDFLAP_OPTIONS=-help a.out for its options.

bash: pip: command not found

What I did to overcome this was sudo apt install python-pip.

It turned out my virtual machine did not have pip installed yet. It's conceivable that other people could have this scenario too.

C++ template constructor

template<class...>struct types{using type=types;};
template<class T>struct tag{using type=T;};
template<class Tag>using type_t=typename Tag::type;

the above helpers let you work with types as values.

class A {
  template<class T>
  A( tag<T> );
};

the tag<T> type is a variable with no state besides the type it caries. You can use this to pass a pure-type value into a template function and have the type be deduced by the template function:

auto a = A(tag<int>{});

You can pass in more than one type:

class A {
  template<class T, class U, class V>
  A( types<T,U,V> );
};
auto a = A(types<int,double,std::string>{});

How does strcmp() work?

The pseudo-code "implementation" of strcmp would go something like:

define strcmp (s1, s2):
    p1 = address of first character of str1
    p2 = address of first character of str2

    while contents of p1 not equal to null:
        if contents of p2 equal to null: 
            return 1

        if contents of p2 greater than contents of p1:
            return -1

        if contents of p1 greater than contents of p2:
            return 1

        advance p1
        advance p2

    if contents of p2 not equal to null:
        return -1

    return 0

That's basically it. Each character is compared in turn an a decision is made as to whether the first or second string is greater, based on that character.

Only if the characters are identical do you move to the next character and, if all the characters were identical, zero is returned.

Note that you may not necessarily get 1 and -1, the specs say that any positive or negative value will suffice, so you should always check the return value with < 0, > 0 or == 0.

Turning that into real C would be relatively simple:

int myStrCmp (const char *s1, const char *s2) {
    const unsigned char *p1 = (const unsigned char *)s1;
    const unsigned char *p2 = (const unsigned char *)s2;

    while (*p1 != '\0') {
        if (*p2 == '\0') return  1;
        if (*p2 > *p1)   return -1;
        if (*p1 > *p2)   return  1;

        p1++;
        p2++;
    }

    if (*p2 != '\0') return -1;

    return 0;
}

Also keep in mind that "greater" in the context of characters is not necessarily based on simple ASCII ordering for all string functions.

C has a concept called 'locales' which specify (among other things) collation, or ordering of the underlying character set and you may find, for example, that the characters a, á, à and ä are all considered identical. This will happen for functions like strcoll.

How can I get input radio elements to horizontally align?

This also works like a charm

_x000D_
_x000D_
<form>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio" checked>Option 1_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 2_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 3_x000D_
    </label>_x000D_
  </form>
_x000D_
_x000D_
_x000D_

Correct way to convert size in bytes to KB, MB, GB in JavaScript

I just wanted to share my input. I had this problem so my solution is this. This will convert lower units to higher units and vice versa just supply the argument toUnit and fromUnit

export function fileSizeConverter(size: number, fromUnit: string, toUnit: string ): number | string {
  const units: string[] = ['B', 'KB', 'MB', 'GB', 'TB'];
  const from = units.indexOf(fromUnit.toUpperCase());
  const to = units.indexOf(toUnit.toUpperCase());
  const BASE_SIZE = 1024;
  let result: number | string = 0;

  if (from < 0 || to < 0 ) { return result = 'Error: Incorrect units'; }

  result = from < to ? size / (BASE_SIZE ** to) : size * (BASE_SIZE ** from);

  return result.toFixed(2);
}

I got the idea from here

Convert dictionary to bytes and back again python?

If you need to convert the dictionary to binary, you need to convert it to a string (JSON) as described in the previous answer, then you can convert it to binary.

For example:

my_dict = {'key' : [1,2,3]}

import json
def dict_to_binary(the_dict):
    str = json.dumps(the_dict)
    binary = ' '.join(format(ord(letter), 'b') for letter in str)
    return binary


def binary_to_dict(the_binary):
    jsn = ''.join(chr(int(x, 2)) for x in the_binary.split())
    d = json.loads(jsn)  
    return d

bin = dict_to_binary(my_dict)
print bin

dct = binary_to_dict(bin)
print dct

will give the output

1111011 100010 1101011 100010 111010 100000 1011011 110001 101100 100000 110010 101100 100000 110011 1011101 1111101

{u'key': [1, 2, 3]}

The 'Access-Control-Allow-Origin' header contains multiple values

Apache Server:

I spend the same, but it was because I had no quotation marks (") the asterisk in my file that provided access to the server, eg '.htaccess.':

Header add Access-Control-Allow-Origin: * 
Header add Access-Control-Allow-Origin "*" 

You may also have a file '.htaccess' in a folder with another '.htaccess' out, eg

/ 
- .htaccess 
- public_html / .htaccess (problem here)

In your case instead of '*' asterisk would be the ip (http://127.0.0.1:9000) server that you give permission to serve data.

ASP.NET:

Check that there is no 'Access-Control-Allow-Origin' duplicate in your code.

Developer Tools:

With Chrome you can verify your request headers. Press the F12 key and go to the 'Network' tab, now run the AJAX request and will appear on the list, click and give all the information is there.

Access-Control-Allow-Origin: *

How do I update an entity using spring-data-jpa?

This is how I solved the problem:

User inbound = ...
User existing = userRepository.findByFirstname(inbound.getFirstname());
if(existing != null) inbound.setId(existing.getId());
userRepository.save(inbound);

Can dplyr join on multiple columns or composite key?

Updating to use tibble()

You can pass a named vector of length greater than 1 to the by argument of left_join():

library(dplyr)

d1 <- tibble(
  x = letters[1:3],
  y = LETTERS[1:3],
  a = rnorm(3)
  )

d2 <- tibble(
  x2 = letters[3:1],
  y2 = LETTERS[3:1],
  b = rnorm(3)
  )

left_join(d1, d2, by = c("x" = "x2", "y" = "y2"))

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Enter the original date into a Date object and then print out the result with a DateFormat. You may have to split up the string into smaller pieces to create the initial Date object, if the automatic parse method does not accept your format.

Pseudocode:

Date inputDate = convertYourInputIntoADateInWhateverWayYouPrefer(inputString);
DateFormat outputFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss.SSS");
String outputString = outputFormat.format(inputDate);

Passing a varchar full of comma delimited values to a SQL Server IN function

I've written a stored procedure to show how to do this before. You basically have to process the string. I tried to post the code here but the formatting got all screwy.

IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = object_id(N'[dbo].[uspSplitTextList]') AND OBJECTPROPERTY(id, N'IsProcedure') = 1)
   DROP PROCEDURE [dbo].[uspSplitTextList]
GO

SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO


/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
-- uspSplitTextList
--
-- Description:
--    splits a separated list of text items and returns the text items
--
-- Arguments:
--    @list_text        - list of text items
--    @Delimiter        - delimiter
--
-- Notes:
-- 02/22/2006 - WSR : use DATALENGTH instead of LEN throughout because LEN doesn't count trailing blanks
--
-- History:
-- 02/22/2006 - WSR : revised algorithm to account for items crossing 8000 character boundary
-- 09/18/2006 - WSR : added to this project
--
CREATE PROCEDURE uspSplitTextList
   @list_text           text,
   @Delimiter           varchar(3)
AS

SET NOCOUNT ON

DECLARE @InputLen       integer         -- input text length
DECLARE @TextPos        integer         -- current position within input text
DECLARE @Chunk          varchar(8000)   -- chunk within input text
DECLARE @ChunkPos       integer         -- current position within chunk
DECLARE @DelimPos       integer         -- position of delimiter
DECLARE @ChunkLen       integer         -- chunk length
DECLARE @DelimLen       integer         -- delimiter length
DECLARE @ItemBegPos     integer         -- item starting position in text
DECLARE @ItemOrder      integer         -- item order in list
DECLARE @DelimChar      varchar(1)      -- first character of delimiter (simple delimiter)

-- create table to hold list items
-- actually their positions because we may want to scrub this list eliminating bad entries before substring is applied
CREATE TABLE #list_items ( item_order integer, item_begpos integer, item_endpos integer )

-- process list
IF @list_text IS NOT NULL
   BEGIN

   -- initialize
   SET @InputLen = DATALENGTH(@list_text)
   SET @TextPos = 1
   SET @DelimChar = SUBSTRING(@Delimiter, 1, 1)
   SET @DelimLen = DATALENGTH(@Delimiter)
   SET @ItemBegPos = 1
   SET @ItemOrder = 1
   SET @ChunkLen = 1

   -- cycle through input processing chunks
   WHILE @TextPos <= @InputLen AND @ChunkLen <> 0
      BEGIN

      -- get current chunk
      SET @Chunk = SUBSTRING(@list_text, @TextPos, 8000)

      -- setup initial variable values
      SET @ChunkPos = 1
      SET @ChunkLen = DATALENGTH(@Chunk)
      SET @DelimPos = CHARINDEX(@DelimChar, @Chunk, @ChunkPos)

      -- loop over the chunk, until the last delimiter
      WHILE @ChunkPos <= @ChunkLen AND @DelimPos <> 0
         BEGIN

         -- see if this is a full delimiter
         IF SUBSTRING(@list_text, (@TextPos + @DelimPos - 1), @DelimLen) = @Delimiter
            BEGIN

            -- insert position
            INSERT INTO #list_items (item_order, item_begpos, item_endpos)
            VALUES (@ItemOrder, @ItemBegPos, (@TextPos + @DelimPos - 1) - 1)

            -- adjust positions
            SET @ItemOrder = @ItemOrder + 1
            SET @ItemBegPos = (@TextPos + @DelimPos - 1) + @DelimLen
            SET @ChunkPos = @DelimPos + @DelimLen

            END
         ELSE
            BEGIN

            -- adjust positions
            SET @ChunkPos = @DelimPos + 1

            END

         -- find next delimiter      
         SET @DelimPos = CHARINDEX(@DelimChar, @Chunk, @ChunkPos)

         END

      -- adjust positions
      SET @TextPos = @TextPos + @ChunkLen

      END

   -- handle last item
   IF @ItemBegPos <= @InputLen
      BEGIN

      -- insert position
      INSERT INTO #list_items (item_order, item_begpos, item_endpos)
      VALUES (@ItemOrder, @ItemBegPos, @InputLen)

      END

   -- delete the bad items
   DELETE FROM #list_items
   WHERE item_endpos < item_begpos

   -- return list items
   SELECT SUBSTRING(@list_text, item_begpos, (item_endpos - item_begpos + 1)) AS item_text, item_order, item_begpos, item_endpos
   FROM #list_items
   ORDER BY item_order

   END

DROP TABLE #list_items

RETURN

/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

How to programmatically set the Image source

Try to assign the image that way instead:

imgFavorito.Source = new BitmapImage(new Uri(base.BaseUri, @"/Assets/favorited.png"));

Open a local HTML file using window.open in Chrome

window.location.href = 'file://///fileserver/upload/Old_Upload/05_06_2019/THRESHOLD/BBH/Look/chrs/Delia';

Nothing Worked for me.

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

Is it possible to install another version of Python to Virtualenv?

Full guide with pyenv

If pyenv is not installed then install it with pyenv-installer:

$ curl https://pyenv.run | bash

To use any custom python version, e.g. 3.5.6 use the following:

pyenv install 3.5.6
pyenv virtualenv 3.5.6 NAME_OF_YOUR_ENV
cd YOUR_PROJECT_PATH
pyenv local NAME_OF_YOUR_ENV

Linq with group by having count

For anyone looking to do this in vb (as I was and couldn't find anything)

From c In db.Company 
Select c.Name Group By Name Into Group 
Where Group.Count > 1

Responsively change div size keeping aspect ratio

Bumming off Chris's idea, another option is to use pseudo elements so you don't need to use an absolutely positioned internal element.

<style>
.square {
    /* width within the parent.
       can be any percentage. */
    width: 100%;
}
.square:before {
    content: "";
    float: left;

    /* essentially the aspect ratio. 100% means the
       div will remain 100% as tall as it is wide, or
       square in other words.  */
    padding-bottom: 100%;
}
/* this is a clearfix. you can use whatever
   clearfix you usually use, add
   overflow:hidden to the parent element,
   or simply float the parent container. */
.square:after {
    content: "";
    display: table;
    clear: both;
}
</style>
<div class="square">
  <h1>Square</h1>
  <p>This div will maintain its aspect ratio.</p>
</div>

I've put together a demo here: http://codepen.io/tcmulder/pen/iqnDr


EDIT:

Now, bumming off of Isaac's idea, it's easier in modern browsers to simply use vw units to force aspect ratio (although I wouldn't also use vh as he does or the aspect ratio will change based on window height).

So, this simplifies things:

<style>
.square {
    /* width within the parent (could use vw instead of course) */
    width: 50%;
    /* set aspect ratio */
    height: 50vw;
}
</style>
<div class="square">
  <h1>Square</h1>
  <p>This div will maintain its aspect ratio.</p>
</div>

I've put together a modified demo here: https://codepen.io/tcmulder/pen/MdojRG?editors=1100

You could also set max-height, max-width, and/or min-height, min-width if you don't want it to grow ridiculously big or small, since it's based on the browser's width now and not the container and will grow/shrink indefinitely.

Note you can also scale the content inside the element if you set the font size to a vw measurement and all the innards to em measurements, and here's a demo for that: https://codepen.io/tcmulder/pen/VBJqLV?editors=1100

Check if a string within a list contains a specific string with Linq

If yoou use Contains, you could get false positives. Suppose you have a string that contains such text: "My text data Mdd LH" Using Contains method, this method will return true for call. The approach is use equals operator:

bool exists = myStringList.Any(c=>c == "Mdd LH")

Run ScrollTop with offset of element by ID

No magic involved, just subtract from the offset top of the element

$('html, body').animate({scrollTop: $('#contact').offset().top -100 }, 'slow');

How to print Two-Dimensional Array like table

Just for the records, Java 8 provides a better alternative.

int[][] table = new int[][]{{2,4,5},{6,34,7},{23,57,2}};

System.out.println(Stream.of(table)
    .map(rowParts -> Stream.of(rowParts
    .map(element -> ((Integer)element).toString())
        .collect(Collectors.joining("\t")))
    .collect(Collectors.joining("\n")));

Failed to authenticate on SMTP server error using gmail

If you still get this error when sending email: "Failed to authenticate on SMTP server with username "[email protected]" using 3 possible authenticators"

You may try one of these methods:

  1. Go to https://accounts.google.com/UnlockCaptcha, click continue and unlock your account for access through other media/sites.

  2. Using a double quote password: "your password" <-- this one also solved my problem.

Update built-in vim on Mac OS X

brew install vim --override-system-vi

How to Define Callbacks in Android?

to clarify a bit on dragon's answer (since it took me a while to figure out what to do with Handler.Callback):

Handler can be used to execute callbacks in the current or another thread, by passing it Messages. the Message holds data to be used from the callback. a Handler.Callback can be passed to the constructor of Handler in order to avoid extending Handler directly. thus, to execute some code via callback from the current thread:

Message message = new Message();
<set data to be passed to callback - eg message.obj, message.arg1 etc - here>

Callback callback = new Callback() {
    public boolean handleMessage(Message msg) {
        <code to be executed during callback>
    }
};

Handler handler = new Handler(callback);
handler.sendMessage(message);

EDIT: just realized there's a better way to get the same result (minus control of exactly when to execute the callback):

post(new Runnable() {
    @Override
    public void run() {
        <code to be executed during callback>
    }
});

How to select a single child element using jQuery?

Not jQuery, as the question asks for, but natively (i.e., no libraries required) I think the better tool for the job is querySelector to get a single instance of a selector:

let el = document.querySelector('img');
console.log(el);

For all matching instances, use document.querySelectorAll(), or for those within another element you can chain as follows:

// Get some wrapper, with class="parentClassName"
let parentEl = document.querySelector('.parentClassName');
// Get all img tags within the parent element by parentEl variable
let childrenEls = parentEl.querySelectorAll('img');

Note the above is equivalent to:

let childrenEls = document.querySelector('.parentClassName').querySelectorAll('img');

Numpy: Get random set of rows from 2D array

This is a similar answer to the one Hezi Rasheff provided, but simplified so newer python users understand what's going on (I noticed many new datascience students fetch random samples in the weirdest ways because they don't know what they are doing in python).

You can get a number of random indices from your array by using:

indices = np.random.choice(A.shape[0], amount_of_samples, replace=False)

You can then use fancy indexing with your numpy array to get the samples at those indices:

A[indices]

This will get you the specified number of random samples from your data.

Store multiple values in single key in json

{
  "number" : ["1","2","3"],
  "alphabet" : ["a", "b", "c"]
}

Is there a way to style a TextView to uppercase all of its letters?

It is really very disappointing that you can't do it with styles (<item name="android:textAllCaps">true</item>) or on each XML layout file with the textAllCaps attribute, and the only way to do it is actually using theString.toUpperCase() on each of the strings when you do a textViewXXX.setText(theString).

In my case, I did not wanted to have theString.toUpperCase() everywhere in my code but to have a centralized place to do it because I had some Activities and lists items layouts with TextViews that where supposed to be capitalized all the time (a title) and other who did not... so... some people may think is an overkill, but I created my own CapitalizedTextView class extending android.widget.TextView and overrode the setText method capitalizing the text on the fly.

At least, if the design changes or I need to remove the capitalized text in future versions, I just need to change to normal TextView in the layout files.

Now, take in consideration that I did this because the App's Designer actually wanted this text (the titles) in CAPS all over the App no matter the original content capitalization, and also I had other normal TextViews where the capitalization came with the the actual content.

This is the class:

package com.realactionsoft.android.widget;

import android.content.Context; 
import android.util.AttributeSet; 
import android.view.ViewTreeObserver; 
import android.widget.TextView;


public class CapitalizedTextView extends TextView implements ViewTreeObserver.OnPreDrawListener {

    public CapitalizedTextView(Context context) {
        super(context);
    }

    public CapitalizedTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

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

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text.toString().toUpperCase(), type);
    }

}

And whenever you need to use it, just declare it with all the package in the XML layout:

<com.realactionsoft.android.widget.CapitalizedTextView 
        android:id="@+id/text_view_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

Some will argue that the correct way to style text on a TextView is to use a SpannableString, but I think that would be even a greater overkill, not to mention more resource-consuming because you'll be instantiating another class than TextView.

Display text on MouseOver for image in html

You can do like this also:

HTML:

<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ' onmouseover="somefunction();"></a>

In javascript:

function somefunction()
{
  //Do somethisg.
}

?

@JsonProperty annotation on field as well as getter/setter

My observations based on a few tests has been that whichever name differs from the property name is one which takes effect:

For eg. consider a slight modification of your case:

@JsonProperty("fileName")
private String fileName;

@JsonProperty("fileName")
public String getFileName()
{
    return fileName;
}

@JsonProperty("fileName1")
public void setFileName(String fileName)
{
    this.fileName = fileName;
}

Both fileName field, and method getFileName, have the correct property name of fileName and setFileName has a different one fileName1, in this case Jackson will look for a fileName1 attribute in json at the point of deserialization and will create a attribute called fileName1 at the point of serialization.

Now, coming to your case, where all the three @JsonProperty differ from the default propertyname of fileName, it would just pick one of them as the attribute(FILENAME), and had any on of the three differed, it would have thrown an exception:

java.lang.IllegalStateException: Conflicting property name definitions

What is the meaning of the word logits in TensorFlow?

(FOMOsapiens).

If you check math Logit function, it converts real space from [0,1] interval to infinity [-inf, inf].

Sigmoid and softmax will do exactly the opposite thing. They will convert the [-inf, inf] real space to [0, 1] real space.

This is why, in machine learning we may use logit before sigmoid and softmax function (since they match).

And this is why "we may call" anything in machine learning that goes in front of sigmoid or softmax function the logit.

Here is J. Hinton video using this term.

SQL QUERY replace NULL value in a row with a value from the previous known value

First of all, do you really need to store the values? You may just use the view that does the job:

SELECT  t."date",
        x."number" AS "number"
FROM    @Table t
JOIN    @Table x
    ON  x."date" = (SELECT  TOP 1 z."date"
                    FROM    @Table z
                    WHERE   z."date" <= t."date"
                        AND z."number" IS NOT NULL
                    ORDER BY z."date" DESC)

If you really do have the ID ("date") column and it is a primary key (clustered), then this query should be pretty fast. But check the query plan: it might be better to have a cover index including the Val column as well.

Also if you do not like procedures when you can avoid them, you can also use similar query for UPDATE:

UPDATE  t
SET     t."number" = x."number"
FROM    @Table t
JOIN    @Table x
    ON  x."date" = (SELECT  TOP 1 z."date"
                    FROM    @Table z
                    WHERE   z."date" < t."date" --//@note: < and not <= here, as = not required
                        AND z."number" IS NOT NULL
                    ORDER BY z."date" DESC)
WHERE   t."number" IS NULL

NOTE: the code must works on "SQL Server".

Jquery get form field value

var textValue = $("input[type=text]").val()

this will get all values of all text boxes. You can use methods like children, firstchild, etc to hone in. Like by form $('form[name=form1] input[type=text]') Easier to use IDs for targeting elements but if it's purely dynamic you can get all input values then loop through then with JS.

How to cherry-pick multiple commits

Here's a script that will allow you to cherry-pick multiple commits in a row simply by telling the script which source and target branches for the cherry picks and the number of commits:

https://gist.github.com/nickboldt/99ac1dc4eb4c9ff003a1effef2eb2d81

To cherry-pick from your branch to master (uses the current branch as source):

./gcpl.sh -m

To cherry-pick the latest 5 commits from your 6.19.x branch to master:

./gcpl.sh -c 5 -s 6.19.x -t master

Multiple conditions in WHILE loop

Your condition is wrong. myChar != 'n' || myChar != 'N' will always be true.

Use myChar != 'n' && myChar != 'N' instead

Get the client's IP address in socket.io

Here's how to get your client's ip address (v 3.1.0):


// Current Client
const ip = socket.handshake.headers["x-forwarded-for"].split(",")[1].toString().substring(1, this.length);
// Server 
const ip2 = socket.handshake.headers["x-forwarded-for"].split(",")[0].toString();

And just to check if it works go to geoplugin.net/json.gsp?ip= just make sure to switch the ip in the link. After you have done that it should give you the accurate location of the client which means that it worked.

How do I force git to checkout the master branch and remove carriage returns after I've normalized files using the "text" attribute?

As others have pointed out one could just delete all the files in the repo and then check them out. I prefer this method and it can be done with the code below

git ls-files -z | xargs -0 rm
git checkout -- .

or one line

git ls-files -z | xargs -0 rm ; git checkout -- .

I use it all the time and haven't found any down sides yet!

For some further explanation, the -z appends a null character onto the end of each entry output by ls-files, and the -0 tells xargs to delimit the output it was receiving by those null characters.

Git checkout - switching back to HEAD

You can stash (save the changes in temporary box) then, back to master branch HEAD.

$ git add .
$ git stash
$ git checkout master

Jump Over Commits Back and Forth:

  • Go to a specific commit-sha.

      $ git checkout <commit-sha>
    
  • If you have uncommitted changes here then, you can checkout to a new branch | Add | Commit | Push the current branch to the remote.

      # checkout a new branch, add, commit, push
      $ git checkout -b <branch-name>
      $ git add .
      $ git commit -m 'Commit message'
      $ git push origin HEAD          # push the current branch to remote 
    
      $ git checkout master           # back to master branch now
    
  • If you have changes in the specific commit and don't want to keep the changes, you can do stash or reset then checkout to master (or, any other branch).

      # stash
      $ git add -A
      $ git stash
      $ git checkout master
    
      # reset
      $ git reset --hard HEAD
      $ git checkout master
    
  • After checking out a specific commit if you have no uncommitted change(s) then, just back to master or other branch.

      $ git status          # see the changes
      $ git checkout master
    
      # or, shortcut
      $ git checkout -      # back to the previous state
    

Java Package Does Not Exist Error

I had the exact same problem when manually compiling through the command line, my solution was I didn't include the -sourcepath directory so that way all the subdirectory java files would be compiled too!

Converting JSON to XLS/CSV in Java

A JSON document basically consists of lists and dictionaries. There is no obvious way to map such a datastructure on a two-dimensional table.

Check image width and height before upload with Javascript

function uploadfile(ctrl) {
    var validate = validateimg(ctrl);

    if (validate) {
        if (window.FormData !== undefined) {
            ShowLoading();
            var fileUpload = $(ctrl).get(0);
            var files = fileUpload.files;


            var fileData = new FormData();


            for (var i = 0; i < files.length; i++) {
                fileData.append(files[i].name, files[i]);
            }


            fileData.append('username', 'Wishes');

            $.ajax({
                url: 'UploadWishesFiles',
                type: "POST",
                contentType: false,
                processData: false,
                data: fileData,
                success: function(result) {
                    var id = $(ctrl).attr('id');
                    $('#' + id.replace('txt', 'hdn')).val(result);

                    $('#imgPictureEn').attr('src', '../Data/Wishes/' + result).show();

                    HideLoading();
                },
                error: function(err) {
                    alert(err.statusText);
                    HideLoading();
                }
            });
        } else {
            alert("FormData is not supported.");
        }

    }

Iterator Loop vs index loop

Iterators are first choice over operator[]. C++11 provides std::begin(), std::end() functions.

As your code uses just std::vector, I can't say there is much difference in both codes, however, operator [] may not operate as you intend to. For example if you use map, operator[] will insert an element if not found.

Also, by using iterator your code becomes more portable between containers. You can switch containers from std::vector to std::list or other container freely without changing much if you use iterator such rule doesn't apply to operator[].

Error during installing HAXM, VT-X not working

If you are still having issues, try running these steps from VMware to disable credential guard. Worked for me, finally. Steps and link are posted below, not taking credit for them.

Original content from https://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2146361

To disable Device Guard or Credential Guard on Itanium based computers:

  1. Disable the group policy setting that was used to enable Credential Guard.

    On the host operating system, click Start > Run, type gpedit.msc, and click Ok. The Local group Policy Editor opens.

    Go to Local Computer Policy > Computer Configuration > Administrative Templates > System > Device Guard > Turn on Virtualization Based Security.

    Select Disabled.

  2. Go to Control Panel > Programs and Features > Turn Windows features on or off to turn off Hyper-V. [ remove a program on Windows 8 or earlier]

  3. Select Do not restart.

  4. Delete the related EFI variables by launching a command prompt on the host machine using an Administrator account and run these commands:

    enter code here

    mountvol X: /s

    copy %WINDIR%\System32\SecConfig.efi X:\EFI\Microsoft\Boot\SecConfig.efi /Y

    bcdedit /create {0cb3b571-2f2e-4343-a879-d86a476d7215} /d "DebugTool" /application osloader

    bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} path "\EFI\Microsoft\Boot\SecConfig.efi"

    bcdedit /set {bootmgr} bootsequence {0cb3b571-2f2e-4343-a879-d86a476d7215}

    bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} loadoptions DISABLE-LSA-ISO,DISABLE-VBS

    bcdedit /set {0cb3b571-2f2e-4343-a879-d86a476d7215} device partition=X:

    mountvol X: /d

Note: Ensure X is an unused drive, else change to another drive.

  1. Restart the host.

  2. Accept the prompt on the boot screen to disable Device Guard or Credential Guard.

You should be able to install and start HAXM now

document.createElement("script") synchronously

function include(file){
return new Promise(function(resolve, reject){
        var script = document.createElement('script');
        script.src = file;
        script.type ='text/javascript';
        script.defer = true;
        document.getElementsByTagName('head').item(0).appendChild(script);

        script.onload = function(){
        resolve()
        }
        script.onerror = function(){
          reject()
        }
      })

 /*I HAVE MODIFIED THIS TO  BE PROMISE-BASED 
   HOW TO USE THIS FUNCTION 

  include('js/somefile.js').then(function(){
  console.log('loaded');
  },function(){
  console.log('not loaded');
  })
  */
}

How do I configure Notepad++ to use spaces instead of tabs?

I have NotePad++ v6.8.3, and it was in Settings ? Preferences ? Tab Settings ? [Default] ? Replace by space:

NotePad++ Preferences

NotePad++ Tab Settings

What is the default encoding of the JVM?

To get default java settings just use :

java -XshowSettings 

SQL - How to select a row having a column with max value

SQL> create table t (mydate,value)
  2  as
  3  select to_date('18/5/2010, 1 pm','dd/mm/yyyy, hh am'), 40 from dual union all
  4  select to_date('18/5/2010, 2 pm','dd/mm/yyyy, hh am'), 20 from dual union all
  5  select to_date('18/5/2010, 3 pm','dd/mm/yyyy, hh am'), 60 from dual union all
  6  select to_date('18/5/2010, 4 pm','dd/mm/yyyy, hh am'), 30 from dual union all
  7  select to_date('18/5/2010, 5 pm','dd/mm/yyyy, hh am'), 60 from dual union all
  8  select to_date('18/5/2010, 6 pm','dd/mm/yyyy, hh am'), 25 from dual
  9  /

Table created.

SQL> select min(mydate) keep (dense_rank last order by value) mydate
  2       , max(value) value
  3    from t
  4  /

MYDATE                   VALUE
------------------- ----------
18-05-2010 15:00:00         60

1 row selected.

Regards, Rob.

npm ERR! network getaddrinfo ENOTFOUND

Step 1: Set the proxy npm set proxy http://username:password@companyProxy:8080

npm set https-proxy http://username:password@companyProxy:8080

npm config set strict-ssl false -g

NOTES: No special characters in password except @ allowed.

CSS :not(:last-child):after selector

Your example as written works perfectly in Chrome 11 for me. Perhaps your browser just doesn't support the :not() selector?

You may need to use JavaScript or similar to accomplish this cross-browser. jQuery implements :not() in its selector API.

Copy entire directory contents to another directory?

The following is an example of using JDK7.

public class CopyFileVisitor extends SimpleFileVisitor<Path> {
    private final Path targetPath;
    private Path sourcePath = null;
    public CopyFileVisitor(Path targetPath) {
        this.targetPath = targetPath;
    }

    @Override
    public FileVisitResult preVisitDirectory(final Path dir,
    final BasicFileAttributes attrs) throws IOException {
        if (sourcePath == null) {
            sourcePath = dir;
        } else {
        Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(final Path file,
    final BasicFileAttributes attrs) throws IOException {
    Files.copy(file,
        targetPath.resolve(sourcePath.relativize(file)));
    return FileVisitResult.CONTINUE;
    }
}

To use the visitor do the following

Files.walkFileTree(sourcePath, new CopyFileVisitor(targetPath));

If you'd rather just inline everything (not too efficient if you use it often, but good for quickies)

    final Path targetPath = // target
    final Path sourcePath = // source
    Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(final Path dir,
                final BasicFileAttributes attrs) throws IOException {
            Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(final Path file,
                final BasicFileAttributes attrs) throws IOException {
            Files.copy(file,
                    targetPath.resolve(sourcePath.relativize(file)));
            return FileVisitResult.CONTINUE;
        }
    });

Get MD5 hash of big files in Python

I don't like loops. Based on @Nathan Feger:

md5 = hashlib.md5()
with open(filename, 'rb') as f:
    functools.reduce(lambda _, c: md5.update(c), iter(lambda: f.read(md5.block_size * 128), b''), None)
md5.hexdigest()

Wait till a Function with animations is finished until running another Function

Here is a solution for n-calls (recursive function). https://jsfiddle.net/mathew11/5f3mu0f4/7/

function myFunction(array){
var r = $.Deferred();

if(array.length == 0){
    r.resolve();
    return r;
}

var element = array.shift();
// async task 
timer = setTimeout(function(){
    $("a").text($("a").text()+ " " + element);
    var resolving = function(){
        r.resolve();
    }

    myFunction(array).done(resolving);

 }, 500);

return r;
}

//Starting the function
var myArray = ["Hi", "that's", "just", "a", "test"];
var alerting = function (){window.alert("finished!")};
myFunction(myArray).done(alerting);

Combine Multiple child rows into one row MYSQL

Joe Edel's answer to himself is actually the right approach to resolve the pivot problem.

Basically the idea is to list out the columns in the base table firstly, and then any number of options.value from the joint option table. Just left join the same option table multiple times in order to get all the options.

What needs to be done by the programming language is to build this query dynamically according to a list of options needs to be queried.

What could cause an error related to npm not being able to find a file? No contents in my node_modules subfolder. Why is that?

If it happens, then it means you have to upgrade your node.js. Simply uninstall your current node from your pc or mac and download the latest version from https://nodejs.org/en/

How to use su command over adb shell?

By default CM10 only allows root access from Apps not ADB. Go to Settings -> Developer options -> Root access, and change option to "Apps and ADB".

Select second last element with css

Note: Posted this answer because OP later stated in comments that they need to select the last two elements, not just the second to last one.


The :nth-child CSS3 selector is in fact more capable than you ever imagined!

For example, this will select the last 2 elements of #container:

#container :nth-last-child(-n+2) {}

But this is just the beginning of a beautiful friendship.

_x000D_
_x000D_
#container :nth-last-child(-n+2) {
  background-color: cyan;
}
_x000D_
<div id="container">
 <div>a</div>
 <div>b</div>
 <div>SELECT THIS</div>
 <div>SELECT THIS</div>
</div>
_x000D_
_x000D_
_x000D_

List tables in a PostgreSQL schema

You can select the tables from information_schema

SELECT * FROM information_schema.tables 
WHERE table_schema = 'public'

Consider defining a bean of type 'service' in your configuration [Spring boot]

remove annotation configuration like service, repository, components

@Component
@Service

Reading a JSP variable from JavaScript

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> 

    <title>JSP Page</title>
    <script>
       $(document).ready(function(){
          <% String name = "phuongmychi.github.io" ;%> // jsp vari
         var name = "<%=name %>" // call var to js
         $("#id").html(name); //output to html

       });
    </script>
</head>
<body>
    <h1 id='id'>!</h1>
</body>

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

On IntelliJ go to Preference -> Build, Execution, Deployment -> Build Tools -> Maven. Turn on the checkbox for "Always update snapshots" apply and save changes then do mvn clean install

How to select into a variable in PL/SQL when the result might be null?

Using an Cursor FOR LOOP Statement is my favourite way to do this.

It is safer than using an explicit cursor, because you don't need to remember to close it, so you can't "leak" cursors.

You don't need "into" variables, you don't need to "FETCH", you don't need to catch and handle "NO DATA FOUND" exceptions.

Try it, you'll never go back.

v_column my_table.column%TYPE;

v_column := null;

FOR rMyTable IN (SELECT COLUMN FROM MY_TABLE WHERE ....) LOOP
  v_column := rMyTable.COLUMN;
  EXIT;  -- Exit the loop if you only want the first result.
END LOOP;

Unsupported operand type(s) for +: 'int' and 'str'

try,

str_list = " ".join([str(ele) for ele in numlist])

this statement will give you each element of your list in string format

print("The list now looks like [{0}]".format(str_list))

and,

change print(numlist.pop(2)+" has been removed") to

print("{0} has been removed".format(numlist.pop(2)))

as well.

Javascript to open popup window and disable parent window

This is how I finally did it! You can put a layer (full sized) over your body with high z-index and, of course hidden. You will make it visible when the window is open, make it focused on click over parent window (the layer), and finally will disappear it when the opened window is closed or submitted or whatever.

      .layer
  {
        position: fixed;
        opacity: 0.7;
        left: 0px;
        top: 0px;
        width: 100%;
        height: 100%;
        z-index: 999999;
        background-color: #BEBEBE;
        display: none;
        cursor: not-allowed;
  }

and layer in the body:

                <div class="layout" id="layout"></div>

function that opens the popup window:

    var new_window;
    function winOpen(){
        $(".layer").show();
        new_window=window.open(srcurl,'','height=750,width=700,left=300,top=200');
    }

keeping new window focused:

         $(document).ready(function(){
             $(".layout").click(function(e) {
                new_window.focus();
            }
        });

and in the opened window:

    function submit(){
        var doc = window.opener.document,
        doc.getElementById("layer").style.display="none";
         window.close();
    }   

   window.onbeforeunload = function(){
        var doc = window.opener.document;
        doc.getElementById("layout").style.display="none";
   }

I hope it would help :-)

How to remove an item from an array in AngularJS scope?

You'll have to find the index of the person in your persons array, then use the array's splice method:

$scope.persons.splice( $scope.persons.indexOf(person), 1 );

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

Getting vertical gridlines to appear in line plot in matplotlib

maybe this can solve the problem: matplotlib, define size of a grid on a plot

ax.grid(True, which='both')

The truth is that the grid is working, but there's only one v-grid in 00:00 and no grid in others. I meet the same problem that there's only one grid in Nov 1 among many days.

How do you clear the console screen in C?

Since you mention cls, it sounds like you are referring to windows. If so, then this KB item has the code that will do it. I just tried it, and it worked when I called it with the following code:

cls( GetStdHandle( STD_OUTPUT_HANDLE ));

Sending data through POST request from a node.js server to a node.js server

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for executing a POST request:

var requestify = require('requestify');

requestify.post('http://example.com', {
    hello: 'world'
})
.then(function(response) {
    // Get the response body (JSON parsed or jQuery object for XMLs)
    response.getBody();
});

Using a BOOL property

There's no benefit to using properties with primitive types. @property is used with heap allocated NSObjects like NSString*, NSNumber*, UIButton*, and etc, because memory managed accessors are created for free. When you create a BOOL, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking is simply the popular way of expressing the state of a boolean value.

In another OO language you would make a variable private bool working; and two accessors: SetWorking for the setter and IsWorking for the accessor.

How to specify font attributes for all elements on an html web page?

* {
 font-size: 100%;
 font-family: Arial;
}

The asterisk implies all elements.

make arrayList.toArray() return more specific types

A shorter version of converting List to Array of specific type (for example Long):

Long[] myArray = myList.toArray(Long[]::new);

Illegal character in path at index 16

I had a similar problem for xml. Just passing the error and solution (edited Jonathon version).

Code:

HttpGet xmlGet = new HttpGet( xmlContent );

Xml format:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
    <code>CA</code>
    <name>Cath</name>
    <salary>300</salary>
</employee>

Error:

java.lang.IllegalArgumentException: Illegal character in path at index 0: <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<contents>
    <portalarea>CA</portalarea>
    <portalsubarea>Cath</portalsubarea>
    <direction>Navigator</direction>
</contents>
    at java.net.URI.create(URI.java:859)
    at org.apache.http.client.methods.HttpGet.<init>(HttpGet.java:69)
    at de.vogella.jersey.first.Hello.validate(Hello.java:56)

Not Exactly perfect Solution: ( error vanished for that instance )

String theXml = URLEncoder.encode( xmlContent, "UTF-8" );
HttpGet xmlGet = new HttpGet( theXml );

Any idea What i should be doing ? It just cleared passed but had problem while doing this

HttpResponse response = httpclient.execute( xmlGet );

Debug/run standard java in Visual Studio Code IDE and OS X?

There is a much easier way to run Java, no configuration needed:

  1. Install the Code Runner Extension
  2. Open your Java code file in Text Editor, then use shortcut Ctrl+Alt+N, or press F1 and then select/type Run Code, or right click the Text Editor and then click Run Code in context menu, the code will be compiled and run, and the output will be shown in the Output Window.

runJave

How to convert Map keys to array?

Not exactly best answer to question but this trick new Array(...someMap) saved me couple of times when I need both key and value to generate needed array. For example when there is need to create react components from Map object based on both key and value values.

  let map = new Map();
  map.set("1", 1);
  map.set("2", 2);
  console.log(new Array(...map).map(pairs => pairs[0])); -> ["1", "2"]

How to Convert JSON object to Custom C# object?

public static class Utilities
{
    public static T Deserialize<T>(string jsonString)
    {
        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
        {    
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            return (T)serializer.ReadObject(ms);
        }
    }
}

More information go to following link http://ishareidea.blogspot.in/2012/05/json-conversion.html

About DataContractJsonSerializer Class you can read here.

Is it possible to get element from HashMap by its position?

HashMap has no concept of position so there is no way to get an object by position. Objects in Maps are set and get by keys.

Show Error on the tip of the Edit Text Android

if(TextUtils.isEmpty(firstName.getText().toString()){
      firstName.setError("TEXT ERROR HERE");
}

Or you can also use TextInputLayout which has some useful method and some user friendly animation

Facebook share button and custom text

To give custom parameters to facebook share its better to give only the link and facebook gets its Title + Description + Picture automatically from the page that you are sharing. In order to "help" facebook API find those things you can put the following things in the header of the page that you are sharing:

<meta property="og:title" content="title" />
<meta property="og:description" content="description" />
<meta property="og:image" content="thumbnail_image" />

Check here

If the page is not under your control use what AllisonC has shared above.

For popup modalview type behavior:

Use your own button/link/text and then you can use a modal view type of popup this way:

<script type= 'text/javascript'>
$('#twitterbtn-link,#facebookbtn-link').click(function(event) {
var width  = 575,
    height = 400,
    left   = ($(window).width()  - width)  / 2,
    top    = ($(window).height() - height) / 2,
    url    = this.href,
    opts   = 'status=1' +
             ',width='  + width  +
             ',height=' + height +
             ',top='    + top    +
             ',left='   + left;

window.open(url, 'twitter', opts);

return false;
});
</script>

where twitterbtn-link and facebookbtn-link are both ids of anchors.

Alter MySQL table to add comments on columns

As per the documentation you can add comments only at the time of creating table. So it is must to have table definition. One way to automate it using the script to read the definition and update your comments.

Reference:

http://cornempire.net/2010/04/15/add-comments-to-column-mysql/

http://bugs.mysql.com/bug.php?id=64439

I want to declare an empty array in java and then I want do update it but the code is not working

You need to give the array a size:

public static void main(String args[])
{
    int array[] = new int[4];
    int number = 5, i = 0,j = 0;
    while (i<4){
        array[i]=number;
        i=i+1;
    }
    while (j<4){
        System.out.println(array[j]);
        j++;
    }
}

How to uncommit my last commit in Git

Be careful, reset --hard will remove your local (uncommitted) modifications, too.

git reset --hard HEAD^

note: if you're on windows you'll need to quote the HEAD^ so

git reset --hard "HEAD^"

If you want to revert the commit WITHOUT throwing away work, use the --soft flag instead of --hard

Call to getLayoutInflater() in places not in activity

Using context object you can get LayoutInflater from following code

LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

Bootstrap 4 img-circle class not working

In Bootstrap 4 it was renamed to .rounded-circle

Usage :

<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>

See migration docs from bootstrap.

android:drawableLeft margin and/or padding

You can use a padding for the button and you can play with drawablePadding

 <Button
    style="@style/botonesMenu"
    android:padding="15dp"
    android:drawablePadding="-15dp"
    android:text="@string/actualizarBD"
    android:textAlignment="gravity"
    android:gravity="center"
    android:layout_row="1"
    android:layout_column="0"
    android:drawableTop="@drawable/actualizar"
    android:id="@+id/btnActualizar"
    android:onClick="actualizarBD" />

you can use a specific padding depends where put your drawable, with android:paddingLeft="10dp" or android:paddingBottom="10dp" or android:paddingRight="10dp" or android:paddingTop="10dp"

Does MySQL foreign_key_checks affect the entire database?

In case of using Mysql query browser, SET FOREIGN_KEY_CHECKS=0; does not have any impact in version 1.1.20. However, it works fine on Mysql query browser 1.2.17

JS search in object values

You can use this javascript lib, DefiantJS (http://defiantjs.com), with which you can filter matches using XPath on JSON structures. To put it in JS code:

    var data = [
       { "foo": "bar",   "bar": "sit" },
       { "foo": "lorem", "bar": "ipsum" },
       { "foo": "dolor", "bar": "amet" }
    ],
    res1 = JSON.search( data, '//*[contains(name(), 'r')]/..' ),
    res2 = JSON.search( data, '//*[contains(., 'lo')]' );

/*
res1 = [
    { "foo": "bar",   "bar": "sit" },
    { "foo": "lorem", "bar": "ipsum" },
    { "foo": "dolor", "bar": "amet" }
]
*/

/*
res2 = [
    { "foo": "lorem", "bar": "ipsum" },
    { "foo": "dolor", "bar": "amet" }
]
*/

Here is a working fiddle;
http://jsfiddle.net/hbi99/2kHDZ/

DefiantJS extends the global object with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:

http://www.defiantjs.com/#xpath_evaluator

Creating columns in listView and add items

You need to set property for the control:

listView1.View = View.Details;

React - clearing an input value after form submit

This is the value that i want to clear and create it in state 1st STEP

state={
TemplateCode:"",
}

craete submitHandler function for Button or what you want 3rd STEP

submitHandler=()=>{
this.clear();//this is function i made
}

This is clear function Final STEP

clear = () =>{
  this.setState({
    TemplateCode: ""//simply you can clear Templatecode
  });
}

when click button Templatecode is clear 2nd STEP

<div class="col-md-12" align="right">
  <button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save 
  </button>
</div>

Remove all occurrences of a value from a list?

Remove all occurrences of a value from a Python list

lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list():
    for list in lists:
      if(list!=7):
         print(list)
remove_values_from_list()

Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

Alternatively,

lists = [6.9,7,8.9,3,5,4.9,1,2.9,7,9,12.9,10.9,11,7]
def remove_values_from_list(remove):
    for list in lists:
      if(list!=remove):
        print(list)
remove_values_from_list(7)

Result: 6.9 8.9 3 5 4.9 1 2.9 9 12.9 10.9 11

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

If this is your own collection class rather than a built in one, you need to override its toString method. Eclipse calls that function for any objects for which it does not have a hard-wired formatting.

Get the latest date from grouped MySQL data

try this:

SELECT model, date
FROM doc
WHERE date = (SELECT MAX(date)
FROM doc GROUP BY model LIMIT 0, 1)
GROUP BY model

What is the difference between `let` and `var` in swift?

var is the only way to create a variables in swift. var doesn't mean dynamic variable as in the case of interpreted languages like javascript. For example,

var name = "Bob"

In this case, the type of variable name is inferred that name is of type String, we can also create variables by explicitly defining type, for example

var age:Int = 20

Now if you assign a string to age, then the compiler gives the error.

let is used to declare constants. For example

let city = "Kathmandu"

Or we can also do,

let city:String = "Kathmandu"

If you try to change the value of city, it gives error at compile time.

Cannot find mysql.sock

The original questions seems to come from confusion about a) where is the file, and b) where is it being looked for (and why can't we find it there when we do a locate or grep). I think Alnitak's point was that you want to find where it was linked to - but grep will not show you a link, right? The file doesn't live there, since it's a link it is just a pointer. You still need to know where to put the link.

my sock file is definitely in /tmp and the ERROR I am getting is looking for it in /var/lib/ (not just /var) I have linked to /var and /var/lib now, and I still am getting the error "Cannot connect to local MySQL server through socket 'var/lib/mysql.sock' (2)".

Note the (2) after the error.... I found on another thread that this means the socket might be indeed attempted to be used, but something is wrong with the socket itself - so to shut down the machine - completely - so that the socket closes. Then a restart should fix it. I tried this, but it didn't work for me (now I question if I restarted too quickly? really?) Maybe it will be a solution for someone else.

Counting lines, words, and characters within a text file using Python

Try this:

fname = "feed.txt"

num_lines = 0
num_words = 0
num_chars = 0

with open(fname, 'r') as f:
    for line in f:
        words = line.split()

        num_lines += 1
        num_words += len(words)
        num_chars += len(line)

Back to your code:

fname = "feed.txt"
fname = open('feed.txt', 'r')

what's the point of this? fname is a string first and then a file object. You don't really use the string defined in the first line and you should use one variable for one thing only: either a string or a file object.

for line in feed:
    lines = line.split('\n')

line is one line from the file. It does not make sense to split('\n') it.

What is the difference between range and xrange functions in Python 2.X?

It is for optimization reasons.

range() will create a list of values from start to end (0 .. 20 in your example). This will become an expensive operation on very large ranges.

xrange() on the other hand is much more optimised. it will only compute the next value when needed (via an xrange sequence object) and does not create a list of all values like range() does.

Can I set subject/content of email using mailto:?

Yes:

Use this to experiment with mailto form elements and link encoding.

You can enter subject, body (i.e. content), etc. into the form, hit the button and see the mailto html link that you can paste into your page.

You can even specify elements that are rarely known and used: cc, bcc, from emails.

Fatal error: Call to undefined function socket_create()

For a typical XAMPP install on windows you probably have the php_sockets.dll in your C:\xampp\php\ext directory. All you got to do is go to php.ini in the C:\xampp\php directory and change the ;extension=php_sockets.dll to extension=php_sockets.dll.

Parsing command-line arguments in C

I think that GNU GetOpt is not too immediate to use.

Qt and Boost could be a solution, but you need to download and compile a lot of code.

So I implemented a parser by myself that produces a std::map<std::string, std::string> of parameters.

For example, calling:

 ./myProgram -v -p 1234

map will be:

 ["-v"][""]
 ["-p"]["1234"]

Usage is:

int main(int argc, char *argv[]) {
    MainOptions mo(argc, argv);
    MainOptions::Option* opt = mo.getParamFromKey("-p");
    const string type = opt ? (*opt).second : "";
    cout << type << endl; /* Prints 1234 */
    /* Your check code */
}

MainOptions.h

#ifndef MAINOPTIONS_H_
#define MAINOPTIONS_H_

#include <map>
#include <string>

class MainOptions {
public:
    typedef std::pair<std::string, std::string> Option;
    MainOptions(int argc, char *argv[]);
    virtual ~MainOptions();
    std::string getAppName() const;
    bool hasKey(const std::string&) const;
    Option* getParamFromKey(const std::string&) const;
    void printOptions() const;
private:
    typedef std::map<std::string, std::string> Options;
    void parse();
    const char* const *begin() const;
    const char* const *end() const;
    const char* const *last() const;
    Options options_;
    int argc_;
    char** argv_;
    std::string appName_;
};

MainOptions.cpp

#include "MainOptions.h"

#include <iostream>

using namespace std;

MainOptions::MainOptions(int argc, char* argv[]) :
        argc_(argc),
        argv_(argv) {
    appName_ = argv_[0];
    this->parse();
}

MainOptions::~MainOptions() {
}

std::string MainOptions::getAppName() const {
    return appName_;
}

void MainOptions::parse() {
    typedef pair<string, string> Option;
    Option* option = new pair<string, string>();
    for (const char* const * i = this->begin() + 1; i != this->end(); i++) {
        const string p = *i;
        if (option->first == "" && p[0] == '-') {
            option->first = p;
            if (i == this->last()) {
                options_.insert(Option(option->first, option->second));
            }
            continue;
        } else if (option->first != "" && p[0] == '-') {
            option->second = "null"; /* or leave empty? */
            options_.insert(Option(option->first, option->second));
            option->first = p;
            option->second = "";
            if (i == this->last()) {
                options_.insert(Option(option->first, option->second));
            }
            continue;
        } else if (option->first != "") {
            option->second = p;
            options_.insert(Option(option->first, option->second));
            option->first = "";
            option->second = "";
            continue;
        }
    }
}

void MainOptions::printOptions() const {
    std::map<std::string, std::string>::const_iterator m = options_.begin();
    int i = 0;
    if (options_.empty()) {
        cout << "No parameters\n";
    }
    for (; m != options_.end(); m++, ++i) {
        cout << "Parameter [" << i << "] [" << (*m).first << " " << (*m).second
                << "]\n";
    }
}

const char* const *MainOptions::begin() const {
    return argv_;
}

const char* const *MainOptions::end() const {
    return argv_ + argc_;
}

const char* const *MainOptions::last() const {
    return argv_ + argc_ - 1;
}

bool MainOptions::hasKey(const std::string& key) const {
    return options_.find(key) != options_.end();
}

MainOptions::Option* MainOptions::getParamFromKey(
        const std::string& key) const {
    const Options::const_iterator i = options_.find(key);
    MainOptions::Option* o = 0;
    if (i != options_.end()) {
        o = new MainOptions::Option((*i).first, (*i).second);
    }
    return o;
}

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

Getting value from table cell in JavaScript...not jQuery

<script>
    $('#tinh').click(function () {
        var sumVal = 0;
        var table = document.getElementById("table1");

        for (var i = 1; i < (table.rows.length-1); i++) {
            sumVal = sumVal + parseInt(table.rows[i].cells[3].innerHTML);
        }


        document.getElementById("valueTotal").innerHTML = sumVal;
    });
</script>

What is the origin of foo and bar?

tl;dr

  • "Foo" and "bar" as metasyntactic variables were popularised by MIT and DEC, the first references are in work on LISP and PDP-1 and Project MAC from 1964 onwards.

  • Many of these people were in MIT's Tech Model Railroad Club, where we find the first documented use of "foo" in tech circles in 1959 (and a variant in 1958).

  • Both "foo" and "bar" (and even "baz") were well known in popular culture, especially from Smokey Stover and Pogo comics, which will have been read by many TMRC members.

  • Also, it seems likely the military FUBAR contributed to their popularity.


The use of lone "foo" as a nonsense word is pretty well documented in popular culture in the early 20th century, as is the military FUBAR. (Some background reading: FOLDOC FOLDOC Jargon File Jargon File Wikipedia RFC3092)


OK, so let's find some references.

STOP PRESS! After posting this answer, I discovered this perfect article about "foo" in the Friday 14th January 1938 edition of The Tech ("MIT's oldest and largest newspaper & the first newspaper published on the web"), Volume LVII. No. 57, Price Three Cents:

On Foo-ism

The Lounger thinks that this business of Foo-ism has been carried too far by its misguided proponents, and does hereby and forthwith take his stand against its abuse. It may be that there's no foo like an old foo, and we're it, but anyway, a foo and his money are some party. (Voice from the bleachers- "Don't be foo-lish!")

As an expletive, of course, "foo!" has a definite and probably irreplaceable position in our language, although we fear that the excessive use to which it is currently subjected may well result in its falling into an early (and, alas, a dark) oblivion. We say alas because proper use of the word may result in such happy incidents as the following.

It was an 8.50 Thermodynamics lecture by Professor Slater in Room 6-120. The professor, having covered the front side of the blackboard, set the handle that operates the lift mechanism, turning meanwhile to the class to continue his discussion. The front board slowly, majestically, lifted itself, revealing the board behind it, and on that board, writ large, the symbols that spelled "FOO"!

The Tech newspaper, a year earlier, the Letter to the Editor, September 1937:

By the time the train has reached the station the neophytes are so filled with the stories of the glory of Phi Omicron Omicron, usually referred to as Foo, that they are easy prey.

...

It is not that I mind having lost my first four sons to the Grand and Universal Brotherhood of Phi Omicron Omicron, but I do wish that my fifth son, my baby, should at least be warned in advance.

Hopefully yours,

Indignant Mother of Five.

And The Tech in December 1938:

General trend of thought might be best interpreted from the remarks made at the end of the ballots. One vote said, '"I don't think what I do is any of Pulver's business," while another merely added a curt "Foo."


The first documented "foo" in tech circles is probably 1959's Dictionary of the TMRC Language:

FOO: the sacred syllable (FOO MANI PADME HUM); to be spoken only when under inspiration to commune with the Deity. Our first obligation is to keep the Foo Counters turning.

These are explained at FOLDOC. The dictionary's compiler Pete Samson said in 2005:

Use of this word at TMRC antedates my coming there. A foo counter could simply have randomly flashing lights, or could be a real counter with an obscure input.

And from 1996's Jargon File 4.0.0:

Earlier versions of this lexicon derived 'baz' as a Stanford corruption of bar. However, Pete Samson (compiler of the TMRC lexicon) reports it was already current when he joined TMRC in 1958. He says "It came from "Pogo". Albert the Alligator, when vexed or outraged, would shout 'Bazz Fazz!' or 'Rowrbazzle!' The club layout was said to model the (mythical) New England counties of Rowrfolk and Bassex (Rowrbazzle mingled with (Norfolk/Suffolk/Middlesex/Essex)."

A year before the TMRC dictionary, 1958's MIT Voo Doo Gazette ("Humor suplement of the MIT Deans' office") (PDF) mentions Foocom, in "The Laws of Murphy and Finagle" by John Banzhaf (an electrical engineering student):

Further research under a joint Foocom and Anarcom grant expanded the law to be all embracing and universally applicable: If anything can go wrong, it will!

Also 1964's MIT Voo Doo (PDF) references the TMRC usage:

Yes! I want to be an instant success and snow customers. Send me a degree in: ...

  • Foo Counters

  • Foo Jung


Let's find "foo", "bar" and "foobar" published in code examples.

So, Jargon File 4.4.7 says of "foobar":

Probably originally propagated through DECsystem manuals by Digital Equipment Corporation (DEC) in 1960s and early 1970s; confirmed sightings there go back to 1972.

The first published reference I can find is from February 1964, but written in June 1963, The Programming Language LISP: its Operation and Applications by Information International, Inc., with many authors, but including Timothy P. Hart and Michael Levin:

Thus, since "FOO" is a name for itself, "COMITRIN" will treat both "FOO" and "(FOO)" in exactly the same way.

Also includes other metasyntactic variables such as: FOO CROCK GLITCH / POOT TOOR / ON YOU / SNAP CRACKLE POP / X Y Z

I expect this is much the same as this next reference of "foo" from MIT's Project MAC in January 1964's AIM-064, or LISP Exercises by Timothy P. Hart and Michael Levin:

car[((FOO . CROCK) . GLITCH)]

It shares many other metasyntactic variables like: CHI / BOSTON NEW YORK / SPINACH BUTTER STEAK / FOO CROCK GLITCH / POOT TOOP / TOOT TOOT / ISTHISATRIVIALEXCERCISE / PLOOP FLOT TOP / SNAP CRACKLE POP / ONE TWO THREE / PLANE SUB THRESHER

For both "foo" and "bar" together, the earliest reference I could find is from MIT's Project MAC in June 1966's AIM-098, or PDP-6 LISP by none other than Peter Samson:

EXPLODE, like PRIN1, inserts slashes, so (EXPLODE (QUOTE FOO/ BAR)) PRIN1's as (F O O // / B A R) or PRINC's as (F O O / B A R).


Some more recallations.

@Walter Mitty recalled on this site in 2008:

I second the jargon file regarding Foo Bar. I can trace it back at least to 1963, and PDP-1 serial number 2, which was on the second floor of Building 26 at MIT. Foo and Foo Bar were used there, and after 1964 at the PDP-6 room at project MAC.

John V. Everett recalls in 1996:

When I joined DEC in 1966, foobar was already being commonly used as a throw-away file name. I believe fubar became foobar because the PDP-6 supported six character names, although I always assumed the term migrated to DEC from MIT. There were many MIT types at DEC in those days, some of whom had worked with the 7090/7094 CTSS. Since the 709x was also a 36 bit machine, foobar may have been used as a common file name there.

Foo and bar were also commonly used as file extensions. Since the text editors of the day operated on an input file and produced an output file, it was common to edit from a .foo file to a .bar file, and back again.

It was also common to use foo to fill a buffer when editing with TECO. The text string to exactly fill one disk block was IFOO$HXA127GA$$. Almost all of the PDP-6/10 programmers I worked with used this same command string.

Daniel P. B. Smith in 1998:

Dick Gruen had a device in his dorm room, the usual assemblage of B-battery, resistors, capacitors, and NE-2 neon tubes, which he called a "foo counter." This would have been circa 1964 or so.

Robert Schuldenfrei in 1996:

The use of FOO and BAR as example variable names goes back at least to 1964 and the IBM 7070. This too may be older, but that is where I first saw it. This was in Assembler. What would be the FORTRAN integer equivalent? IFOO and IBAR?

Paul M. Wexelblat in 1992:

The earliest PDP-1 Assembler used two characters for symbols (18 bit machine) programmers always left a few words as patch space to fix problems. (Jump to patch space, do new code, jump back) That space conventionally was named FU: which stood for Fxxx Up, the place where you fixed Fxxx Ups. When spoken, it was known as FU space. Later Assemblers ( e.g. MIDAS allowed three char tags so FU became FOO, and as ALL PDP-1 programmers will tell you that was FOO space.

Bruce B. Reynolds in 1996:

On the IBM side of FOO(FU)BAR is the use of the BAR side as Base Address Register; in the middle 1970's CICS programmers had to worry out the various xxxBARs...I think one of those was FRACTBAR...

Here's a straight IBM "BAR" from 1955.


Other early references:


I haven't been able to find any references to foo bar as "inverted foo signal" as suggested in RFC3092 and elsewhere.

Here are a some of even earlier F00s but I think they're coincidences/false positives:

How do I use arrays in cURL POST requests

    $ch = curl_init();

    $data = array(
        'client_id' => 'xx',
        'client_secret' => 'xx',
        'redirect_uri' => $x,
        'grant_type' => 'xxx',
        'code' => $xx,
    );

    $data = http_build_query($data);

    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_URL, "https://example.com");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);

    $output = curl_exec($ch);

How to count duplicate value in an array in javascript

var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];

var newArr = [];
testArray.forEach((item) => {
    newArr[item] = testArray.filter((el) => {
            return el === item;
    }).length;
})
console.log(newArr);

Sorting std::map using value

U can consider using boost::bimap that might gave you a feeling that map is sorted by key and by values simultaneously (this is not what really happens, though)

Search and get a line in Python

items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:

you can also get the line if there are other characters before token

items=re.findall("^.*token.*$",s,re.MULTILINE)

The above works like grep token on unix and keyword 'in' or .contains in python and C#

s='''
qwertyuiop
asdfghjkl

zxcvbnm
token qwerty

asdfghjklñ
'''

http://pythex.org/ matches the following 2 lines

....
....
token qwerty

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

df = df.replace({np.nan: None})

Credit goes to this guy here on this Github issue.

JavaScript: IIF like statement

Something like this:

for (/* stuff */)
{
    var x = '<option value="' + col + '" '
        + (col === 'screwdriver' ? 'selected' : '')
        + '>Very roomy</option>';
    // snip...
}

Combine two ActiveRecord::Relation objects

If you want to combine using AND (intersection), use merge:

first_name_relation.merge(last_name_relation)

If you want to combine using OR (union), use or:

first_name_relation.or(last_name_relation)

Only in ActiveRecord 5+; for 4.2 install the where-or backport.

How to configure slf4j-simple

It's either through system property

-Dorg.slf4j.simpleLogger.defaultLogLevel=debug

or simplelogger.properties file on the classpath

see http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html for details

SQL: How to to SUM two values from different tables

select region,sum(number) total
from
(
    select region,number
    from cash_table
    union all
    select region,number
    from cheque_table
) t
group by region

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

For RubyOnRails app add localhost If you use custom Postgresql version

# config/database.yml
default: &default
  host: localhost

What is the difference between active and passive FTP?

I recently run into this question in my work place so I think I should say something more here. I will use image to explain how the FTP works as an additional source for previous answer.

Active mode:

active mode


Passive mode:

enter image description here


In an active mode configuration, the server will attempt to connect to a random client-side port. So chances are, that port wouldn't be one of those predefined ports. As a result, an attempt to connect to it will be blocked by the firewall and no connection will be established.

enter image description here


A passive configuration will not have this problem since the client will be the one initiating the connection. Of course, it's possible for the server side to have a firewall too. However, since the server is expected to receive a greater number of connection requests compared to a client, then it would be but logical for the server admin to adapt to the situation and open up a selection of ports to satisfy passive mode configurations.

So it would be best for you to configure server to support passive mode FTP. However, passive mode would make your system vulnerable to attacks because clients are supposed to connect to random server ports. Thus, to support this mode, not only should your server have to have multiple ports available, your firewall should also allow connections to all those ports to pass through!

To mitigate the risks, a good solution would be to specify a range of ports on your server and then to allow only that range of ports on your firewall.

For more information, please read the official document.

Gradle, Android and the ANDROID_HOME SDK location

Your local.properties file might be missing. If so add a file named 'local.properties' inside /local.properties and provide the sdk location as following.

sdk.dir=C:\Users\\AppData\Local\Android\Sdk

Querying Windows Active Directory server using ldapsearch from command line

You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify

Slide div left/right using jQuery

You can easy get that effect without using jQueryUI, for example:

$(document).ready(function(){
    $('#slide').click(function(){
    var hidden = $('.hidden');
    if (hidden.hasClass('visible')){
        hidden.animate({"left":"-1000px"}, "slow").removeClass('visible');
    } else {
        hidden.animate({"left":"0px"}, "slow").addClass('visible');
    }
    });
});

Try this working Fiddle:

http://jsfiddle.net/ZQTFq/

What is the best JavaScript code to create an img element

Are you allowed to use a framework? jQuery and Prototype make this sort of thing pretty easy. Here's a sample in Prototype:

var elem = new Element('img', { 'class': 'foo', src: 'pic.jpg', alt: 'alternate text' });
$(document).insert(elem);

How to change background Opacity when bootstrap modal is open

It should work with:

.modal:before{
   opacity:0.001 !important;
}

converting drawable resource image into bitmap

First Create Bitmap Image

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);

now set bitmap in Notification Builder Icon....

Notification.Builder.setLargeIcon(bmp);

jQuery checkbox check/uncheck

Use .prop() instead and if we go with your code then compare like this:

Look at the example jsbin:

  $("#news_list tr").click(function () {
    var ele = $(this).find(':checkbox');
    if ($(':checked').length) {
      ele.prop('checked', false);
      $(this).removeClass('admin_checked');
    } else {
      ele.prop('checked', true);
      $(this).addClass('admin_checked');
    }
 });

Changes:

  1. Changed input to :checkbox.
  2. Comparing the length of the checked checkboxes.

What is the best way to update the entity in JPA

It depends on number of entities which are going to be updated, if you have large number of entities using JPA Query Update statement is better as you dont have to load all the entities from database, if you are going to update just one entity then using find and update is fine.

how to make a countdown timer in java

import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

public class Stopwatch {
static int interval;
static Timer timer;

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.print("Input seconds => : ");
    String secs = sc.nextLine();
    int delay = 1000;
    int period = 1000;
    timer = new Timer();
    interval = Integer.parseInt(secs);
    System.out.println(secs);
    timer.scheduleAtFixedRate(new TimerTask() {

        public void run() {
            System.out.println(setInterval());

        }
    }, delay, period);
}

private static final int setInterval() {
    if (interval == 1)
        timer.cancel();
    return --interval;
}
}

Try this.

Quick Way to Implement Dictionary in C

Hashing is the key. I think use lookup table and hashing key for this. You can find many hashing function online.

Java collections maintaining insertion order

The collections don't maintain order of insertion. Some just default to add a new value at the end. Maintaining order of insertion is only useful if you prioritize the objects by it or use it to sort objects in some way.

As for why some collections maintain it by default and others don't, this is mostly caused by the implementation and only sometimes part of the collections definition.

  • Lists maintain insertion order as just adding a new entry at the end or the beginning is the fastest implementation of the add(Object ) method.

  • Sets The HashSet and TreeSet implementations don't maintain insertion order as the objects are sorted for fast lookup and maintaining insertion order would require additional memory. This results in a performance gain since insertion order is almost never interesting for Sets.

  • ArrayDeque a deque can used for simple que and stack so you want to have ''first in first out'' or ''first in last out'' behaviour, both require that the ArrayDeque maintains insertion order. In this case the insertion order is maintained as a central part of the classes contract.

Android webview slow

Adding this android:hardwareAccelerated="true" in the manifest was the only thing that significantly improved the performance for me

More info here: http://developer.android.com/guide/topics/manifest/application-element.html#hwaccel

Google Chrome display JSON AJAX response as tree and not as a plain text

Google Chrome now supports this (Developer Tools > Network > [XHR item in list] Preview).

In addition, you can use a third party tool to format the json content. Here's one that presents a tree view, and here's another that merely formats the text (and does validation).

Regexp Java for password validation

easy one

("^ (?=.* [0-9]) (?=.* [a-z]) (?=.* [A-Z]) (?=.* [\\W_])[\\S]{8,10}$")

  1. (?= anything ) ->means positive looks forward in all input string and make sure for this condition is written .sample(?=.*[0-9])-> means ensure one digit number is written in the all string.if not written return false .

  2. (?! anything ) ->(vise versa) means negative looks forward if condition is written return false.

    close meaning ^(condition)(condition)(condition)(condition)[\S]{8,10}$

Injecting $scope into an angular service function()

Well (a long one) ... if you insist to have $scope access inside a service, you can:

Create a getter/setter service

ngapp.factory('Scopes', function (){
  var mem = {};
  return {
    store: function (key, value) { mem[key] = value; },
    get: function (key) { return mem[key]; }
  };
});

Inject it and store the controller scope in it

ngapp.controller('myCtrl', ['$scope', 'Scopes', function($scope, Scopes) {
  Scopes.store('myCtrl', $scope);
}]);

Now, get the scope inside another service

ngapp.factory('getRoute', ['Scopes', '$http', function(Scopes, $http){
  // there you are
  var $scope = Scopes.get('myCtrl');
}]);

What ports does RabbitMQ use?

To find out what ports rabbitmq uses:

$ epmd -names

Outputs:

epmd: up and running on port 4369 with data:
name rabbit at port 25672

Run these as root:

lsof -i :4369
lsof -i :25672

More about epmd options.

How to calculate the running time of my program?

Beside the well-known (and already mentioned) System.currentTimeMillis() and System.nanoTime() there is also a neat library called perf4j which might be useful too, depending on your purpose of course.

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;
}

how to set the default value to the drop down list control?

lstDepartment.DataTextField = "DepartmentName";
lstDepartment.DataValueField = "DepartmentID";
lstDepartment.DataSource = dtDept;
lstDepartment.DataBind();
'Set the initial value:
lstDepartment.SelectedValue = depID;
lstDepartment.Attributes.Remove("InitialValue");
lstDepartment.Attributes.Add("InitialValue", depID);

And in your cancel method:

lstDepartment.SelectedValue = lstDepartment.Attributes("InitialValue");

And in your update method:

lstDepartment.Attributes("InitialValue") = lstDepartment.SelectedValue;

Using relative URL in CSS file, what location is it relative to?

One issue that can occur, and seemingly break this is when using auto minimization of css. The request path for the minified bundle can have a different path than the original css. This may happen automatically so it can cause confusion.

The mapped request path for the minified bundle should be "/originalcssfolder/minifiedbundlename" not just "minifiedbundlename".

In other words, name your bundles to have same path (with the /) as the original folder structure, this way any external resources like fonts, images will map to correct URIs by the browser. The alternative is to use absolute url( refs in your css but that isn't usually desirable.

Project Links do not work on Wamp Server

I believe this is the best solution:

Open index.php in www folder and set

change line 30:$suppress_localhost = true;

to $suppress_localhost = false;

This will ensure the project is prefixed with your local host IP/name

How to plot a function curve in R

You mean like this?

> eq = function(x){x*x}
> plot(eq(1:1000), type='l')

Plot of eq over range 1:1000

(Or whatever range of values is relevant to your function)

Linq where clause compare only date value without time value

Try this,

var _My_ResetSet_Array = _DB
    .tbl_MyTable
    .Where(x => x.Active == true
         && x.DateTimeValueColumn <= DateTime.Now)
    .Select(x => x.DateTimeValueColumn)
    .AsEnumerable()
    .select(p=>p.DateTimeValueColumn.value.toString("YYYY-MMM-dd");

iPhone and WireShark

You can proceed as follow:

  1. Install Charles Web Proxy.
  2. Disable SSL proxying (uncheck the flag in Proxy->Proxy Settings...->SSL
  3. Connect your iDevice to the Charles proxy, as explained here
  4. Sniff the packets via Wireshark or Charles

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

In my case increasing mem by setting MAVEN_OPTS helped:

set MAVEN_OPTS=-Xmx1024m

Permutations in JavaScript?

const removeItem = (arr, i) => {
  return arr.slice(0, i).concat(arr.slice(i+1));
}

const makePermutations = (strArr) => {
  const doPermutation = (strArr, pairArr) => {
    return strArr.reduce((result, permutItem, i) => {
      const currentPair = removeItem(pairArr, i);
      const tempResult = currentPair.map((item) => permutItem+item);
      return tempResult.length === 1 ? result.concat(tempResult) :
             result.concat(doPermutation(tempResult, currentPair));
    }, []);
  }
  return strArr.length === 1 ? strArr :
         doPermutation(strArr, strArr);
}


makePermutations(["a", "b", "c", "d"]);
//result: ["abcd", "abdc", "acbd", "acdb", "adbc", "adcb", "bacd", "badc", "bcad", "bcda", "bdac", "bdca", "cabd", "cadb", "cbad", "cbda", "cdab", "cdba", "dabc", "dacb", "dbac", "dbca", "dcab", "dcba"]

Sum of Numbers C++

You can try:

int sum = startingNumber; 
for (int i=0; i < positiveInteger; i++) {     
    sum += i;
}
cout << sum;

But much easier is to note that the sum 1+2+...+n = n*(n+1) / 2, so you do not need a loop at all, just use the formula n*(n+1)/2.

Stock ticker symbol lookup API

Your best bets are probably going with one of the other lookup services (still screen-scraping), and checking whether they don't require CAPTCHAs.

The last appears the least likely to require a CAPTCHA at any point, but it's worth checking all three.

Invalid URI: The format of the URI could not be determined

Check possible reasons here: http://msdn.microsoft.com/en-us/library/z6c2z492(v=VS.100).aspx

EDIT:

You need to put the protocol prefix in front the address, i.e. in your case "ftp://"

convert php date to mysql format

If intake_date is some common date format you can use date() and strtotime()

$mysqlDate = date('Y-m-d H:i:s', strtotime($_POST['intake_date']));

However, this will only work if the date format is accepted by strtotime(). See it's doc page for supported formats.

What's the complete range for Chinese characters in Unicode?

The exact ranges for Chinese characters (except the extensions) are [\u2E80-\u2FD5\u3190-\u319f\u3400-\u4DBF\u4E00-\u9FCC\uF900-\uFAAD].

  1. [\u2e80-\u2fd5]

CJK Radicals Supplement is a Unicode block containing alternative, often positional, forms of the Kangxi radicals. They are used headers in dictionary indices and other CJK ideograph collections organized by radical-stroke.

  1. [\u3190-\u319f]

Kanbun is a Unicode block containing annotation characters used in Japanese copies of classical Chinese texts, to indicate reading order.

  1. [\u3400-\u4DBF]

CJK Unified Ideographs Extension-A is a Unicode block containing rare Han ideographs.

  1. [\u4E00-\u9FCC]

CJK Unified Ideographs is a Unicode block containing the most common CJK ideographs used in modern Chinese and Japanese.

  1. [\uF900-\uFAAD]

CJK Compatibility Ideographs is a Unicode block created to contain Han characters that were encoded in multiple locations in other established character encodings, in addition to their CJK Unified Ideographs assignments, in order to retain round-trip compatibility between Unicode and those encodings.

For the details please refer to here, and the extensions are provided in other answers.

How to add "class" to host element?

You can simply add @HostBinding('class') class = 'someClass'; inside your @Component class.

Example:

@Component({
   selector: 'body',
   template: 'app-element'       
})
export class App implements OnInit {

  @HostBinding('class') class = 'someClass';

  constructor() {}      

  ngOnInit() {}
}

Execute Shell Script after post build in Jenkins

You can also run arbitrary commands using the Groovy Post Build - and that will give you a lot of control over when they run and so forth. We use that to run a 'finger of blame' shell script in the case of failed or unstable builds.

if (manager.build.result.isWorseThan(hudson.model.Result.SUCCESS)) {
  item = hudson.model.Hudson.instance.getItem("PROJECTNAMEHERE")
  lastStableBuild = item.getLastStableBuild()
  lastStableDate = lastStableBuild.getTime()
  formattedLastStableDate = lastStableDate.format("MM/dd/yyyy h:mm:ss a")
  now = new Date()
  formattedNow = now.format("MM/dd/yyyy h:mm:ss a")
  command = ['/appframe/jenkins/appframework/fob.ksh', "${formattedLastStableDate}", "${formattedNow}"]
  manager.listener.logger.println "FOB Command: ${command}"
  manager.listener.logger.println command.execute().text
}

(Our command takes the last stable build date and the current time as parameters so it can go investigate who might have broken the build, but you could run whatever commands you like in a similar fashion)

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How to change MySQL timezone in a database connection using Java?

Is there a way we can get the list of supported timeZone from MySQL ? ex - serverTimezone=America/New_York. That can solve many such issue. I believe every time you need to specify the correct time zone from the Application irrespective of the DB TimeZone.

How to call a JavaScript function from PHP?

PHP runs in the server. JavaScript runs in the client. So php can't call a JavaScript function.

How to write log base(2) in c/c++

All the above answers are correct. This answer of mine below can be helpful if someone needs it. I have seen this requirement in many questions which we are solving using C.

log2 (x) = logy (x) / logy (2)

However, if you are using C language and you want the result in integer, you can use the following:

int result = (int)(floor(log(x) / log(2))) + 1;

Hope this helps.

jquery input select all on focus

Found a awesome solution reading this thread

$(function(){

    jQuery.selectText('input:text');
    jQuery.selectText('input:password');

});

jQuery.extend( {
    selectText: function(s) { 
        $(s).live('focus',function() {
            var self = $(this);
            setTimeout(function() {self.select();}, 0);
        });
    }
});

Best way to iterate through a Perl array

1 is substantially different from 2 and 3, since it leaves the array in tact, whereas the other two leave it empty.

I'd say #3 is pretty wacky and probably less efficient, so forget that.

Which leaves you with #1 and #2, and they do not do the same thing, so one cannot be "better" than the other. If the array is large and you don't need to keep it, generally scope will deal with it (but see NOTE), so generally, #1 is still the clearest and simplest method. Shifting each element off will not speed anything up. Even if there is a need to free the array from the reference, I'd just go:

undef @Array;

when done.

  • NOTE: The subroutine containing the scope of the array actually keeps the array and re-uses the space next time. Generally, that should be fine (see comments).

Is it possible to modify a registry entry via a .bat/.cmd script?

Yes. You can use reg.exe which comes with the OS to add, delete or query registry values. Reg.exe does not have an explicit modify command, but you can do it by doing delete and then add.

How can I start an interactive console for Perl?

Not only did Matt Trout write an article about a REPL, he actually wrote one - Devel::REPL

I've used it a bit and it works fairly well, and it's under active development.

BTW, I have no idea why someone modded down the person who mentioned using "perl -e" from the console. This isn't really a REPL, true, but it's fantastically useful, and I use it all the time.

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

Accessing SQL Database in Excel-VBA

Suggested changes:

  • Do not invoke the Command object's Execute method;
  • Set the Recordset object's Source property to be your Command object;
  • Invoke the Recordset object's Open method with no parameters;
  • Remove the parentheses from around the Recordset object in the call to CopyFromRecordset;
  • Actually declare your variables :)

Revised code:

Sub GetDataFromADO()

    'Declare variables'
        Dim objMyConn As ADODB.Connection
        Dim objMyCmd As ADODB.Command
        Dim objMyRecordset As ADODB.Recordset

        Set objMyConn = New ADODB.Connection
        Set objMyCmd = New ADODB.Command
        Set objMyRecordset = New ADODB.Recordset

    'Open Connection'
        objMyConn.ConnectionString = "Provider=SQLOLEDB;Data Source=localhost;User ID=abc;Password=abc;"    
        objMyConn.Open

    'Set and Excecute SQL Command'
        Set objMyCmd.ActiveConnection = objMyConn
        objMyCmd.CommandText = "select * from mytable"
        objMyCmd.CommandType = adCmdText

    'Open Recordset'
        Set objMyRecordset.Source = objMyCmd
        objMyRecordset.Open

    'Copy Data to Excel'
        ActiveSheet.Range("A1").CopyFromRecordset objMyRecordset

End Sub

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

Java Revisited

  1. Resource included by include directive is loaded during jsp translation time, while resource included by include action is loaded during request time.
  2. Any change on included resource will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in next request.
  3. Include directive is static import, while include action is dynamic import
  4. Include directive uses file attribute to specify resource to be included while include action use page attribute for same purpose.

Error in styles_base.xml file - android app - No resource found that matches the given name 'android:Widget.Material.ActionButton'

I am writing application to API level 21, I tried all the above but didn't worked, Finally i deleted Values-v23 from appcompat_v7.It worked.

What does $@ mean in a shell script?

From the manual:

@

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" .... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

100% width in React Native Flexbox

Here you go:

Just change the line1 style as per below:

line1: {
    backgroundColor: '#FDD7E4',
    width:'100%',
    alignSelf:'center'
}

Can I have H2 autocreate a schema in an in-memory database?

If you are using spring with application.yml the following will work for you

spring: datasource: url: jdbc:h2:mem:mydb;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS calendar

Best C++ IDE or Editor for Windows

Emacs. Xemacs works fine under Windows. For using it as an IDE, I recommend running it under Cygwin.

Is it possible to preview stash contents in git?

Beyond the gitk recommendation in Is it possible to preview stash contents in git? you can install tig and call tig stash. This free/open console program also allows you to choose which stash to compare

Converting dd/mm/yyyy formatted string to Datetime

use DateTime.ParseExact

string strDate = "24/01/2013";
DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", null)

null will use the current culture, which is somewhat dangerous. Try to supply a specific culture

DateTime date = DateTime.ParseExact(strDate, "dd/MM/YYYY", CultureInfo.InvariantCulture)

Fixed position but relative to container

Yes it is possible as long as you don't set the position (top or left, etc.) of your fixed element (you can still use margin to set a relative position, though). Simon Bos posted about this a while ago.

However don't expect fixed element to scroll with non-fixed relatives.

See a demo here.

Should black box or white box testing be the emphasis for testers?

What constitutes, "internal knowledge?" Does knowing that such-and-such algorithm was used to solve a problem qualify or does the tester have to see every line of code for it to be "internal?"

I think in any test case, there should be expected results given by the specification used and not determined by how the tester decides to interpret the specification as this can lead to issues where each thinks they are right and blaming the other for the problem.

How to get the size of a string in Python?

>>> s = 'abcd'
>>> len(s)
4

must declare a named package eclipse because this compilation unit is associated to the named module

The "delete module-info.java at your Project Explorer tab" answer is the easiest and most straightforward answer, but

for those who would want a little more understanding or control of what's happening, the following alternate methods may be desirable;

  • make an ever so slightly more realistic application; com.YourCompany.etc or just com.HelloWorld (Project name: com.HelloWorld and class name: HelloWorld)

or

  • when creating the java project; when in the Create Java Project dialog, don't choose Finish but Next, and deselect Create module-info.java file

Oracle PL/SQL - Are NO_DATA_FOUND Exceptions bad for stored procedure performance?

I would not use an explicit cursor to do this. Steve F. no longer advises people to use explicit cursors when an implicit cursor could be used.

The method with count(*) is unsafe. If another session deletes the row that met the condition after the line with the count(*), and before the line with the select ... into, the code will throw an exception that will not get handled.

The second version from the original post does not have this problem, and it is generally preferred.

That said, there is a minor overhead using the exception, and if you are 100% sure the data will not change, you can use the count(*), but I recommend against it.

I ran these benchmarks on Oracle 10.2.0.1 on 32 bit Windows. I am only looking at elapsed time. There are other test harnesses that can give more details (such as latch counts and memory used).

SQL>create table t (NEEDED_FIELD number, COND number);

Table created.

SQL>insert into t (NEEDED_FIELD, cond) values (1, 0);

1 row created.

declare
  otherVar  number;
  cnt number;
begin
  for i in 1 .. 50000 loop
     select count(*) into cnt from t where cond = 1;

     if (cnt = 1) then
       select NEEDED_FIELD INTO otherVar from t where cond = 1;
     else
       otherVar := 0;
     end if;
   end loop;
end;
/

PL/SQL procedure successfully completed.

Elapsed: 00:00:02.70

declare
  otherVar  number;
begin
  for i in 1 .. 50000 loop
     begin
       select NEEDED_FIELD INTO otherVar from t where cond = 1;
     exception
       when no_data_found then
         otherVar := 0;
     end;
   end loop;
end;
/

PL/SQL procedure successfully completed.

Elapsed: 00:00:03.06

Bootstrap 3: Offset isn't working?

If I get you right, you want something that seems to be the opposite of what is desired normally: you want a horizontal layout for small screens and vertically stacked elements on large screens. You may achieve this in a way like this:

<div class="container">
    <div class="row">
        <div class="hidden-md hidden-lg col-xs-3 col-xs-offset-6">a</div>
        <div class="hidden-md hidden-lg col-xs-3">b</div>
    </div>
    <div class="row">
        <div class="hidden-xs hidden-sm">c</div>

    </div>
</div>

On small screens, i.e. xs and sm, this generates one row with two columns with an offset of 6. On larger screens, i.e. md and lg, it generates two vertically stacked elements in full width (12 columns).

In Node.js, how do I "include" functions from my other files?

If, despite all the other answers, you still want to traditionally include a file in a node.js source file, you can use this:

var fs = require('fs');

// file is included here:
eval(fs.readFileSync('tools.js')+'');
  • The empty string concatenation +'' is necessary to get the file content as a string and not an object (you can also use .toString() if you prefer).
  • The eval() can't be used inside a function and must be called inside the global scope otherwise no functions or variables will be accessible (i.e. you can't create a include() utility function or something like that).

Please note that in most cases this is bad practice and you should instead write a module. However, there are rare situations, where pollution of your local context/namespace is what you really want.

Update 2015-08-06

Please also note this won't work with "use strict"; (when you are in "strict mode") because functions and variables defined in the "imported" file can't be accessed by the code that does the import. Strict mode enforces some rules defined by newer versions of the language standard. This may be another reason to avoid the solution described here.

What is the purpose of the "role" attribute in HTML?

I realise this is an old question, but another possible consideration depending on your exact requirements is that validating on https://validator.w3.org/ generates warnings as follows:

Warning: The form role is unnecessary for element form.

#if DEBUG vs. Conditional("DEBUG")

It really depends on what you're going for:

  • #if DEBUG: The code in here won't even reach the IL on release.
  • [Conditional("DEBUG")]: This code will reach the IL, however calls to the method will be omitted unless DEBUG is set when the caller is compiled.

Personally I use both depending on the situation:

Conditional("DEBUG") Example: I use this so that I don't have to go back and edit my code later during release, but during debugging I want to be sure I didn't make any typos. This function checks that I type a property name correctly when trying to use it in my INotifyPropertyChanged stuff.

[Conditional("DEBUG")]
[DebuggerStepThrough]
protected void VerifyPropertyName(String propertyName)
{
    if (TypeDescriptor.GetProperties(this)[propertyName] == null)
        Debug.Fail(String.Format("Invalid property name. Type: {0}, Name: {1}",
            GetType(), propertyName));
}

You really don't want to create a function using #if DEBUG unless you are willing to wrap every call to that function with the same #if DEBUG:

#if DEBUG
    public void DoSomething() { }
#endif

    public void Foo()
    {
#if DEBUG
        DoSomething(); //This works, but looks FUGLY
#endif
    }

versus:

[Conditional("DEBUG")]
public void DoSomething() { }

public void Foo()
{
    DoSomething(); //Code compiles and is cleaner, DoSomething always
                   //exists, however this is only called during DEBUG.
}

#if DEBUG example: I use this when trying to setup different bindings for WCF communication.

#if DEBUG
        public const String ENDPOINT = "Localhost";
#else
        public const String ENDPOINT = "BasicHttpBinding";
#endif

In the first example, the code all exists, but is just ignored unless DEBUG is on. In the second example, the const ENDPOINT is set to "Localhost" or "BasicHttpBinding" depending on if DEBUG is set or not.


Update: I am updating this answer to clarify an important and tricky point. If you choose to use the ConditionalAttribute, keep in mind that calls are omitted during compilation, and not runtime. That is:

MyLibrary.dll

[Conditional("DEBUG")]
public void A()
{
    Console.WriteLine("A");
    B();
}

[Conditional("DEBUG")]
public void B()
{
    Console.WriteLine("B");
}

When the library is compiled against release mode (i.e. no DEBUG symbol), it will forever have the call to B() from within A() omitted, even if a call to A() is included because DEBUG is defined in the calling assembly.

How can one print a size_t variable portably using the printf family?

As AraK said, the c++ streams interface will always work portably.

std::size_t s = 1024; std::cout << s; // or any other kind of stream like stringstream!

If you want C stdio, there is no portable answer to this for certain cases of "portable." And it gets ugly since as you've seen, picking the wrong format flags may yield a compiler warning or give incorrect output.

C99 tried to solve this problem with inttypes.h formats like "%"PRIdMAX"\n". But just as with "%zu", not everyone supports c99 (like MSVS prior to 2013). There are "msinttypes.h" files floating around to deal with this.

If you cast to a different type, depending on flags you may get a compiler warning for truncation or a change of sign. If you go this route pick a larger relevant fixed size type. One of unsigned long long and "%llu" or unsigned long "%lu" should work, but llu may also slow things down in a 32bit world as excessively large. (Edit - my mac issues a warning in 64 bit for %llu not matching size_t, even though %lu, %llu, and size_t are all the same size. And %lu and %llu are not the same size on my MSVS2012. So you may need to cast + use a format that matches.)

For that matter, you can go with fixed size types, such as int64_t. But wait! Now we're back to c99/c++11, and older MSVS fails again. Plus you also have casts (e.g. map.size() is not a fixed size type)!

You can use a 3rd party header or library such as boost. If you're not already using one, you may not want to inflate your project that way. If you're willing to add one just for this issue, why not use c++ streams, or conditional compilation?

So you're down to c++ streams, conditional compilation, 3rd party frameworks, or something sort of portable that happens to work for you.

How can I make window.showmodaldialog work in chrome 37?

    (function() {
        window.spawn = window.spawn || function(gen) {
            function continuer(verb, arg) {
                var result;
                try {
                    result = generator[verb](arg);
                } catch (err) {
                    return Promise.reject(err);
                }
                if (result.done) {
                    return result.value;
                } else {
                    return Promise.resolve(result.value).then(onFulfilled, onRejected);
                }
            }
            var generator = gen();
            var onFulfilled = continuer.bind(continuer, 'next');
            var onRejected = continuer.bind(continuer, 'throw');
            return onFulfilled();
        };
        window.showModalDialog = window.showModalDialog || function(url, arg, opt) {
            url = url || ''; //URL of a dialog
            arg = arg || null; //arguments to a dialog
            opt = opt || 'dialogWidth:300px;dialogHeight:200px'; //options: dialogTop;dialogLeft;dialogWidth;dialogHeight or CSS styles
            var caller = showModalDialog.caller.toString();
            var dialog = document.body.appendChild(document.createElement('dialog'));
            dialog.setAttribute('style', opt.replace(/dialog/gi, ''));
            dialog.innerHTML = '<a href="#" id="dialog-close" style="position: absolute; top: 0; right: 4px; font-size: 20px; color: #000; text-decoration: none; outline: none;">&times;</a><iframe id="dialog-body" src="' + url + '" style="border: 0; width: 100%; height: 100%;"></iframe>';
            document.getElementById('dialog-body').contentWindow.dialogArguments = arg;
            document.getElementById('dialog-close').addEventListener('click', function(e) {
                e.preventDefault();
                dialog.close();
            });
            dialog.showModal();
            //if using yield
            if(caller.indexOf('yield') >= 0) {
                return new Promise(function(resolve, reject) {
                    dialog.addEventListener('close', function() {
                        var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
                        document.body.removeChild(dialog);
                        resolve(returnValue);
                    });
                });
            }
            //if using eval
            var isNext = false;
            var nextStmts = caller.split('\n').filter(function(stmt) {
                if(isNext || stmt.indexOf('showModalDialog(') >= 0)
                    return isNext = true;
                return false;
            });
            dialog.addEventListener('close', function() {
                var returnValue = document.getElementById('dialog-body').contentWindow.returnValue;
                document.body.removeChild(dialog);
                nextStmts[0] = nextStmts[0].replace(/(window\.)?showModalDialog\(.*\)/g, JSON.stringify(returnValue));
                eval('{\n' + nextStmts.join('\n'));
            });
            throw 'Execution stopped until showModalDialog is closed';
        };
    })()

;

**Explanation:
------------**
The best way to deal with showModalDialog for older application conversions is use to `https://github.com/niutech/showModalDialog` inorder to work with show modal dialogs  and if modal dailog has ajax calls you need to create object and set the parameters of function to object and pass below...before that check for browser and set the useragent...example: agentStr = navigator.userAgent; and then check for chrome

var objAcceptReject={}; // create empty object and set the parameters to object and send to the other functions as dialog when opened in chrome breaks the functionality
    function rejectClick(index, transferId) {
        objAcceptReject.index=index;
        objAcceptReject.transferId=transferId;

     agentStr = navigator.userAgent;

                var msie = ua.indexOf("MSIE ");

                if (msie > 0) // If Internet Explorer, return version number
                {
                    var ret = window.showModalDialog("/abc.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");   

                    if (ret=="true") {
                        doSomeClick(index);
                    }

                } else if ((agentStr.indexOf("Chrome")) >- 1){
                spawn(function() {

                    var ret = window.showModalDialog("/abcd.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");   

                    if (ret=="true") {// create an object and store values in objects and send as parameters
                        doSomeClick(objAcceptReject.index);
                    }

                });

                }
                else {
                    var ret = window.showModalDialog("/xtz.jsp?accept=false",window,"dialogHeight:175px;dialogWidth:475px;scroll:no;status:no;help:no");   

                    if (ret=="true") {
                        doSomeClick(index);
                    }
                }

add new row in gridview after binding C#, ASP.net

you can try the following code

protected void Button1_Click(object sender, EventArgs e)
   {
       DataTable dt = new DataTable();

       if (dt.Columns.Count == 0)
       {
           dt.Columns.Add("PayScale", typeof(string));
           dt.Columns.Add("IncrementAmt", typeof(string));
           dt.Columns.Add("Period", typeof(string));
       }

       DataRow NewRow = dt.NewRow();
       NewRow[0] = TextBox1.Text;
       NewRow[1] = TextBox2.Text;
       dt.Rows.Add(NewRow); 
       GridView1.DataSource = dt;
       GridViewl.DataBind();
   }

here payscale,incrementamt and period are database field name.

Draw line in UIView

Based on Guy Daher's answer.

I try to avoid using ? because it can cause an application crash if the GetCurrentContext() returns nil.

I would do nil check if statement:

class CustomView: UIView 
{    
    override func draw(_ rect: CGRect) 
    {
        super.draw(rect)
        if let context = UIGraphicsGetCurrentContext()
        {
            context.setStrokeColor(UIColor.gray.cgColor)
            context.setLineWidth(1)
            context.move(to: CGPoint(x: 0, y: bounds.height))
            context.addLine(to: CGPoint(x: bounds.width, y: bounds.height))
            context.strokePath()
        }
    }
}

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

Find an object in SQL Server (cross-database)

You can use sp_MSforeachdb to search all databases.

declare @RETURN_VALUE int

declare @command1 nvarchar(2000)

set @command1 = "Your command goes here"

exec @RETURN_VALUE = sp_MSforeachdb @command1 = @command1

Raj

make bootstrap twitter dialog modal draggable

In my case I am enabling draggable. It works.

var bootstrapDialog = new BootstrapDialog({
    title: 'Message',
    draggable: true,
    closable: false,
    size: BootstrapDialog.SIZE_WIDE,
    message: 'Hello World',
    buttons: [{
         label: 'close',
         action: function (dialogRef) {
             dialogRef.close();
         }
     }],
});
bootstrapDialog.open();

Might be it helps you.

jQuery creating objects

You can always make it a function

function writeObject(color){
    $('body').append('<div style="color:'+color+';">Hello!</div>')
}

writeObject('blue') ? enter image description here

How do I check if a cookie exists?

document.cookie.indexOf('cookie_name=');

It will return -1 if that cookie does not exist.

p.s. Only drawback of it is (as mentioned in comments) that it will mistake if there is cookie set with such name: any_prefix_cookie_name

(Source)

Regular Expression to select everything before and up to a particular text

Up to and including txt you would need to change your regex like so:

^(.*?\\.txt)

background-size in shorthand background property (CSS3)

Just a note for reference: I was trying to do shorthand like so:

background: url('../images/sprite.png') -312px -234px / 355px auto no-repeat;

but iPhone Safari browsers weren't showing the image properly with a fixed position element. I didn't check with a non-fixed, because I'm lazy. I had to switch the css to what's below, being careful to put background-size after the background property. If you do them in reverse, the background reverts the background-size to the original size of the image. So generally I would avoid using the shorthand to set background-size.

background: url('../images/sprite.png') -312px -234px no-repeat;
background-size: 355px auto;

How to find lines containing a string in linux

/tmp/myfile

first line text
wanted text
other text

the command

$ grep -n "wanted text" /tmp/myfile | awk -F  ":" '{print $1}'
2