Programs & Examples On #Asynctoken

Simple example of threading in C++

There is also a POSIX library for POSIX operating systems. Check for compatability

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>

void *task(void *argument){
      char* msg;
      msg = (char*)argument;
      std::cout<<msg<<std::endl;
}

int main(){
    pthread_t thread1, thread2;
    int i1,i2;
    i1 = pthread_create( &thread1, NULL, task, (void*) "thread 1");
    i2 = pthread_create( &thread2, NULL, task, (void*) "thread 2");

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return 0;

}

compile with -lpthread

http://en.wikipedia.org/wiki/POSIX_Threads

How to enable assembly bind failure logging (Fusion) in .NET

The Fusion Log Settings Viewer changer script is bar none the best way to do this.

In ASP.NET, it has been tricky at times to get this to work correctly. This script works great and was listed on Scott Hanselman's Power Tool list as well. I've personally used it for years and its never let me down.

Python equivalent of a given wget command

Let me Improve a example with threads in case you want download many files.

import math
import random
import threading

import requests
from clint.textui import progress

# You must define a proxy list
# I suggests https://free-proxy-list.net/
proxies = {
    0: {'http': 'http://34.208.47.183:80'},
    1: {'http': 'http://40.69.191.149:3128'},
    2: {'http': 'http://104.154.205.214:1080'},
    3: {'http': 'http://52.11.190.64:3128'}
}


# you must define the list for files do you want download
videos = [
    "https://i.stack.imgur.com/g2BHi.jpg",
    "https://i.stack.imgur.com/NURaP.jpg"
]

downloaderses = list()


def downloaders(video, selected_proxy):
    print("Downloading file named {} by proxy {}...".format(video, selected_proxy))
    r = requests.get(video, stream=True, proxies=selected_proxy)
    nombre_video = video.split("/")[3]
    with open(nombre_video, 'wb') as f:
        total_length = int(r.headers.get('content-length'))
        for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length / 1024) + 1):
            if chunk:
                f.write(chunk)
                f.flush()


for video in videos:
    selected_proxy = proxies[math.floor(random.random() * len(proxies))]
    t = threading.Thread(target=downloaders, args=(video, selected_proxy))
    downloaderses.append(t)

for _downloaders in downloaderses:
    _downloaders.start()

Deleting rows with Python in a CSV file

You are very close; currently you compare the row[2] with integer 0, make the comparison with the string "0". When you read the data from a file, it is a string and not an integer, so that is why your integer check fails currently:

row[2]!="0":

Also, you can use the with keyword to make the current code slightly more pythonic so that the lines in your code are reduced and you can omit the .close statements:

import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != "0":
            writer.writerow(row)

Note that input is a Python builtin, so I've used another variable name instead.


Edit: The values in your csv file's rows are comma and space separated; In a normal csv, they would be simply comma separated and a check against "0" would work, so you can either use strip(row[2]) != 0, or check against " 0".

The better solution would be to correct the csv format, but in case you want to persist with the current one, the following will work with your given csv file format:

$ cat test.py 
import csv
with open('first.csv', 'rb') as inp, open('first_edit.csv', 'wb') as out:
    writer = csv.writer(out)
    for row in csv.reader(inp):
        if row[2] != " 0":
            writer.writerow(row)
$ cat first.csv 
6.5, 5.4, 0, 320
6.5, 5.4, 1, 320
$ python test.py 
$ cat first_edit.csv 
6.5, 5.4, 1, 320

How do I change the UUID of a virtual disk?

The correct command is the following one.

VBoxManage internalcommands sethduuid "/home/user/VirtualBox VMs/drupal/drupal.vhd"

The path for the virtual disk contains a space, so it must be enclosed in double quotes to avoid it is parsed as two parameters.

How do I alter the position of a column in a PostgreSQL database table?

"Alter column position" in the PostgreSQL Wiki says:

PostgreSQL currently defines column order based on the attnum column of the pg_attribute table. The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.

That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either. Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.

One other idea occurs to me: you can define a VIEW that specifies the order of columns how you like it, without changing the physical position of the column in the base table.

How to change current Theme at runtime in Android

If you want to change theme of an already existing activity, call recreate() after setTheme().

Note: don't call recreate if you change theme in onCreate(), to avoid infinite loop.

What is the correct way to read a serial port using .NET framework?

Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method

 using System;
 using System.IO.Ports;

 class SerialPortProgram 
 { 
  // Create the serial port with basic settings 
    private SerialPort port = new   SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One); 
    [STAThread] 
    static void Main(string[] args) 
    { 
      // Instatiate this 
      SerialPortProgram(); 
    } 

    private static void SerialPortProgram() 
    { 
        Console.WriteLine("Incoming Data:");
         // Attach a method to be called when there
         // is data waiting in the port's buffer 
        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); 
        // Begin communications 
        port.Open(); 
        // Enter an application loop to keep this thread alive 
        Console.ReadLine();
     } 

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 
       // Show all the incoming data in the port's buffer
       Console.WriteLine(port.ReadExisting()); 
    } 
}

Or is you want to do it based on what you were trying to do , you can try this

public class MySerialReader : IDisposable
{
  private SerialPort serialPort;
  private Queue<byte> recievedData = new Queue<byte>();

  public MySerialReader()
  {
    serialPort = new SerialPort();
    serialPort.Open();
    serialPort.DataReceived += serialPort_DataReceived;
  }

  void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
  {
    byte[] data = new byte[serialPort.BytesToRead];
    serialPort.Read(data, 0, data.Length);
    data.ToList().ForEach(b => recievedData.Enqueue(b));
    processData();
  }

  void processData()
  {
    // Determine if we have a "packet" in the queue
    if (recievedData.Count > 50)
    {
        var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
    }
  }

  public void Dispose()
  {
        if (serialPort != null)
        {
            serialPort.Dispose();
        }
  }

Remove Trailing Spaces and Update in Columns in SQL Server

If we also want to handle white spaces and unwanted tabs-

Check and Try the below script (Unit Tested)-

--Declaring
DECLARE @Tbl TABLE(col_1 VARCHAR(100));

--Test Samples
INSERT INTO @Tbl (col_1)
VALUES
('  EY     y            
Salem')
, ('  EY     P    ort       Chennai   ')
, ('  EY     Old           Park   ')
, ('  EY   ')
, ('  EY   ')
,(''),(null),('d                           
    f');

SELECT col_1 AS INPUT,
    LTRIM(RTRIM(
    REPLACE(
    REPLACE(
    REPLACE(
    REPLACE(
    REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(
        REPLACE(col_1,CHAR(10),' ')
        ,CHAR(11),' ')
        ,CHAR(12),' ')
        ,CHAR(13),' ')
        ,CHAR(14),' ')
        ,CHAR(160),' ')
        ,CHAR(13)+CHAR(10),' ')
    ,CHAR(9),' ')
    ,' ',CHAR(17)+CHAR(18))
    ,CHAR(18)+CHAR(17),'')
    ,CHAR(17)+CHAR(18),' ')
    )) AS [OUTPUT]
FROM @Tbl;

Stretch image to fit full container width bootstrap

In bootstrap 4.1, the w-100 class is required along with img-fluid for images smaller than the page to be stretched:

<div class="container">
  <div class="row">
    <img class='img-fluid w-100' src="#" alt="" />
  </div>
</div>

see closed issue: https://github.com/twbs/bootstrap/issues/20830

(As of 2018-04-20, the documentation is wrong: https://getbootstrap.com/docs/4.1/content/images/ says that img-fluid applies max-width: 100%; height: auto;" but img-fluid does not resolve the issue, and neither does manually adding those style attributes with or without bootstrap classes on the img tag.)

Authentication plugin 'caching_sha2_password' is not supported

I had an almost identical error:

Error while connecting to MySQL: Authentication plugin 'caching_sha2_password' is not supported

The solution for me was simple:

My db username/password creds were incorrect. The error was not descriptive of the problem, so I thought I would share this in case someone else runs into this.

FCM getting MismatchSenderId

You will have a server key something like this AIzaSyDiTEVq4Li1pj7IyraRlyRU9adc-49-KVY available in the Settings section of firebase console console.firebase.google.com/project/project-XXXXXXXXXXXXX/settings/cloudmessaging.

Specify the correct key with your code and try again.

How to convert Map keys to array?

Array.from(myMap.keys()) does not work in google application scripts.

Trying to use it results in the error TypeError: Cannot find function from in object function Array() { [native code for Array.Array, arity=1] }.

To get a list of keys in GAS do this:

var keysList = Object.keys(myMap);

What is size_t in C?

The manpage for types.h says:

size_t shall be an unsigned integer type

HTTP client timeout and server timeout

According to https://bugzilla.mozilla.org/show_bug.cgi?id=592284, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.

How to pass command line argument to gnuplot?

You can input variables via switch -e

$ gnuplot -e "filename='foo.data'" foo.plg

In foo.plg you can then use that variable

$ cat foo.plg 
plot filename
pause -1

To make "foo.plg" a bit more generic, use a conditional:

if (!exists("filename")) filename='default.dat'
plot filename
pause -1

Note that -e has to precede the filename otherwise the file runs before the -e statements. In particular, running a shebang gnuplot #!/usr/bin/env gnuplot with ./foo.plg -e ... CLI arguments will ignore use the arguments provided.

jQuery or Javascript - how to disable window scroll without overflow:hidden;

CSS 'fixed' solution (like Facebook does):

body_temp = $("<div class='body_temp' />")
    .append($('body').contents())
    .css('position', 'fixed')
    .css('top', "-" + scrolltop + 'px')
    .width($(window).width())
    .appendTo('body');

to toggle to normal state:

var scrolltop = Math.abs($('.body_temp').position().top);
$('body').append($('.body_temp').contents()).scrollTop(scrolltop);

It is more efficient to use if-return-return or if-else-return?

Since the return statement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).

The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the if condition is false anyway.

Note that Python supports a syntax that allows you to use only one return statement in your case:

return A+1 if A > B else A-1

Excel vba - convert string to number

If, for example, x = 5 and is stored as string, you can also just:

x = x + 0

and the new x would be stored as a numeric value.

ORA-01861: literal does not match format string

Just before executing the query: alter session set NLS_DATE_FORMAT = "DD.MM.YYYY HH24:MI:SS"; or whichever format you are giving the information to the date function. This should fix the ORA error

CSS media queries for screen sizes

Unless you have more style sheets than that, you've messed up your break points:

#1 (max-width: 700px)
#2 (min-width: 701px) and (max-width: 900px)
#3 (max-width: 901px)

The 3rd media query is probably meant to be min-width: 901px. Right now, it overlaps #1 and #2, and only controls the page layout by itself when the screen is exactly 901px wide.

Edit for updated question:

(max-width: 640px)
(max-width: 800px)
(max-width: 1024px)
(max-width: 1280px)

Media queries aren't like catch or if/else statements. If any of the conditions match, then it will apply all of the styles from each media query it matched. If you only specify a min-width for all of your media queries, it's possible that some or all of the media queries are matched. In your case, a device that's 640px wide matches all 4 of your media queries, so all for style sheets are loaded. What you are most likely looking for is this:

(max-width: 640px)
(min-width: 641px) and (max-width: 800px)
(min-width: 801px) and (max-width: 1024px)
(min-width: 1025px)

Now there's no overlap. The styles will only apply if the device's width falls between the widths specified.

Notify ObservableCollection when Item changes

One simple solution to this is to replace the item being changed in the ObservableCollection which notifies the collection of the changed item. In the sample code snippet below Artists is the ObservableCollection and artist is an item of the type in the ObservableCollection:

    var index = Artists.IndexOf(artist);
    Artists.RemoveAt(index);
    artist.IsFollowed = true; // change something in the item
    Artists.Insert(index, artist);

ASP.NET MVC - Extract parameter of an URL

I wrote this method:

    private string GetUrlParameter(HttpRequestBase request, string parName)
    {
        string result = string.Empty;

        var urlParameters = HttpUtility.ParseQueryString(request.Url.Query);
        if (urlParameters.AllKeys.Contains(parName))
        {
            result = urlParameters.Get(parName);
        }

        return result;
    }

And I call it like this:

string fooBar = GetUrlParameter(Request, "FooBar");
if (!string.IsNullOrEmpty(fooBar))
{

}

linux find regex

You should have a look on the -regextype argument of find, see manpage:

      -regextype type
          Changes the regular expression syntax understood by -regex and -iregex 
          tests which occur later on the command line.  Currently-implemented  
          types  are  emacs (this is the default), posix-awk, posix-basic, 
          posix-egrep and posix-extended. 

I guess the emacs type doesn't support the [[:digit:]] construct. I tried it with posix-extended and it worked as expected:

find -regextype posix-extended -regex '.*[1234567890]'
find -regextype posix-extended -regex '.*[[:digit:]]'

preg_match(); - Unknown modifier '+'

You need to use delimiters with regexes in PHP. You can use the often used /, but PHP lets you use any matching characters, so @ and # are popular.

Further Reading.

If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote().

how does Array.prototype.slice.call() work?

First, you should read how function invocation works in JavaScript. I suspect that alone is enough to answer your question. But here's a summary of what is happening:

Array.prototype.slice extracts the slice method from Array's prototype. But calling it directly won't work, as it's a method (not a function) and therefore requires a context (a calling object, this), otherwise it would throw Uncaught TypeError: Array.prototype.slice called on null or undefined.

The call() method allows you to specify a method's context, basically making these two calls equivalent:

someObject.slice(1, 2);
slice.call(someObject, 1, 2);

Except the former requires the slice method to exist in someObject's prototype chain (as it does for Array), whereas the latter allows the context (someObject) to be manually passed to the method.

Also, the latter is short for:

var slice = Array.prototype.slice;
slice.call(someObject, 1, 2);

Which is the same as:

Array.prototype.slice.call(someObject, 1, 2);

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

"Reuse types" is not always the problem when this error occurs.

When adding a reference to an older service, click 'advanced' and there 'Add Web Reference'. Now link to your wsdl and everything should be working.

How to convert string to binary?

You can access the code values for the characters in your string using the ord() built-in function. If you then need to format this in binary, the string.format() method will do the job.

a = "test"
print(' '.join(format(ord(x), 'b') for x in a))

(Thanks to Ashwini Chaudhary for posting that code snippet.)

While the above code works in Python 3, this matter gets more complicated if you're assuming any encoding other than UTF-8. In Python 2, strings are byte sequences, and ASCII encoding is assumed by default. In Python 3, strings are assumed to be Unicode, and there's a separate bytes type that acts more like a Python 2 string. If you wish to assume any encoding other than UTF-8, you'll need to specify the encoding.

In Python 3, then, you can do something like this:

a = "test"
a_bytes = bytes(a, "ascii")
print(' '.join(["{0:b}".format(x) for x in a_bytes]))

The differences between UTF-8 and ascii encoding won't be obvious for simple alphanumeric strings, but will become important if you're processing text that includes characters not in the ascii character set.

How to display a database table on to the table in the JSP page

you can also print the data onto your HTML/JSP document. like:-

<!DOCTYPE html>
<html>
<head>
    <title>Jsp Sample</title>
    <%@page import="java.sql.*;"%>
</head>
<body bgcolor=yellow>
    <%
    try
    {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=(Connection)DriverManager.getConnection(
            "jdbc:mysql://localhost:3306/forum","root","root");
        Statement st=con.createStatement();
        ResultSet rs=st.executeQuery("select * from student;");
    %><table border=1 align=center style="text-align:center">
      <thead>
          <tr>
             <th>ID</th>
             <th>NAME</th>
             <th>SKILL</th>
             <th>ACTION</th>
          </tr>
      </thead>
      <tbody>
        <%while(rs.next())
        {
            %>
            <tr>
                <td><%=rs.getString("id") %></td>
                <td><%=rs.getString("name") %></td>
                <td><%=rs.getString("skill") %></td>
                <td><%=rs.getString("action") %></td>
            </tr>
            <%}%>
           </tbody>
        </table><br>
    <%}
    catch(Exception e){
        out.print(e.getMessage());%><br><%
    }
    finally{
        st.close();
        con.close();
    }
    %>
</body>
</html>

<!--executeUpdate() mainupulation and executeQuery() for retriving-->

Recursive sub folder search and return files in a list python

This function will recursively put only files into a list.

import os


def ls_files(dir):
    files = list()
    for item in os.listdir(dir):
        abspath = os.path.join(dir, item)
        try:
            if os.path.isdir(abspath):
                files = files + ls_files(abspath)
            else:
                files.append(abspath)
        except FileNotFoundError as err:
            print('invalid directory\n', 'Error: ', err)
    return files

C# Change A Button's Background Color

In WPF, the background is not a Color, it is a Brush. So, try this for starters:

using System.Windows.Media;

// ....

ButtonToday.Background = new SolidColorBrush(Colors.Red);

More sensibly, though, you should probably look at doing this in your Xaml instead of in code.

How to get primary key column in Oracle?

Try This Code Here I created a table for get primary key column in oracle which is called test and then query

create table test
(
id int,
name varchar2(20),
city varchar2(20),
phone int,
constraint pk_id_name_city primary key (id,name,city)
);

SELECT cols.table_name, cols.column_name, cols.position, cons.status, cons.owner FROM all_constraints cons, all_cons_columns cols WHERE cols.table_name = 'TEST' AND cons.constraint_type = 'P' AND cons.constraint_name = cols.constraint_name AND cons.owner = cols.owner  ORDER BY cols.table_name, cols.position;

How to convert an int to string in C?

EDIT: As pointed out in the comment, itoa() is not a standard, so better use sprintf() approach suggested in the rivaling answer!


You can use itoa() function to convert your integer value to a string.

Here is an example:

int num = 321;
char snum[5];

// convert 123 to string [buf]
itoa(num, snum, 10);

// print our string
printf("%s\n", snum);

If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.

Setting network adapter metric priority in Windows 7

Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.

To change the priority of the connections:

  • Open your Adapter Settings (Control Panel\Network and Internet\Network Connections)
  • Click Alt to pull up the menu bar
  • Select Advanced -> Advanced Settings
  • Change the order of the connections so that the connection you want to have priority is top on the list

Java: How to stop thread?

You can create a boolean field and check it inside run:

public class Task implements Runnable {

   private volatile boolean isRunning = true;

   public void run() {

     while (isRunning) {
         //do work
     }
   }

   public void kill() {
       isRunning = false;
   }

}

To stop it just call

task.kill();

This should work.

How to check if Location Services are enabled?

private boolean isGpsEnabled()
{
    LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
    return service.isProviderEnabled(LocationManager.GPS_PROVIDER)&&service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}

Finding import static statements for Mockito constructs

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

Uncaught TypeError: Cannot read property 'length' of undefined

console.log(typeof json_data !== 'undefined'
    ? json_data.length : 'There is no spoon.');

...or more simply...

console.log(json_data ? json_data.length : 'json_data is null or undefined');

Git status shows files as changed even though contents are the same

Have you changed the mode of the files? I did it on my machine and the local dev machine had 777 given to all the files whereas the repo had 755 which showed every file as modified. I did git diff and it showed the old mode and new mode are different. If that is the problem then you can easily ignore them by git config core.filemode false
Cheers

Pretty-Print JSON in Java

You can use Gson like below

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(object);

From the post JSON pretty print using Gson

Alternatively, You can use Jackson like below

ObjectMapper mapper = new ObjectMapper();
String perttyStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);

From the post Pretty print JSON in Java (Jackson)

Hope this help!

Matching a space in regex

Use it like this to allow for single space.

$newtag = preg_replace("/[^a-zA-Z0-9\s]/", "", $tag)

How to secure MongoDB with username and password

Here is a javascript code to add users.

  1. Start mongod with --auth = true

  2. Access admin database from mongo shell and pass the javascript file.

    mongo admin "Filename.js"

    "Filename.js"

    // Adding admin user
    db.addUser("admin_username", " admin_password");
    // Authenticate admin user
    db.auth("admin_username ", " admin_password ");
    // use  database code from java script
    db = db.getSiblingDB("newDatabase");
    // Adding newDatabase database user  
    db.addUser("database_username ", " database_ password ");
    
  3. Now user addition is complete, we can verify accessing the database from mongo shell

xcopy file, rename, suppress "Does xxx specify a file name..." message

So, there is a simple fix for this. It is admittedly awkward, but it works. xcopy will not prompt to find out if the destination is a directory or file IF the new file(filename) already exists. If you precede your xcopy command with a simple echo to the new filename, it will overwrite the empty file. Example

echo.>newfile.txt
xcopy oldfile.txt newfile.txt /Y

Create a folder and sub folder in Excel VBA

This works like a charm in AutoCad VBA and I grabbed it from an excel forum. I don't know why you all make it so complicated?

FREQUENTLY ASKED QUESTIONS

Question: I'm not sure if a particular directory exists already. If it doesn't exist, I'd like to create it using VBA code. How can I do this?

Answer: You can test to see if a directory exists using the VBA code below:

(Quotes below are omitted to avoid confusion of programming code)


If Len(Dir("c:\TOTN\Excel\Examples", vbDirectory)) = 0 Then

   MkDir "c:\TOTN\Excel\Examples"

End If

http://www.techonthenet.com/excel/formulas/mkdir.php

ADB error: cannot connect to daemon

I face this problem on daily basis, so to resolve this I kill adb.exe by executing following command :

taskkill /f /im adb.exe

Note : You should have administrative rights to execute the above command.

How can I stop Chrome from going into debug mode?

You've accidentally set "Pause on Exceptions" to all/uncaught exceptions.

Go to the "Sources" tab. At the bottom toolbar, toggle the button that looks like the pause symbol surrounded by a circle (4th button from the left) until the color of the circle turns black to turn it off.

How to access the php.ini from my CPanel?

If you're on a shared hosting environment you won't have access to the php.ini to make these changes, if you need access, a virtual private server (VPS) or a dedicated server may be a better option if you're confident in managing it yourself.

Alternatively if you create a new file called .htaccess in your root of your web directory (Ensure it doesn't contain a .txt extension if using notepad to create the file) and copy something like this inside.

php_value settingToChange 6000

This will only work if your hosting provider let's you override the certain config value. Best to ask if it doesn't work after trying.

How to enumerate an enum with String type?

If you give the enum a raw Int value it will make looping much easier.

For example, you can use anyGenerator to get a generator that can enumerate across your values:

enum Suit: Int, CustomStringConvertible {
    case Spades, Hearts, Diamonds, Clubs
    var description: String {
        switch self {
        case .Spades:   return "Spades"
        case .Hearts:   return "Hearts"
        case .Diamonds: return "Diamonds"
        case .Clubs:    return "Clubs"
        }
    }
    static func enumerate() -> AnyGenerator<Suit> {
        var nextIndex = Spades.rawValue
        return anyGenerator { Suit(rawValue: nextIndex++) }
    }
}
// You can now use it like this:
for suit in Suit.enumerate() {
    suit.description
}
// or like this:
let allSuits: [Suit] = Array(Suit.enumerate())

However, this looks like a fairly common pattern, wouldn't it be nice if we could make any enum type enumerable by simply conforming to a protocol? Well with Swift 2.0 and protocol extensions, now we can!

Simply add this to your project:

protocol EnumerableEnum {
    init?(rawValue: Int)
    static func firstValue() -> Int
}
extension EnumerableEnum {
    static func enumerate() -> AnyGenerator<Self> {
        var nextIndex = firstRawValue()
        return anyGenerator { Self(rawValue: nextIndex++) }
    }
    static func firstRawValue() -> Int { return 0 }
}

Now any time you create an enum (so long as it has an Int raw value), you can make it enumerable by conforming to the protocol:

enum Rank: Int, EnumerableEnum {
    case Ace, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King
}
// ...
for rank in Rank.enumerate() { ... }

If your enum values don't start with 0 (the default), override the firstRawValue method:

enum DeckColor: Int, EnumerableEnum {
    case Red = 10, Blue, Black
    static func firstRawValue() -> Int { return Red.rawValue }
}
// ...
let colors = Array(DeckColor.enumerate())

The final Suit class, including replacing simpleDescription with the more standard CustomStringConvertible protocol, will look like this:

enum Suit: Int, CustomStringConvertible, EnumerableEnum {
    case Spades, Hearts, Diamonds, Clubs
    var description: String {
        switch self {
        case .Spades:   return "Spades"
        case .Hearts:   return "Hearts"
        case .Diamonds: return "Diamonds"
        case .Clubs:    return "Clubs"
        }
    }
}
// ...
for suit in Suit.enumerate() {
    print(suit.description)
}

Swift 3 syntax:

protocol EnumerableEnum {
    init?(rawValue: Int)
    static func firstRawValue() -> Int
}

extension EnumerableEnum {
    static func enumerate() -> AnyIterator<Self> {
        var nextIndex = firstRawValue()

        let iterator: AnyIterator<Self> = AnyIterator {
            defer { nextIndex = nextIndex + 1 }
            return Self(rawValue: nextIndex)
        }

        return iterator
    }

    static func firstRawValue() -> Int {
        return 0
    }
}

Jackson JSON custom serialization for certain fields

In case you don't want to pollute your model with annotations and want to perform some custom operations, you could use mixins.

ObjectMapper mapper = new ObjectMapper();
SimpleModule simpleModule = new SimpleModule();
simpleModule.setMixInAnnotation(Person.class, PersonMixin.class);
mapper.registerModule(simpleModule);

Override age:

public abstract class PersonMixin {
    @JsonSerialize(using = PersonAgeSerializer.class)
    public String age;
}

Do whatever you need with the age:

public class PersonAgeSerializer extends JsonSerializer<Integer> {
    @Override
    public void serialize(Integer integer, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeString(String.valueOf(integer * 52) + " months");
    }
}

How to enable TLS 1.2 in Java 7

Add this parameter to JAVA_OPTS or to the command line in Maven: -Dhttps.protocols=TLSv1.2

Difference between Divide and Conquer Algo and Dynamic Programming

Divide and Conquer

Divide and Conquer works by dividing the problem into sub-problems, conquer each sub-problem recursively and combine these solutions.

Dynamic Programming

Dynamic Programming is a technique for solving problems with overlapping subproblems. Each sub-problem is solved only once and the result of each sub-problem is stored in a table ( generally implemented as an array or a hash table) for future references. These sub-solutions may be used to obtain the original solution and the technique of storing the sub-problem solutions is known as memoization.

You may think of DP = recursion + re-use

A classic example to understand the difference would be to see both these approaches towards obtaining the nth fibonacci number. Check this material from MIT.


Divide and Conquer approach Divide and Conquer approach

Dynamic Programming Approach enter image description here

Clone private git repo with dockerfile

My key was password protected which was causing the problem, a working file is now listed below (for help of future googlers)

FROM ubuntu

MAINTAINER Luke Crooks "[email protected]"

# Update aptitude with new repo
RUN apt-get update

# Install software 
RUN apt-get install -y git
# Make ssh dir
RUN mkdir /root/.ssh/

# Copy over private key, and set permissions
# Warning! Anyone who gets their hands on this image will be able
# to retrieve this private key file from the corresponding image layer
ADD id_rsa /root/.ssh/id_rsa

# Create known_hosts
RUN touch /root/.ssh/known_hosts
# Add bitbuckets key
RUN ssh-keyscan bitbucket.org >> /root/.ssh/known_hosts

# Clone the conf files into the docker container
RUN git clone [email protected]:User/repo.git

Angular 4.3 - HttpClient set params

Before 5.0.0-beta.6

let httpParams = new HttpParams();
Object.keys(data).forEach(function (key) {
     httpParams = httpParams.append(key, data[key]);
});

Since 5.0.0-beta.6

Since 5.0.0-beta.6 (2017-09-03) they added new feature (accept object map for HttpClient headers & params)

Going forward the object can be passed directly instead of HttpParams.

getCountries(data: any) {
    // We don't need any more these lines
    // let httpParams = new HttpParams();
    // Object.keys(data).forEach(function (key) {
    //     httpParams = httpParams.append(key, data[key]);
    // });

    return this.httpClient.get("/api/countries", {params: data})
}

How to use random in BATCH script?

And just to be completely random for those who don't always want a black screen.

@(IF not "%1" == "max" (start /MAX cmd /Q /C %0 max&X)ELSE set A=0&set C=1&set V=A&wmic process where name="cmd.exe" CALL setpriority "REALTIME">NUL)&CLS
:Y
(IF %A% EQU 10 set A=A)&(IF %A% EQU 11 set A=B)&(IF %A% EQU 12 set A=C)&(IF %A% EQU 13 set A=D)&(IF %A% EQU 14 set A=E)&(IF %A% EQU 15 set A=F)
(IF %V% EQU 10 set V=A)&(IF %V% EQU 11 set V=B)&(IF %V% EQU 12 set V=C)&(IF %V% EQU 13 set V=D)&(IF %V% EQU 14 set V=E)&(IF %V% EQU 15 set V=F)
(IF %A% EQU %V% set A=0)
title %A%%V%%random%6%random%%random%%random%%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%%random%&color %A%%V%&ECHO %random%%C%%random%%random%%random%%random%6%random%9%random%%random%%random%%random%%random%%random%%random%%random%%random%&(IF %C% EQU 46 (TIMEOUT /T 1 /NOBREAK>nul&set C=1&CLS&SET /A A=%random% %%15 +1&SET /A V=%random% %%15 +1)ELSE set /A C=%C%+1)&goto Y

This will change screen color also both are random.

addClass and removeClass in jQuery - not removing class

Try this :

$('.close-button').on('click', function(){
  $('.element').removeClass('grown');
  $('.element').addClass('spot');
});

$('.element').on('click', function(){
  $(this).removeClass('spot');
  $(this).addClass('grown');
});

I hope I understood your question.

How to check if memcache or memcached is installed for PHP?

this is my test function that I use to check Memcache on the server

<?php     
public function test()
 {
    // memcache test - make sure you have memcache extension installed and the deamon is up and running
    $memcache = new Memcache;
    $memcache->connect('localhost', 11211) or die ("Could not connect");

    $version = $memcache->getVersion();
    echo "Server's version: ".$version."<br/>\n";

    $tmp_object = new stdClass;
    $tmp_object->str_attr = 'test';
    $tmp_object->int_attr = 123;

    $memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
    echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";

    $get_result = $memcache->get('key');
    echo "Data from the cache:<br/>\n";

    var_dump($get_result);
 }

if you see something like this

    Server's version: 1.4.5_4_gaa7839e
    Store data in the cache (data will expire in 10 seconds)
    Data from the cache:
    object(stdClass)#3 (2) { ["str_attr"]=> string(4) "test" ["int_attr"]=> int(123) }

it means that everything is okay

Cheers!

Aligning two divs side-by-side

If you wrapped your divs, like this:

<div id="main">
  <div id="sidebar"></div>
  <div id="page-wrap"></div>
</div>

You could use this styling:

#main { 
    width: 800px;
    margin: 0 auto;
}
#sidebar    {
    width: 200px;
    height: 400px;
    background: red;
    float: left;
}

#page-wrap  {
    width: 600px;
    background: #ffffff;
    height: 400px;
    margin-left: 200px;
}

This is a slightly different look though, so I'm not sure it's what you're after. This would center all 800px as a unit, not the 600px centered with the 200px on the left side. The basic approach is your sidebar floats left, but inside the main div, and the #page-wrap has the width of your sidebar as it's left margin to move that far over.

Update based on comments: For this off-centered look, you can do this:

<div id="page-wrap">
  <div id="sidebar"></div>
</div>

With this styling:

#sidebar    {
    position: absolute;
    left: -200px;
    width: 200px;
    height: 400px;
    background: red;    
}

#page-wrap  {
    position: relative;
    width: 600px;
    background: #ffffff;
    height: 400px;
    margin: 0 auto;
}

Reportviewer tool missing in visual studio 2017 RC

Please NOTE that this procedure of adding the reporting services described by @Rich Shealer above will be iterated every time you start a different project. In order to avoid that:

  1. If you may need to set up a different computer (eg, at home without internet), then keep your downloaded installers from the marketplace somewhere safe, ie:

    • Microsoft.DataTools.ReportingServices.vsix, and
    • Microsoft.RdlcDesigner.vsix
  2. Fetch the following libraries from the packages or bin folder of the application you have created with reporting services in it:

    • Microsoft.ReportViewer.Common.dll
    • Microsoft.ReportViewer.DataVisualization.dll
    • Microsoft.ReportViewer.Design.dll
    • Microsoft.ReportViewer.ProcessingObjectModel.dll
    • Microsoft.ReportViewer.WinForms.dll
  3. Install the 2 components from 1 above

  4. Add the dlls from 2 above as references (Project>References>Add...)
  5. (Optional) Add Reporting tab to the toolbar
  6. Add Items to Reporting tab
  7. Browse to the bin folder or where you have the above dlls and add them

You are now good to go! ReportViewer icon will be added to your toolbar, and you will also now find Report and ReportWizard templates added to your Common list of templates when you want to add a New Item... (Report) to your project

NB: When set up using Nuget package manager, the Report and ReportWizard templates are grouped under Reporting. Using my method described above however does not add the Reporting grouping in installed templates, but I dont think it is any trouble given that it enables you to quickly integrate rdlc without internet and without downloading what you already have from Nuget every time!

Convert hours:minutes:seconds into total minutes in excel

The only way is to use a formula or to format cells. The method i will use will be the following: Add another column next to these values. Then use the following formula:

=HOUR(A1)*60+MINUTE(A1)+SECOND(A1)/60

enter image description here

CodeIgniter: "Unable to load the requested class"

In Windows, capitalization in paths doesn't matter. In Linux it does.

When you autoload, use "Foo" not "foo".

I believe that will do the trick.

I think it works when you take it out of autoloading because codeigniter is smart enough to figure out the capitalization in the path and classes are case independent in php.

HTTP response header content disposition for attachments

Try the Content-Disposition header

Content-Disposition: attachment; filename=<file name.ext> 

android set button background programmatically

I have found that Android Studio gives me a warning that getColor() is deprecated when trying to do this:

Button11.setBackgroundColor(getResources().getColor(R.color.red))

So I found doing the method below to be the simple, up-to-date solution:

Button11.setBackgroundColor(ContextCompat.getColor(context, R.color.red))

You want to avoid hard-coding in the color argument, as it is considered bad code style.

Edit: After using setBackgroundColor() with my own button, I saw that the internal button padding expanded. I couldn't find any way of changing it back to having both height and width set to "wrap_content". Maybe its a bug.

Source: https://stackoverflow.com/a/32202256/6030520

What does the servlet <load-on-startup> value signify

It is simple as you don't even expect.

If the value is positive it loaded when the container starts

If the value is not positive than the servelet is loaded when the request is made.

Count the Number of Tables in a SQL Server Database

USE MyDatabase
SELECT Count(*)
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE';

to get table counts

SELECT COUNT(*)
FROM information_schema.tables
WHERE table_schema = 'dbName';

this also works

USE databasename;
SHOW TABLES;
SELECT FOUND_ROWS();

How to check if a column exists in a datatable

You can use operator Contains,

private void ContainColumn(string columnName, DataTable table)
{
    DataColumnCollection columns = table.Columns;        
    if (columns.Contains(columnName))
    {
       ....
    }
}

MSDN - DataColumnCollection.Contains()

Change the mouse pointer using JavaScript

Look at this page: http://www.webcodingtech.com/javascript/change-cursor.php. Looks like you can access cursor off of style. This page shows it being done with the entire page, but I'm sure a child element would work just as well.

document.body.style.cursor = 'wait';

posting hidden value

You should never assume register_global_variables is turned on. Even if it is, it's deprecated and you should never use it that way.

Refer directly to the $_POST or $_GET variables. Most likely your form is POSTing, so you'd want your code to look something along the lines of this:

<input type="hidden" name="date" id="hiddenField" value="<?php echo $_POST['date'] ?>" />

If this doesn't work for you right away, print out the $_POST or $_GET variable on the page that would have the hidden form field and determine exactly what you want and refer to it.

echo "<pre>";
print_r($_POST);
echo "</pre>";

Set background image in CSS using jquery

You have to remove the semicolon in the css rule string:

$(this).parent().css("background", "url(/images/r-srchbg_white.png) no-repeat");

Is calling destructor manually always a sign of bad design?

There are cases when they are necessary:

In code I work on I use explicit destructor call in allocators, I have implementation of simple allocator that uses placement new to return memory blocks to stl containers. In destroy I have:

  void destroy (pointer p) {
    // destroy objects by calling their destructor
    p->~T();
  }

while in construct:

  void construct (pointer p, const T& value) {
    // initialize memory with placement new
    #undef new
    ::new((PVOID)p) T(value);
  }

there is also allocation being done in allocate() and memory deallocation in deallocate(), using platform specific alloc and dealloc mechanisms. This allocator was used to bypass doug lea malloc and use directly for example LocalAlloc on windows.

Got a NumberFormatException while trying to parse a text file for objects

I changed Scanner fin = new Scanner(file); to Scanner fin = new Scanner(new File(file)); and it works perfectly now. I didn't think the difference mattered but there you go.

How to count duplicate rows in pandas dataframe?

If you like to count duplicates on particular column(s):

len(df['one'])-len(df['one'].drop_duplicates())

If you want to count duplicates on entire dataframe:

len(df)-len(df.drop_duplicates())

Or simply you can use DataFrame.duplicated(subset=None, keep='first'):

df.duplicated(subset='one', keep='first').sum()

where

subset : column label or sequence of labels(by default use all of the columns)

keep : {‘first’, ‘last’, False}, default ‘first’

  • first : Mark duplicates as True except for the first occurrence.
  • last : Mark duplicates as True except for the last occurrence.
  • False : Mark all duplicates as True.

Fetch: reject promise and catch the error if status is not OK?

For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable

Solution 1: Not throwing an error, handle the error ourselves

  async _fetch(request) {
    const fetchResult = await fetch(request); //Making the req
    const result = await fetchResult.json(); // parsing the response

    if (fetchResult.ok) {
      return result; // return success object
    }


    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    const error = new Error();
    error.info = responseError;

    return (error);
  }

Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:

  const userSaved = await apiCall(data); // calling fetch
  if (userSaved instanceof Error) {
    debug.log('Failed saving user', userSaved); // handle error

    return;
  }
  debug.log('Success saving user', userSaved); // handle success

Solution 2: Throwing an error, using try/catch

async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    let error = new Error();
    error = { ...error, ...responseError };
    throw (error);
  }

Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:

  try {
    const userSaved = await apiCall(data); // calling fetch
    debug.log('Success saving user', userSaved); // handle success
  } catch (e) {
    debug.log('Failed saving user', userSaved); // handle error
  }

Solution 3: Using customer error

  async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    throw new ClassError(result.message, result.data, result.code);
  }

And:

class ClassError extends Error {

  constructor(message = 'Something went wrong', data = '', code = '') {
    super();
    this.message = message;
    this.data = data;
    this.code = code;
  }

}

Hope it helped.

Calling Web API from MVC controller

Why don't you simply move the code you have in the ApiController calls - DocumentsController to a class that you can call from both your HomeController and DocumentController. Pull this out into a class you call from both controllers. This stuff in your question:

// All code to find the files are here and is working perfectly...

It doesn't make sense to call a API Controller from another controller on the same website.

This will also simplify the code when you come back to it in the future you will have one common class for finding the files and doing that logic there...

ComboBox SelectedItem vs SelectedValue

I suspect that the SelectedItem property of the ComboBox does not change until the control has been validated (which occurs when the control loses focus), whereas the SelectedValue property changes whenever the user selects an item.

Here is a reference to the focus events that occur on controls:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx

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

I had the same problem in VS2017, Xamarin.Forms project. Reading this bug link:

https://bugzilla.xamarin.com/show_bug.cgi?id=33181#c53

To solve the problem in this case: Right-click on [xaml-file-name].xaml, choose Properties, then change the Build Action to Content then back to Embedded resource.

What is the difference between Nexus and Maven?

This has a good general description: https://gephi.wordpress.com/tag/maven/

Let me make a few statement that can put the difference in focus:

  1. We migrated our code base from Ant to Maven

  2. All 3rd party librairies have been uploaded to Nexus. Maven is using Nexus as a source for libraries.

  3. Basic functionalities of a repository manager like Sonatype are:

    • Managing project dependencies,
    • Artifacts & Metadata,
    • Proxying external repositories
    • and deployment of packaged binaries and JARs to share those artifacts with other developers and end-users.

Python, how to read bytes from file and save it?

Use the open function to open the file. The open function returns a file object, which you can use the read and write to files:

file_input = open('input.txt') #opens a file in reading mode
file_output = open('output.txt') #opens a file in writing mode

data = file_input.read(1024) #read 1024 bytes from the input file
file_output.write(data) #write the data to the output file

How can foreign key constraints be temporarily disabled using T-SQL?

To disable the constraint you have ALTER the table using NOCHECK

ALTER TABLE [TABLE_NAME] NOCHECK CONSTRAINT [ALL|CONSTRAINT_NAME]

To enable you to have to use double CHECK:

ALTER TABLE [TABLE_NAME] WITH CHECK CHECK CONSTRAINT [ALL|CONSTRAINT_NAME]
  • Pay attention to the double CHECK CHECK when enabling.
  • ALL means for all constraints in the table.

Once completed, if you need to check the status, use this script to list the constraint status. Will be very helpfull:

    SELECT (CASE 
        WHEN OBJECTPROPERTY(CONSTID, 'CNSTISDISABLED') = 0 THEN 'ENABLED'
        ELSE 'DISABLED'
        END) AS STATUS,
        OBJECT_NAME(CONSTID) AS CONSTRAINT_NAME,
        OBJECT_NAME(FKEYID) AS TABLE_NAME,
        COL_NAME(FKEYID, FKEY) AS COLUMN_NAME,
        OBJECT_NAME(RKEYID) AS REFERENCED_TABLE_NAME,
        COL_NAME(RKEYID, RKEY) AS REFERENCED_COLUMN_NAME
   FROM SYSFOREIGNKEYS
ORDER BY TABLE_NAME, CONSTRAINT_NAME,REFERENCED_TABLE_NAME, KEYNO 

static constructors in C++? I need to initialize private static objects

When trying to compile and use class Elsewhere (from Earwicker's answer) I get:

error LNK2001: unresolved external symbol "private: static class StaticStuff Elsewhere::staticStuff" (?staticStuff@Elsewhere@@0VStaticStuff@@A)

It seems is not possible to initialize static attributes of non-integer types without putting some code outside the class definition (CPP).

To make that compile you can use "a static method with a static local variable inside" instead. Something like this:

class Elsewhere
{
public:
    static StaticStuff& GetStaticStuff()
    {
        static StaticStuff staticStuff; // constructor runs once, single instance
        return staticStuff;
    }
};

And you may also pass arguments to the constructor or initialize it with specific values, it is very flexible, powerfull and easy to implement... the only thing is you have a static method containing a static variable, not a static attribute... syntaxis changes a bit, but still useful. Hope this is useful for someone,

Hugo González Castro.

Public free web services for testing soap client

There is a bunch on here:

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

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

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

Angular2 router (@angular/router), how to set default route?

I just faced the same issue, I managed to make it work on my machine, however the change I did is not the same way it is mentioned in the documentation so it could be an issue of angular version routing module, mine is Angular 7

It only worked when I changed the lazy module main route entry path with same path as configured at the app-routes.ts

routes = [{path:'', redirectTo: '\home\default', pathMatch: 'full'},
           {path: '', 
           children: [{
             path:'home',
             loadChildren :'lazy module path'      
           }]

         }];

 routes configured at HomeModule
 const routes = [{path: 'home', redirectTo: 'default', pathMatch: 'full'},
             {path: 'default', component: MyPageComponent},
            ]

 instead of 
 const routes = [{path: '', redirectTo: 'default', pathMatch: 'full'},
                   {path: 'default', component: MyPageComponent},
                ]

Jupyter Notebook not saving: '_xsrf' argument missing from post

In my case, this problem was solved by clicking 'Kernel' (shown on the top of notebooks) and then 'Reconnect'.

Note Added: In some versions of Jupyter, there is not 'Reconnect'.

How to select element using XPATH syntax on Selenium for Python?

Check this blog by Martin Thoma. I tested the below code on MacOS Mojave and it worked as specified.

> def get_browser():
>     """Get the browser (a "driver")."""
>     # find the path with 'which chromedriver'
>     path_to_chromedriver = ('/home/moose/GitHub/algorithms/scraping/'
>                             'venv/bin/chromedriver')
>     download_dir = "/home/moose/selenium-download/"
>     print("Is directory: {}".format(os.path.isdir(download_dir)))
> 
>     from selenium.webdriver.chrome.options import Options
>     chrome_options = Options()
>     chrome_options.add_experimental_option('prefs', {
>         "plugins.plugins_list": [{"enabled": False,
>                                   "name": "Chrome PDF Viewer"}],
>         "download": {
>             "prompt_for_download": False,
>             "default_directory": download_dir
>         }
>     })
> 
>     browser = webdriver.Chrome(path_to_chromedriver,
>                                chrome_options=chrome_options)
>     return browser

How to Ignore "Duplicate Key" error in T-SQL (SQL Server)

Expanding on your comment to SquareCog's reply, you could do:

INSERT INTO X VALUES(Y,Z)    WHERE Y  NOT IN (SELECT Y FROM X)
INSERT INTO X2 VALUES(Y2,Z2) WHERE Y2 NOT IN (SELECT Y FROM X2)
INSERT INTO X3 VALUES(Y3,Z3) WHERE Y3 NOT IN (SELECT Y FROM X3)

Here, I assume that column Y is present in all three tables. Note that performance will be poor if the tables are not indexed on Y.

Oh yeah, Y has a unique constraint on it--so they're indexed, and this should perform optimally.

Returning multiple values from a C++ function

Personally, I generally dislike return parameters for a number of reasons:

  • it is not always obvious in the invocation which parameters are ins and which are outs
  • you generally have to create a local variable to catch the result, while return values can be used inline (which may or may not be a good idea, but at least you have the option)
  • it seems cleaner to me to have an "in door" and an "out door" to a function -- all the inputs go in here, all the outputs come out there
  • I like to keep my argument lists as short as possible

I also have some reservations about the pair/tuple technique. Mainly, there is often no natural order to the return values. How is the reader of the code to know whether result.first is the quotient or the remainder? And the implementer could change the order, which would break existing code. This is especially insidious if the values are the same type so that no compiler error or warning would be generated. Actually, these arguments apply to return parameters as well.

Here's another code example, this one a bit less trivial:

pair<double,double> calculateResultingVelocity(double windSpeed, double windAzimuth,
                                               double planeAirspeed, double planeCourse);

pair<double,double> result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.first << endl;
cout << result.second << endl;

Does this print groundspeed and course, or course and groundspeed? It's not obvious.

Compare to this:

struct Velocity {
    double speed;
    double azimuth;
};
Velocity calculateResultingVelocity(double windSpeed, double windAzimuth,
                                    double planeAirspeed, double planeCourse);

Velocity result = calculateResultingVelocity(25, 320, 280, 90);
cout << result.speed << endl;
cout << result.azimuth << endl;

I think this is clearer.

So I think my first choice in general is the struct technique. The pair/tuple idea is likely a great solution in certain cases. I'd like to avoid the return parameters when possible.

Java RegEx meta character (.) and ordinary dot?

I am doing some basic array in JGrasp and found that with an accessor method for a char[][] array to use ('.') to place a single dot.

How to determine the installed webpack version

If using Angular CLI v7+, the webpack version is printed in the output of ng version:

-> ng version

     _                      _                 ____ _     ___
    / \   _ __   __ _ _   _| | __ _ _ __     / ___| |   |_ _|
   / ? \ | '_ \ / _` | | | | |/ _` | '__|   | |   | |    | |
  / ___ \| | | | (_| | |_| | | (_| | |      | |___| |___ | |
 /_/   \_\_| |_|\__, |\__,_|_|\__,_|_|       \____|_____|___|
                |___/


Angular CLI: 7.0.6
Node: 11.0.0
OS: darwin x64
Angular: 7.1.0
... animations, cdk, common, compiler, compiler-cli, core, forms
... http, language-service, material, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.10.6
@angular-devkit/build-angular     0.10.6
@angular-devkit/build-optimizer   0.10.6
@angular-devkit/build-webpack     0.10.6
@angular-devkit/core              7.0.6
@angular-devkit/schematics        7.0.6
@angular/cli                      7.0.6
@ngtools/webpack                  7.0.6
@schematics/angular               7.0.6
@schematics/update                0.10.6
rxjs                              6.3.3
typescript                        3.1.6
webpack                           4.19.1

Validate phone number with JavaScript

realy simple

"9001234567".match(/^\d{10}$/g)

Position: absolute and parent height?

If I understand what you're trying to do correctly, then I don't think this is possible with CSS while keeping the children absolutely positioned.

Absolutely positioned elements are completely removed from the document flow, and thus their dimensions cannot alter the dimensions of their parents.

If you really had to achieve this affect while keeping the children as position: absolute, you could do so with JavaScript by finding the height of the absolutely positioned children after they have rendered, and using that to set the height of the parent.

Alternatively, just use float: left/float:right and margins to get the same positioning effect while keeping the children in the document flow, you can then use overflow: hidden on the parent (or any other clearfix technique) to cause its height to expand to that of its children.

article {
    position: relative;
    overflow: hidden;
}

.one {
    position: relative;
    float: left;
    margin-top: 10px;
    margin-left: 10px;
    background: red;
    width: 30px;
    height: 30px;
}

.two {
    position: relative;
    float: right;
    margin-top: 10px;
    margin-right: 10px;
    background: blue;
    width: 30px;
    height: 30px;
}

What is setBounds and how do I use it?

Actually, a Swing component does have multiple dimensions, as:

  • current size - setSize() and setBounds() sets this
  • minimum size - setMinimumSize() sets this
  • preferred size - setPerferredSize() sets this
  • maximum size - setMaximumSize() sets this.

SetBounds is a shortcut for setting current size plus location of the widget if you don't use any layout manager.

If you use a layout manager, it is the responsibility of the layout manager to lay out your components, taking into account the preferred size you set, and ensuring that the comonent never gets smaller than its minimumSize or bigger than its maximumSize.

In this case, the layoutManager will call setSize (or setBounds), and you can not really control the position or dimension of the component.

The whole point of using a layout manager is to have a platform and window-size independent way of laying out your components automatically, therefore you don't expect to call setSize from your code.

(Personal comment: There are buggy layout managers, I personally hate all of them and rolled my own, which offers the flexibility of MigLayout without the learning curve.)

How do I run a bat file in the background from another bat file?

Actually, the following works fine for me and creates new windows:

test.cmd:

@echo off
start test2.cmd
start test3.cmd
echo Foo
pause

test2.cmd

@echo off
echo Test 2
pause
exit

test3.cmd

@echo off
echo Test 3
pause
exit

Combine that with parameters to start, such as /min, as Moshe pointed out if you don't want the new windows to spawn in front of you.

How to uninstall an older PHP version from centOS7

yum -y remove php* to remove all php packages then you can install the 5.6 ones.

Get property value from string using reflection

Here is my solution. It works also with COM objects and allows to access collection/array items from COM objects.

public static object GetPropValue(this object obj, string name)
{
    foreach (string part in name.Split('.'))
    {
        if (obj == null) { return null; }

        Type type = obj.GetType();
        if (type.Name == "__ComObject")
        {
            if (part.Contains('['))
            {
                string partWithoundIndex = part;
                int index = ParseIndexFromPropertyName(ref partWithoundIndex);
                obj = Versioned.CallByName(obj, partWithoundIndex, CallType.Get, index);
            }
            else
            {
                obj = Versioned.CallByName(obj, part, CallType.Get);
            }
        }
        else
        {
            PropertyInfo info = type.GetProperty(part);
            if (info == null) { return null; }
            obj = info.GetValue(obj, null);
        }
    }
    return obj;
}

private static int ParseIndexFromPropertyName(ref string name)
{
    int index = -1;
    int s = name.IndexOf('[') + 1;
    int e = name.IndexOf(']');
    if (e < s)
    {
        throw new ArgumentException();
    }
    string tmp = name.Substring(s, e - s);
    index = Convert.ToInt32(tmp);
    name = name.Substring(0, s - 1);
    return index;
}

How to navigate to a section of a page

Use an call thru section, it works

<div id="content">
     <section id="home">
               ...
     </section>

Call the above the thru

 <a href="#home">page1</a>

Scrolling needs jquery paste this.. on above to ending body closing tag..

<script>
  $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
          if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
              var target = $(this.hash);
              target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
              if (target.length) {
                  $('html,body').animate({
                      scrollTop: target.offset().top
                  }, 1000);
                  return false;
              }
          }
      });
  });
</script>

How to block users from closing a window in Javascript?

Take a look at onBeforeUnload.

It wont force someone to stay but it will prompt them asking them whether they really want to leave, which is probably the best cross browser solution you can manage. (Similar to this site if you attempt to leave mid-answer.)

<script language="JavaScript">
    window.onbeforeunload = confirmExit;
    function confirmExit() {
        return "You have attempted to leave this page. Are you sure?";
    }
</script>

Edit: Most browsers no longer allow a custom message for onbeforeunload.

See this bug report from the 18th of February, 2016.

onbeforeunload dialogs are used for two things on the Modern Web:
1. Preventing users from inadvertently losing data.
2. Scamming users.

In an attempt to restrict their use for the latter while not stopping the former, we are going to not display the string provided by the webpage. Instead, we are going to use a generic string.

Firefox already does this[...]

Quick way to retrieve user information Active Directory

You can call UserPrincipal.FindByIdentity inside System.DirectoryServices.AccountManagement:

using System.DirectoryServices.AccountManagement;

using (var pc = new PrincipalContext(ContextType.Domain, "MyDomainName"))
{
    var user = UserPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "MyDomainName\\" + userName);
}

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

MySQL root access from all hosts

MariaDB running on Raspbian - the file containing bind-address is hard to pinpoint. MariaDB have some not-very-helpful-info on the subject.

I used

# sudo grep -R bind-address /etc 

to locate where the damn thing is.

I also had to set the privileges and hosts in the mysql like everyone above pointed out.

And also had some fun time opening the 3306 port for remote connections to my Raspberry Pi - finally used iptables-persistent.

All works great now.

Suppress InsecureRequestWarning: Unverified HTTPS request is being made in Python2.6

Why not using pyvmomi original function SmartConnectNoSSL. They added this function on June 14, 2016 and named it ConnectNoSSL, one day after they changed the name to SmartConnectNoSSL, use that instead of by passing the warning with unnecessary lines of code in your project?

Provides a standard method for connecting to a specified server without SSL verification. Useful when connecting to servers with self-signed certificates or when you wish to ignore SSL altogether

service_instance = connect.SmartConnectNoSSL(host=args.ip,
                                             user=args.user,
                                             pwd=args.password)

How do I make XAML DataGridColumns fill the entire DataGrid?

Set the columns Width property to be a proportional width such as *

Initialize/reset struct to zero/null

debugger screenshot

Take a surprise from gnu11!

typedef struct {
    uint8_t messType;
    uint8_t ax;  //axis
    uint32_t position;
    uint32_t velocity;
}TgotoData;

TgotoData tmpData = { 0 };

nothing is zero.

Adding sheets to end of workbook in Excel (normal method not working?)

mainWB.Sheets.Add(After:=Sheets(Sheets.Count)).Name = new_sheet_name 

should probably be

mainWB.Sheets.Add(After:=mainWB.Sheets(mainWB.Sheets.Count)).Name = new_sheet_name 

how to fetch data from database in Hibernate

Hibernate has its own sql features that is known as hibernate query language. for retriving data from database using hibernate.

String sql_query = "from employee"//user table name which is in database.
Query query = session.createQuery(sql_query);
//for fetch we need iterator
Iterator it=query.iterator();
while(it.hasNext())
    {
         s=(employee) it.next();
System.out.println("Id :"+s.getId()+"FirstName"+s.getFirstName+"LastName"+s.getLastName);

   }

for fetch we need Iterator for that define and import package.

Is generator.next() visible in Python 3?

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.

invalid use of non-static data member

You try to access private member of one class from another. The fact that bar-class is declared within foo-class means that bar in visible only inside foo class, but that is still other class.

And what is p->param?

Actually, it isn't clear what do you want to do

Entity Framework 6 GUID as primary key: Cannot insert the value NULL into column 'Id', table 'FileStore'; column does not allow nulls

Entity Framework – Use a Guid as the primary key

Using a Guid as your tables primary key, when using Entity Framework, requires a little more effort than when using a integer. The setup process is straightforward, after you’ve read/been shown how to do it.

The process is slightly different for the Code First and Database First approaches. This post discusses both techniques.

enter image description here

Code First

Using a Guid as the primary key when taking the code first approach is simple. When creating your entity, add the DatabaseGenerated attribute to your primary key property, as shown below;

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

Entity framework will create the column as you would expect, with a primary key and uniqueidentifier data type.

codefirst-defaultvalue

Also notice, very important, that the default value on the column has been set to (newsequentialid()). This generates a new sequential (continuous) Guid for each row. If you were so inclined, you could change this to newid()), which would result in a completely random Guid for each new row. This will be cleared each time your database gets dropped and re-created, so this works better when taking the Database First approach.

Database First

The database first approach follows a similar line to the code first approach, but you’ll have to manually edit your model to make it work.

Ensure that you edit the primary key column and add the (newsequentialid()) or (newid()) function as the default value before doing anything.

enter image description here

Next, open you EDMX diagram, select the appropriate property and open the properties window. Ensure that StoreGeneratedPattern is set to identity.

databasefirst-model

No need to give your entity an ID in your code, that will be populated for you automatically after the entity has been commited to the database;

using (ApplicationDbContext context = new ApplicationDbContext())
{
    var person = new Person
                     {
                         FirstName = "Random",
                         LastName = "Person";
                     };

    context.People.Add(person);
    context.SaveChanges();
    Console.WriteLine(person.Id);
}

Important Note: Your Guid field MUST be a primary key, or this does not work. Entity Framework will give you a rather cryptic error message!

Summary

Guid (Globally Unique Identifiers) can easily be used as primary keys in Entity Framework. A little extra effort is required to do this, depending on which approach you are taking. When using the code first approach, add the DatabaseGenerated attribute to your key field. When taking the Database First approach, explicitly set the StoredGeneratedPattern to Identity on your model.

[1]: https://i.stack.imgur.com/IxGdd.png
[2]: https://i.stack.imgur.com/Qssea.png

How to check if a line has one of the strings in a list?

This still loops through the cartesian product of the two lists, but it does it one line:

>>> lines1 = ['soup', 'butter', 'venison']
>>> lines2 = ['prune', 'rye', 'turkey']
>>> search_strings = ['a', 'b', 'c']
>>> any(s in l for l in lines1 for s in search_strings)
True
>>> any(s in l for l in lines2 for s in search_strings)
False

This also have the advantage that any short-circuits, and so the looping stops as soon as a match is found. Also, this only finds the first occurrence of a string from search_strings in linesX. If you want to find multiple occurrences you could do something like this:

>>> lines3 = ['corn', 'butter', 'apples']
>>> [(s, l) for l in lines3 for s in search_strings if s in l]
[('c', 'corn'), ('b', 'butter'), ('a', 'apples')]

If you feel like coding something more complex, it seems the Aho-Corasick algorithm can test for the presence of multiple substrings in a given input string. (Thanks to Niklas B. for pointing that out.) I still think it would result in quadratic performance for your use-case since you'll still have to call it multiple times to search multiple lines. However, it would beat the above (cubic, on average) algorithm.

OpenCV get pixel channel value from Mat image

The pixels array is stored in the "data" attribute of cv::Mat. Let's suppose that we have a Mat matrix where each pixel has 3 bytes (CV_8UC3).

For this example, let's draw a RED pixel at position 100x50.

Mat foo;
int x=100, y=50;

Solution 1:

Create a macro function that obtains the pixel from the array.

#define PIXEL(frame, W, x, y) (frame+(y)*3*(W)+(x)*3)
//...
unsigned char * p = PIXEL(foo.data, foo.rols, x, y);
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Solution 2:

Get's the pixel using the method ptr.

unsigned char * p = foo.ptr(y, x); // Y first, X after
p[0] = 0;   // B
p[1] = 0;   // G
p[2] = 255; // R

Jenkins, specifying JAVA_HOME

i saw into Eclipse > Preferences>installed JREs > JRE Definition i found the directory of java_home so it's /Library/Java/JavaVirtualMachines/jdk1.7.0_17.jdk/Contents/Home

How to negate a method reference predicate

I'm planning to static import the following to allow for the method reference to be used inline:

public static <T> Predicate<T> not(Predicate<T> t) {
    return t.negate();
}

e.g.

Stream<String> s = ...;
long nonEmptyStrings = s.filter(not(String::isEmpty)).count();

Update: Starting from Java-11, the JDK offers a similar solution built-in as well.

Best C/C++ Network Library

Aggregated List of Libraries

How to jQuery clone() and change id?

This works too

_x000D_
_x000D_
 var i = 1;_x000D_
 $('button').click(function() {_x000D_
     $('#red').clone().appendTo('#test').prop('id', 'red' + i);_x000D_
     i++; _x000D_
 });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>_x000D_
<div id="test">_x000D_
  <button>Clone</button>_x000D_
  <div class="red" id="red">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<style>_x000D_
  .red {_x000D_
    width:20px;_x000D_
    height:20px;_x000D_
    background-color: red;_x000D_
    margin: 10px;_x000D_
  }_x000D_
</style>
_x000D_
_x000D_
_x000D_

origin 'http://localhost:4200' has been blocked by CORS policy in Angular7

1: Create a class WebMvcConfig and extend it as shown from the WebMvcConfiguration and override addCorsMappings method.

2: Most importantly don't forget to make it @Configuration annotation because it should be loaded with Main Spring class to allow Cross-Origin.

  @Configuration
    public class WebMvcCofig implements WebMvcConfigurer{
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/*")
                    .allowedOrigins("*")
                    .allowedMethods("*")
                    .allowedHeaders("*")
                    .allowCredentials(true);
        }
    }

Correlation heatmap

  1. Use the 'jet' colormap for a transition between blue and red.
  2. Use pcolor() with the vmin, vmax parameters.

It is detailed in this answer: https://stackoverflow.com/a/3376734/21974

Open file dialog and select a file using WPF controls and C#

var ofd = new Microsoft.Win32.OpenFileDialog() {Filter = "JPEG Files (*.jpeg)|*.jpeg|PNG Files (*.png)|*.png|JPG Files (*.jpg)|*.jpg|GIF Files (*.gif)|*.gif"}; 
var result = ofd.ShowDialog();
if (result == false) return;
textBox1.Text = ofd.FileName;

How do you count the lines of code in a Visual Studio solution?

In Visual Studio 2015 go to the Analyze Menu and select "Calculate Code Metrics".

Call a Vue.js component method from outside the component

For Vue2 this applies:

var bus = new Vue()

// in component A's method

bus.$emit('id-selected', 1)

// in component B's created hook

bus.$on('id-selected', function (id) {

  // ...
})

See here for the Vue docs. And here is more detail on how to set up this event bus exactly.

If you'd like more info on when to use properties, events and/ or centralized state management see this article.

See below comment of Thomas regarding Vue 3.

getting file size in javascript

If it's not a local application powered by JavaScript with full access permissions, you can't get the size of any file just from the path name. Web pages running javascript do not have access to the local filesystem for security reasons.

You can use a graceful degrading file uploader like SWFUpload if you want to show a progress bar. HTML5 also has the File API, but that is not widely supported just yet. If a user selects the file for an input[type=file] element, you can get details about the file from the files collection:

alert(myInp.files[0].size);

Switching between GCC and Clang/LLVM using CMake

You definitely don't need to use the various different llvm-ar etc programs:

SET (CMAKE_AR      "/usr/bin/llvm-ar")
SET (CMAKE_LINKER  "/usr/bin/llvm-ld")
SET (CMAKE_NM      "/usr/bin/llvm-nm")
SET (CMAKE_OBJDUMP "/usr/bin/llvm-objdump")
SET (CMAKE_RANLIB  "/usr/bin/llvm-ranlib")

These are made to work on the llvm internal format and as such aren't useful to the build of your application.

As a note -O4 will invoke LTO on your program which you may not want (it will increase compile time greatly) and clang defaults to c99 mode so that flag isn't necessarily needed either.

java.net.ConnectException :connection timed out: connect?

Exception : java.net.ConnectException

This means your request didn't getting response from server in stipulated time. And their are some reasons for this exception:

  • Too many requests overloading the server
  • Request packet loss because of wrong network configuration or line overload
  • Sometimes firewall consume request packet before sever getting
  • Also depends on thread connection pool configuration and current status of connection pool
  • Response packet lost during transition

Merge DLL into EXE?

Download

ILMerge

Call

ilmerge /target:winexe /out:c:\output.exe c:\input.exe C:\input.dll

Android Button click go to another xml page

Write below code in your MainActivity.java file instead of your code.

public class MainActivity extends Activity implements OnClickListener {

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

        Button mBtn1 = (Button) findViewById(R.id.mBtn1);
        mBtn1.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        Log.i("clicks","You Clicked B1");
        Intent i=new Intent(MainActivity.this, MainActivity2.class);
        startActivity(i);
    }
}

And Declare MainActivity2 into your Androidmanifest.xml file using below code.

<activity
    android:name=".MainActivity2"
    android:label="@string/title_activity_main">
</activity>

Add animated Gif image in Iphone UIImageView

If you must load the gif image from URL, you can always embed the gif in an image tag in a UIWebView.

How large is a DWORD with 32- and 64-bit code?

No ... on all Windows platforms DWORD is 32 bits. LONGLONG or LONG64 is used for 64 bit types.

Using jquery to get all checked checkboxes with a certain class name

$('input.yourClass:checkbox:checked').each(function () {
    var sThisVal = $(this).val();
});

This would get all checkboxes of the class name "yourClass". I like this example since it uses the jQuery selector checked instead of doing a conditional check. Personally I would also use an array to store the value, then use them as needed, like:

var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
    arr.push($(this).val());
});

Where does the @Transactional annotation belong?

I prefer to use @Transactional on services layer at method level.

How do I get logs/details of ansible-playbook module executions?

If you pass the -v flag to ansible-playbook on the command line, you'll see the stdout and stderr for each task executed:

$ ansible-playbook -v playbook.yaml

Ansible also has built-in support for logging. Add the following lines to your ansible configuration file:

[defaults] 
log_path=/path/to/logfile

Ansible will look in several places for the config file:

  • ansible.cfg in the current directory where you ran ansible-playbook
  • ~/.ansible.cfg
  • /etc/ansible/ansible.cfg

alert a variable value

Note, while the above answers are correct, if you want, you can do something like:

alert("The variable named x1 has value:  " + x1);

How to check if an object implements an interface?

In general for AnInterface and anInstance of any class:

AnInterface.class.isAssignableFrom(anInstance.getClass());

How to get index of an item in java.util.Set

One solution (though not very pretty) is to use Apache common List/Set mutation

import org.apache.commons.collections.list.SetUniqueList;

final List<Long> vertexes=SetUniqueList.setUniqueList(new LinkedList<>());

it is a list without duplicates

https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/index.html?org/apache/commons/collections/list/SetUniqueList.html

Use jQuery to change a second select list based on the first select list option

All of these methods are great. I have found another simple resource that is a great example of creating a dynamic form using "onchange" with AJAX.

http://www.w3schools.com/php/php_ajax_database.asp

I simply modified the text table output to anther select dropdown populated based on the selection of the first drop down. For my application a user will select a state then the second dropdown will be populated with the cities for the selected state. Much like the JSON example above but with php and mysql.

What does Java option -Xmx stand for?

C:\java -X

    -Xmixed           mixed mode execution (default)
    -Xint             interpreted mode execution only
    -Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
    -Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
    -Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
    -Xnoclassgc       disable class garbage collection
    -Xincgc           enable incremental garbage collection
    -Xloggc:<file>    log GC status to a file with time stamps
    -Xbatch           disable background compilation
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    -Xss<size>        set java thread stack size
    -Xprof            output cpu profiling data
    -Xfuture          enable strictest checks, anticipating future default
    -Xrs              reduce use of OS signals by Java/VM (see documentation)
    -Xcheck:jni       perform additional checks for JNI functions
    -Xshare:off       do not attempt to use shared class data
    -Xshare:auto      use shared class data if possible (default)
    -Xshare:on        require using shared class data, otherwise fail.

The -X options are non-standard and subject to change without notice.

How can I remove a style added with .css() function?

Just using:

$('.tag-class').removeAttr('style');

or

$('#tag-id').removeAttr('style');

How to fast get Hardware-ID in C#?

Here is a DLL that shows:
* Hard drive ID (unique hardware serial number written in drive's IDE electronic chip)
* Partition ID (volume serial number)
* CPU ID (unique hardware ID)
* CPU vendor
* CPU running speed
* CPU theoretic speed
* Memory Load ( Total memory used in percentage (%) )
* Total Physical ( Total physical memory in bytes )
* Avail Physical ( Physical memory left in bytes )
* Total PageFile ( Total page file in bytes )
* Available PageFile( Page file left in bytes )
* Total Virtual( Total virtual memory in bytes )
* Available Virtual ( Virtual memory left in bytes )
* Bios unique identification numberBiosDate
* Bios unique identification numberBiosVersion
* Bios unique identification numberBiosProductID
* Bios unique identification numberBiosVideo

(text grabbed from original web site)
It works with C#.

Git Push ERROR: Repository not found

you have to generate ssh key and add it in your github account in settings go to your project where you clone inside that run these command.-

1-ssh-keygen -t rsa -b 4096 -C "[email protected]"

after the command you will get some options path and name can be leave empty and you can put password.

2-eval $(ssh-agent -s) .

3-ssh-add ~/.ssh/id_rsa

after this command you have to put same password that you created in 1st command

and after that you can check your default home directory or whatever directory it is showing on the terminal .pub file open and copy the key and past in github settings new ssh

Eclipse: Set maximum line length for auto formatting?

In preferences Java -> Code Style -> Formatter, edit the profile. Under the Line Wrapping tab is the primary option for line width (Maximum line width:). In the Comments tab you have a separate option Maximum line width for comments:, which will also need to be changed to affect comment wrapping.

You will need to make your own profile to make these changes in if you using one of the [Built-in] ones. Just click "New..." on the formatter preferences page.

Formatting a number with leading zeros in PHP

You can always abuse type juggling:

function zpad(int $value, int $pad): string {
    return substr(1, $value + 10 ** $pad);
}

This wont work as expected if either 10 ** pad > INT_MAX or value >= 10 * pad.

How to delete history of last 10 commands in shell?

I use this script to delete last 10 commands in history:

pos=$HISTCMD; start=$(( $pos-11 )); end=$(( $pos-1 )); for i in $(eval echo "{${start}..${end}}"); do history -d $start; done

It uses $HISTCMD environment var to get the history index and uses that to delete last 10 entries in history.

How can I add a custom HTTP header to ajax request with js or jQuery?

There are several solutions depending on what you need...

If you want to add a custom header (or set of headers) to an individual request then just add the headers property:

// Request with custom header
$.ajax({
    url: 'foo/bar',
    headers: { 'x-my-custom-header': 'some value' }
});

If you want to add a default header (or set of headers) to every request then use $.ajaxSetup():

$.ajaxSetup({
    headers: { 'x-my-custom-header': 'some value' }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Overwrites the default header with a new header
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

If you want to add a header (or set of headers) to every request then use the beforeSend hook with $.ajaxSetup():

$.ajaxSetup({
    beforeSend: function(xhr) {
        xhr.setRequestHeader('x-my-custom-header', 'some value');
    }
});

// Sends your custom header
$.ajax({ url: 'foo/bar' });

// Sends both custom headers
$.ajax({ url: 'foo/bar', headers: { 'x-some-other-header': 'some value' } });

Edit (more info): One thing to be aware of is that with ajaxSetup you can only define one set of default headers and you can only define one beforeSend. If you call ajaxSetup multiple times, only the last set of headers will be sent and only the last before-send callback will execute.

How do I rename a column in a database table using SQL?

Unfortunately, for a database independent solution, you will need to know everything about the column. If it is used in other tables as a foreign key, they will need to be modified as well.

ALTER TABLE MyTable ADD MyNewColumn OLD_COLUMN_TYPE;
UPDATE MyTable SET MyNewColumn = MyOldColumn;
-- add all necessary triggers and constraints to the new column...
-- update all foreign key usages to point to the new column...
ALTER TABLE MyTable DROP COLUMN MyOldColumn;

For the very simplest of cases (no constraints, triggers, indexes or keys), it will take the above 3 lines. For anything more complicated it can get very messy as you fill in the missing parts.

However, as mentioned above, there are simpler database specific methods if you know which database you need to modify ahead of time.

warning: incompatible implicit declaration of built-in function ‘xyz’

I met these warnings on mempcpy function. Man page says this function is a GNU extension and synopsis shows:

#define _GNU_SOURCE
#include <string.h>

When #define is added to my source before the #include, declarations for the GNU extensions are made visible and warnings disappear.

Jackson Vs. Gson

Jackson and Gson are the most complete Java JSON packages regarding actual data binding support; many other packages only provide primitive Map/List (or equivalent tree model) binding. Both have complete support for generic types, as well, as enough configurability for many common use cases.

Since I am more familiar with Jackson, here are some aspects where I think Jackson has more complete support than Gson (apologies if I miss a Gson feature):

  • Extensive annotation support; including full inheritance, and advanced "mix-in" annotations (associate annotations with a class for cases where you can not directly add them)
  • Streaming (incremental) reading, writing, for ultra-high performance (or memory-limited) use cases; can mix with data binding (bind sub-trees) -- EDIT: latest versions of Gson also include streaming reader
  • Tree model (DOM-like access); can convert between various models (tree <-> java object <-> stream)
  • Can use any constructors (or static factory methods), not just default constructor
  • Field and getter/setter access (earlier gson versions only used fields, this may have changed)
  • Out-of-box JAX-RS support
  • Interoperability: can also use JAXB annotations, has support/work-arounds for common packages (joda, ibatis, cglib), JVM languages (groovy, clojure, scala)
  • Ability to force static (declared) type handling for output
  • Support for deserializing polymorphic types (Jackson 1.5) -- can serialize AND deserialize things like List correctly (with additional type information)
  • Integrated support for binary content (base64 to/from JSON Strings)

Optional query string parameters in ASP.NET Web API

It's possible to pass multiple parameters as a single model as vijay suggested. This works for GET when you use the FromUri parameter attribute. This tells WebAPI to fill the model from the query parameters.

The result is a cleaner controller action with just a single parameter. For more information see: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

public class BooksController : ApiController
  {
    // GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
    public string GetFindBooks([FromUri]BookQuery query)
    {
      // ...
    }
  }

  public class BookQuery
  {
    public string Author { get; set; }
    public string Title { get; set; }
    public string ISBN { get; set; }
    public string SomethingElse { get; set; }
    public DateTime? Date { get; set; }
  }

It even supports multiple parameters, as long as the properties don't conflict.

// GET /api/books?author=tolk&title=lord&isbn=91&somethingelse=ABC&date=1970-01-01
public string GetFindBooks([FromUri]BookQuery query, [FromUri]Paging paging)
{
  // ...
}

public class Paging
{
  public string Sort { get; set; }
  public int Skip { get; set; }
  public int Take { get; set; }
}

Update:
In order to ensure the values are optional make sure to use reference types or nullables (ex. int?) for the models properties.

How to set up a PostgreSQL database in Django

This is one of the very good and step by step process to set up PostgreSQL in ubuntu server. I have tried it with Ubuntu 16.04 and its working.

https://www.digitalocean.com/community/tutorials/how-to-use-postgresql-with-your-django-application-on-ubuntu-14-04

How can I connect to MySQL in Python 3 on Windows?

Untested, but there are some binaries available at:

Unofficial Windows Binaries

Java - Using Accessor and Mutator methods

Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.

So first you need to set up a class with some variables to get/set:

public class IDCard
{
    private String mName;
    private String mFileName;
    private int mID;

}

But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:

IDCard test = new IDCard();

So - let's set up a default constructor, this is the method being called when you "instantiate" a class.

public IDCard()
{
    mName = "";
    mFileName = "";
    mID = -1;
}

But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:

public IDCard(String name, int ID, String filename)
{
    mName = name;
    mID = ID;
    mFileName = filename;
}

Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:

public String getName()
{
    return mName;
}

public void setName( String name )
{
    mName = name;
}

Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie. Good luck.

How to add 10 days to current time in Rails

Some other options, just for reference

-10.days.ago
# Available in Rails 4
DateTime.now.days_ago(-10)

Just list out all options I know:

[1] Time.now + 10.days
[2] 10.days.from_now
[3] -10.days.ago
[4] DateTime.now.days_ago(-10)
[5] Date.today + 10

So now, what is the difference between them if we care about the timezone:

  • [1, 4] With system timezone
  • [2, 3] With config timezone of your Rails app
  • [5] Date only no time included in result

Deleting Objects in JavaScript

IE 5 through 8 has a bug where using delete on properties of a host object (Window, Global, DOM etc) throws TypeError "object does not support this action".

var el=document.getElementById("anElementId");
el.foo = {bar:"baz"};
try{
    delete el.foo;
}catch(){
    //alert("Curses, drats and double double damn!");
    el.foo=undefined; // a work around
}

Later if you need to check where the property has a meaning full value use el.foo !== undefined because "foo" in el will always return true in IE.

If you really need the property to really disappear...

function hostProxy(host){
    if(host===null || host===undefined) return host;
    if(!"_hostProxy" in host){
       host._hostproxy={_host:host,prototype:host};
    }
    return host._hostproxy;
}
var el=hostProxy(document.getElementById("anElementId"));
el.foo = {bar:"baz"};

delete el.foo; // removing property if a non-host object

if your need to use the host object with host api...

el.parent.removeChild(el._host);

Execute a shell function with timeout

You can create a function which would allow you to do the same as timeout but also for other functions:

function run_cmd { 
    cmd="$1"; timeout="$2";
    grep -qP '^\d+$' <<< $timeout || timeout=10

    ( 
        eval "$cmd" &
        child=$!
        trap -- "" SIGTERM 
        (       
                sleep $timeout
                kill $child 2> /dev/null 
        ) &     
        wait $child
    )
}

And could run as below:

run_cmd "echoFooBar" 10

Note: The solution came from one of my questions: Elegant solution to implement timeout for bash commands and functions

Getting mouse position in c#

If you need to get current position in form's area(got experimentally), try:

Console.WriteLine("Current mouse position in form's area is " + 
    (Control.MousePosition.X - this.Location.X - 8).ToString() +
    "x" + 
    (Control.MousePosition.Y - this.Location.Y - 30).ToString()
);

Although, 8 and 30 integers were found by experimenting.

Would be awesome if someone could explain why exactly these numbers ^.


Also, there's another variant(considering code is in Form's CodeBehind):

Point cp = PointToClient(Cursor.Position); // Getting a cursor's position according form's area
Console.WriteLine("Cursor position: X = " + cp.X + ", Y = " + cp.Y);

Difference between number and integer datatype in oracle dictionary views

the best explanation i've found is this:

What is the difference betwen INTEGER and NUMBER? When should we use NUMBER and when should we use INTEGER? I just wanted to update my comments here...

NUMBER always stores as we entered. Scale is -84 to 127. But INTEGER rounds to whole number. The scale for INTEGER is 0. INTEGER is equivalent to NUMBER(38,0). It means, INTEGER is constrained number. The decimal place will be rounded. But NUMBER is not constrained.

  • INTEGER(12.2) => 12
  • INTEGER(12.5) => 13
  • INTEGER(12.9) => 13
  • INTEGER(12.4) => 12
  • NUMBER(12.2) => 12.2
  • NUMBER(12.5) => 12.5
  • NUMBER(12.9) => 12.9
  • NUMBER(12.4) => 12.4

INTEGER is always slower then NUMBER. Since integer is a number with added constraint. It takes additional CPU cycles to enforce the constraint. I never watched any difference, but there might be a difference when we load several millions of records on the INTEGER column. If we need to ensure that the input is whole numbers, then INTEGER is best option to go. Otherwise, we can stick with NUMBER data type.

Here is the link

Scrollview vertical and horizontal in android

My solution based on Mahdi Hijazi answer, but without any custom views:

Layout:

<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/scrollHorizontal"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <ScrollView 
        android:id="@+id/scrollVertical"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" >

        <WateverViewYouWant/>

    </ScrollView>
</HorizontalScrollView>

Code (onCreate/onCreateView):

    final HorizontalScrollView hScroll = (HorizontalScrollView) value.findViewById(R.id.scrollHorizontal);
    final ScrollView vScroll = (ScrollView) value.findViewById(R.id.scrollVertical);
    vScroll.setOnTouchListener(new View.OnTouchListener() { //inner scroll listener         
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return false;
        }
    });
    hScroll.setOnTouchListener(new View.OnTouchListener() { //outer scroll listener         
        private float mx, my, curX, curY;
        private boolean started = false;

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            curX = event.getX();
            curY = event.getY();
            int dx = (int) (mx - curX);
            int dy = (int) (my - curY);
            switch (event.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    if (started) {
                        vScroll.scrollBy(0, dy);
                        hScroll.scrollBy(dx, 0);
                    } else {
                        started = true;
                    }
                    mx = curX;
                    my = curY;
                    break;
                case MotionEvent.ACTION_UP: 
                    vScroll.scrollBy(0, dy);
                    hScroll.scrollBy(dx, 0);
                    started = false;
                    break;
            }
            return true;
        }
    });

You can change the order of the scrollviews. Just change their order in layout and in the code. And obviously instead of WateverViewYouWant you put the layout/views you want to scroll both directions.

Use PPK file in Mac Terminal to connect to remote connection over SSH

Convert PPK to OpenSSh

OS X: Install Homebrew, then run

brew install putty

Place your keys in some directory, e.g. your home folder. Now convert the PPK keys to SSH keypairs:cache search

To generate the private key:

cd ~

puttygen id_dsa.ppk -O private-openssh -o id_dsa

and to generate the public key:

puttygen id_dsa.ppk -O public-openssh -o id_dsa.pub

Move these keys to ~/.ssh and make sure the permissions are set to private for your private key:

mkdir -p ~/.ssh
mv -i ~/id_dsa* ~/.ssh
chmod 600 ~/.ssh/id_dsa
chmod 666 ~/.ssh/id_dsa.pub

connect with ssh server

ssh -i ~/.ssh/id_dsa username@servername

Port Forwarding to connect mysql remote server

ssh -i ~/.ssh/id_dsa -L 9001:127.0.0.1:3306 username@serverName

Closure in Java 7

Java Closures are going to be a part of J2SE 8 and is set to be released by the end of 2012.

Java 8's closures support include the concept of Lambda Expressions, Method Reference, Constructor Reference and the Default Methods.

For more information and working examples for this please visit: http://amitrp.blogspot.in/2012/08/at-first-sight-with-closures-in-java.html

(.text+0x20): undefined reference to `main' and undefined reference to function

This rule

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o producer.o consumer.o AddRemove.o

is wrong. It says to create a file named producer.o (with -o producer.o), but you want to create a file named main. Please excuse the shouting, but ALWAYS USE $@ TO REFERENCE THE TARGET:

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ producer.o consumer.o AddRemove.o

As Shahbaz rightly points out, the gmake professionals would also use $^ which expands to all the prerequisites in the rule. In general, if you find yourself repeating a string or name, you're doing it wrong and should use a variable, whether one of the built-ins or one you create.

main: producer.o consumer.o AddRemove.o
   $(COMPILER) -pthread $(CCFLAGS) -o $@ $^

Fullscreen Activity in Android?

AndroidManifest.xml

<activity ...
          android:theme="@style/FullScreenTheme"
    >
</activity>

I. Your main app the theme is Theme.AppCompat.Light.DarkActionBar

For hide ActionBar / StatusBar
style.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    ...
</style>

<style name="FullScreenTheme" parent="AppTheme">
    <!--this property will help hide the ActionBar-->
    <item name="windowNoTitle">true</item>
    <!--currently, I don't know why we need this property since use windowNoTitle only already help hide actionbar. I use it because it is used inside Theme.AppCompat.Light.NoActionBar (you can check Theme.AppCompat.Light.NoActionBar code). I think there are some missing case that I don't know-->
    <item name="windowActionBar">false</item>
    <!--this property is used for hiding StatusBar-->
    <item name="android:windowFullscreen">true</item>
</style>

To hide the system navigation bar

public class MainActivity extends AppCompatActivity {

    protected void onCreate(Bundle savedInstanceState) {
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        setContentView(R.layout.activity_main)
        ...
    }
 }

II. Your main app theme is Theme.AppCompat.Light.NoActionBar

For hide ActionBar / StatusBar
style.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    ...
</style>

<style name="FullScreenTheme" parent="AppTheme">
    <!--don't need any config for hide ActionBar because our apptheme is NoActionBar-->
    <!--this property is use for hide StatusBar-->
    <item name="android:windowFullscreen">true</item> // 
</style>

To hide the system navigation bar

Similar like Theme.AppCompat.Light.DarkActionBar.

Demo

Bash script plugin for Eclipse?

There exists now a dedicated bash script plugin called "Bash editor". It's available at eclipse market place:

Bash editor log

You can find it at https://marketplace.eclipse.org/content/bash-editor or by marketplace client when searching for "bash".

The plugin does also provide a debugger. Inisde official Bash Editor YouTube playlist you can find some tutorials about usage etc.

PS: I am the author of the mentioned plugin.

Border around each cell in a range

Here's another way

Sub testborder()

    Dim rRng As Range

    Set rRng = Sheet1.Range("B2:D5")

    'Clear existing
    rRng.Borders.LineStyle = xlNone

    'Apply new borders
    rRng.BorderAround xlContinuous
    rRng.Borders(xlInsideHorizontal).LineStyle = xlContinuous
    rRng.Borders(xlInsideVertical).LineStyle = xlContinuous

End Sub

Android Google Maps API V2 Zoom to Current Location

Here's how to do it inside ViewModel and FusedLocationProviderClient, code in Kotlin

locationClient.lastLocation.addOnSuccessListener { location: Location? ->
            location?.let {
                val position = CameraPosition.Builder()
                        .target(LatLng(it.latitude, it.longitude))
                        .zoom(15.0f)
                        .build()
                map.animateCamera(CameraUpdateFactory.newCameraPosition(position))
            }
        }

Set UILabel line spacing

From Interface Builder:

enter image description here

Programmatically:

SWift 4

Using label extension

extension UILabel {

    func setLineSpacing(lineSpacing: CGFloat = 0.0, lineHeightMultiple: CGFloat = 0.0) {

        guard let labelText = self.text else { return }

        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = lineSpacing
        paragraphStyle.lineHeightMultiple = lineHeightMultiple

        let attributedString:NSMutableAttributedString
        if let labelattributedText = self.attributedText {
            attributedString = NSMutableAttributedString(attributedString: labelattributedText)
        } else {
            attributedString = NSMutableAttributedString(string: labelText)
        }

        // Line spacing attribute
        attributedString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attributedString.length))

        self.attributedText = attributedString
    }
}

Now call extension function

let label = UILabel()
let stringValue = "How to\ncontrol\nthe\nline spacing\nin UILabel"

// Pass value for any one argument - lineSpacing or lineHeightMultiple
label.setLineSpacing(lineSpacing: 2.0) .  // try values 1.0 to 5.0

// or try lineHeightMultiple
//label.setLineSpacing(lineHeightMultiple = 2.0) // try values 0.5 to 2.0


Or using label instance (Just copy & execute this code to see result)

let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40

// Line spacing attribute
attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: style, range: NSRange(location: 0, length: stringValue.characters.count))

// Character spacing attribute
attrString.addAttribute(NSAttributedStringKey.kern, value: 2, range: NSMakeRange(0, attrString.length))

label.attributedText = attrString

Swift 3

let label = UILabel()
let stringValue = "Set\nUILabel\nline\nspacing"
let attrString = NSMutableAttributedString(string: stringValue)
var style = NSMutableParagraphStyle()
style.lineSpacing = 24 // change line spacing between paragraph like 36 or 48
style.minimumLineHeight = 20 // change line spacing between each line like 30 or 40
attrString.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange(location: 0, length: stringValue.characters.count))
label.attributedText = attrString

How to write a Unit Test?

  1. Define the expected and desired output for a normal case, with correct input.

  2. Now, implement the test by declaring a class, name it anything (Usually something like TestAddingModule), and add the testAdd method to it (i.e. like the one below) :

    • Write a method, and above it add the @Test annotation.
    • In the method, run your binary sum and assertEquals(expectedVal,calculatedVal).
    • Test your method by running it (in Eclipse, right click, select Run as ? JUnit test).

      //for normal addition 
      @Test
      public void testAdd1Plus1() 
      {
          int x  = 1 ; int y = 1;
          assertEquals(2, myClass.add(x,y));
      }
      
  3. Add other cases as desired.

    • Test that your binary sum does not throw a unexpected exception if there is an integer overflow.
    • Test that your method handles Null inputs gracefully (example below).

      //if you are using 0 as default for null, make sure your class works in that case.
      @Test
      public void testAdd1Plus1() 
      {
          int y = 1;
          assertEquals(0, myClass.add(null,y));
      }
      

How do you add a scroll bar to a div?

<head>
<style>
div.scroll
{
background-color:#00FFFF;
width:40%;
height:200PX;
FLOAT: left;
margin-left: 5%;
padding: 1%;
overflow:scroll;
}


</style>
</head>

<body>



<div class="scroll">You can use the overflow property when you want to have better       control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better </div>


</body>
</html>

jQuery Set Selected Option Using Next

$('#my_sel').val($('#my_sel option:selected').next().val());
$('#my_sel').val($('#my_sel option:selected').prev().val());

The type or namespace name could not be found

The compiled dll should have public Class.

Printing 1 to 1000 without loop or conditionals

I feel this answer will be very simple and easy to understand.

int print1000(int num=1)
{
    printf("%d\n", num);

    // it will check first the num is less than 1000. 
    // If yes then call recursive function to print
    return num<1000 && print1000(++num); 
}

int main()
{
    print1000();
    return 0;        
}

jQuery AJAX Call to PHP Script with JSON Return

Your datatype is wrong, change datatype for dataType.

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

For a Node.js app, in the server.js file before registering all of my own routes, I put the code below. It sets the headers for all responses. It also ends the response gracefully if it is a pre-flight "OPTIONS" call and immediately sends the pre-flight response back to the client without "nexting" (is that a word?) down through the actual business logic routes. Here is my server.js file. Relevant sections highlighted for Stackoverflow use.

// server.js

// ==================
// BASE SETUP

// import the packages we need
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var morgan     = require('morgan');
var jwt        = require('jsonwebtoken'); // used to create, sign, and verify tokens

// ====================================================
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// Logger
app.use(morgan('dev'));

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

//Set CORS header and intercept "OPTIONS" preflight call from AngularJS
var allowCrossDomain = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    if (req.method === "OPTIONS") 
        res.send(200);
    else 
        next();
}

// -------------------------------------------------------------
// STACKOVERFLOW -- END OF THIS SECTION, ONE MORE SECTION BELOW
// -------------------------------------------------------------


// =================================================
// ROUTES FOR OUR API

var route1 = require("./routes/route1");
var route2 = require("./routes/route2");
var error404 = require("./routes/error404");


// ======================================================
// REGISTER OUR ROUTES with app

// -------------------------------------------------------------
// STACKOVERFLOW -- PAY ATTENTION TO THIS NEXT SECTION !!!!!
// -------------------------------------------------------------

app.use(allowCrossDomain);

// -------------------------------------------------------------
//  STACKOVERFLOW -- OK THAT IS THE LAST THING.
// -------------------------------------------------------------

app.use("/api/v1/route1/", route1);
app.use("/api/v1/route2/", route2);
app.use('/', error404);

// =================
// START THE SERVER

var port = process.env.PORT || 8080;        // set our port
app.listen(port);
console.log('API Active on port ' + port);

How to execute INSERT statement using JdbcTemplate class from Spring Framework

If you are planning to use JdbcTemplate in multiple locations, it would be a good idea to create a Spring Bean for it.

Using Java Config it would be:

@Configuration
public class DBConfig {

   @Bean
   public DataSource dataSource() {
      //create a data source
   }

   @Bean
   public JdbcTemplate jdbcTemplate() {
      return new JdbcTemplate(dataSource());
   }

   @Bean
   public TransactionManager transactionManager() {
      return new DataSourceTransactionManager(dataSource());
   }

}

Then a repository that uses that JdbcTemplate could be:

@Repository
public class JdbcSomeRepository implements SomeRepository {

   private final JdbcTemplate jdbcTemplate ;

   @Autowired
   public JdbcSomeRepository(JdbcTemplate jdbcTemplate) {
      this.jdbcTemplate = jdbcTemplate;
   } 

   @Override
   @Transactional 
   public int someUpdate(SomeType someValue, SomeOtherType someOtherValue) {
      return jdbcTemplate.update("INSERT INTO SomeTable(column1, column2) VALUES(?,?)", someValue, someOtherValue)
   }
}

The update method from JdbcTemplate that I have used can be found here.

How to apply multiple transforms in CSS?

Transform Rotate and Translate in single line css:-How?

_x000D_
_x000D_
div.className{_x000D_
    transform : rotate(270deg) translate(-50%, 0);    _x000D_
    -webkit-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -moz-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -ms-transform: rotate(270deg) translate(-50%, -50%);    _x000D_
    -o-transform: rotate(270deg) translate(-50%, -50%); _x000D_
    float:left;_x000D_
    position:absolute;_x000D_
    top:50%;_x000D_
    left:50%;_x000D_
    }
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body>_x000D_
<div class="className">_x000D_
  <span style="font-size:50px">A</span>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to define relative paths in Visual Studio Project?

If I get you right, you need ..\..\src

What's the difference between size_t and int in C++?

It's because size_t can be anything other than an int (maybe a struct). The idea is that it decouples it's job from the underlying type.

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

For whatever reason $('.panel-collapse').collapse({'toggle': true, 'parent': '#accordion'}); only seems to work the first time and it only works to expand the collapsible. (I tried to start with a expanded collapsible and it wouldn't collapse.)

It could just be something that runs once the first time you initialize collapse with those parameters.

You will have more luck using the show and hide methods.

Here is an example:

$(function() {

  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('.collapse-init').on('click', function() {
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      $('.panel-collapse').collapse('show');
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
  });

});

http://bootply.com/98201

Update

Granted KyleMit seems to have a way better handle on this then me. I'm impressed with his answer and understanding.

I don't understand what's going on or why the show seemed to be toggling in some places.

But After messing around for a while.. Finally came with the following solution:

$(function() {
  var transition = false;
  var $active = true;

  $('.panel-title > a').click(function(e) {
    e.preventDefault();
  });

  $('#accordion').on('show.bs.collapse',function(){
    if($active){
        $('#accordion .in').collapse('hide');
    }
  });

  $('#accordion').on('hidden.bs.collapse',function(){
    if(transition){
        transition = false;
        $('.panel-collapse').collapse('show');
    }
  });

  $('.collapse-init').on('click', function() {
    $('.collapse-init').prop('disabled','true');
    if(!$active) {
      $active = true;
      $('.panel-title > a').attr('data-toggle', 'collapse');
      $('.panel-collapse').collapse('hide');
      $(this).html('Click to disable accordion behavior');
    } else {
      $active = false;
      if($('.panel-collapse.in').length){
        transition = true;
        $('.panel-collapse.in').collapse('hide');       
      }
      else{
        $('.panel-collapse').collapse('show');
      }
      $('.panel-title > a').attr('data-toggle','');
      $(this).html('Click to enable accordion behavior');
    }
    setTimeout(function(){
        $('.collapse-init').prop('disabled','');
    },800);
  });
});

http://bootply.com/98239

jQuery click not working for dynamically created items

Try something like

$("#container").on('click', 'someLinkSelector', function(){ $("#container").html( <new html with new spans> ) });

You basically need to attach your events from a non-dynamic part of the DOM so it can watch for dynamically-created elements.

Create space at the beginning of a UITextField

Simple swift 3 solution - add code to viewDidLoad:

let indentView = UIView(frame: CGRect(x: 0, y: 0, width: 10, height: 20))
textField.leftView = indentView
textField.leftViewMode = .always

No need for ridiculously long code

key_load_public: invalid format

There is a simple solution if you can install and use puttygen tool. Below are the steps. You should have the passphrase of the private key.

step 1: Download latest puttygen and open puttygen

step 2: Load your existing private key file, see below image

Load an existing private key

step 3: Enter passphrase for key if asked and hit ok

enter paasphrase

step 4: as shown in the below image select "conversion" menu tab and select "Export OpenSSH key"

save OpenSSH file

Save new private key file at preferred location and use accordingly.

PHP unable to load php_curl.dll extension

Add your php folder path to the System PATH and everything should work fine. It will also fix some other extensions that are broken.

How to split comma separated string using JavaScript?

var array = string.split(',')

and good morning, too, since I have to type 30 chars ...

Setting environment variable in react-native?

Step 1: Create separate component like this Component name : pagebase.js
Step 2: Inside this use code this

    export const BASE_URL = "http://192.168.10.10:4848/";
    export const API_KEY = 'key_token';

Step 3: Use it in any component, for using it first import this component then use it. Import it and use it:

        import * as base from "./pagebase";

        base.BASE_URL
        base.API_KEY

Adjusting HttpWebRequest Connection Timeout in C#

I believe that the problem is that the WebRequest measures the time only after the request is actually made. If you submit multiple requests to the same address then the ServicePointManager will throttle your requests and only actually submit as many concurrent connections as the value of the corresponding ServicePoint.ConnectionLimit which by default gets the value from ServicePointManager.DefaultConnectionLimit. Application CLR host sets this to 2, ASP host to 10. So if you have a multithreaded application that submits multiple requests to the same host only two are actually placed on the wire, the rest are queued up.

I have not researched this to a conclusive evidence whether this is what really happens, but on a similar project I had things were horrible until I removed the ServicePoint limitation.

Another factor to consider is the DNS lookup time. Again, is my belief not backed by hard evidence, but I think the WebRequest does not count the DNS lookup time against the request timeout. DNS lookup time can show up as very big time factor on some deployments.

And yes, you must code your app around the WebRequest.BeginGetRequestStream (for POSTs with content) and WebRequest.BeginGetResponse (for GETs and POSTSs). Synchronous calls will not scale (I won't enter into details why, but that I do have hard evidence for). Anyway, the ServicePoint issue is orthogonal to this: the queueing behavior happens with async calls too.

How do you set the EditText keyboard to only consist of numbers on Android?

I think you used somehow the right way to show the number only on the keyboard so better try the given line with xml in your edit text and it will work perfectly so here the code is-

  android:inputType="number"

In case any doubt you can again ask to me i'll try to completely sort out your problem. Thanks

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

Removing an element from an Array (Java)

Some more pre-conditions are needed for the ones written by Bill K and dadinn

Object[] newArray = new Object[src.length - 1];
if (i > 0){
    System.arraycopy(src, 0, newArray, 0, i);
}

if (newArray.length > i){
    System.arraycopy(src, i + 1, newArray, i, newArray.length - i);
}

return newArray;

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

What about this :


    public static bool SafeInvoke( this Control control, MethodInvoker method )
    {
        if( control != null && ! control.IsDisposed && control.IsHandleCreated && control.FindForm().IsHandleCreated )
        {
            if( control.InvokeRequired )
            {
                control.Invoke( method );
            }
            else
            {
                method();
            }
            return true;
        }
        else return false;
    }

How to check if a string contains only numbers?

You could use a regular expression like this

If Regex.IsMatch(number, "^[0-9 ]+$") Then

...

End If

How do I show the value of a #define at compile-time?

Instead of #error, try redefining the macro, just before it is being used. Compilation will fail and compiler will provide the current value it thinks applies to the macro.

#define BOOST_VERSION blah

How do you add UI inside cells in a google spreadsheet using app script?

Status 2018:

There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.


This being said, there are some things that you can indeed do:

You can...

You can place images within cells using IMAGE(URL), but they cannot be linked to Apps Script functions.

You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))

You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.

Xcode couldn't find any provisioning profiles matching

I opened XCode -> Preferences -> Accounts and clicked on Download certificate. That fixed my problem

How to read a file in Groovy into a string?

String fileContents = new File('/path/to/file').text

If you need to specify the character encoding, use the following instead:

String fileContents = new File('/path/to/file').getText('UTF-8')

Sort list in C# with LINQ

I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:

var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();

How to find whether MySQL is installed in Red Hat?

to ckeck the status use the below command, which worked on debian....

/etc/init.d/mysql status

to start my sql server use the below command

/etc/init.d/mysql start

to stop the server use the below command

/etc/init.d/mysql stop

Use of symbols '@', '&', '=' and '>' in custom directive's scope binding: AngularJS

The AngularJS documentation on directives is pretty well written for what the symbols mean.

To be clear, you cannot just have

scope: '@'

in a directive definition. You must have properties for which those bindings apply, as in:

scope: {
    myProperty: '@'
}

I strongly suggest you read the documentation and the tutorials on the site. There is much more information you need to know about isolated scopes and other topics.

Here is a direct quote from the above-linked page, regarding the values of scope:

The scope property can be true, an object or a falsy value:

  • falsy: No scope will be created for the directive. The directive will use its parent's scope.

  • true: A new child scope that prototypically inherits from its parent will be created for the directive's element. If multiple directives on the same element request a new scope, only one new scope is created. The new scope rule does not apply for the root of the template since the root of the template always gets a new scope.

  • {...} (an object hash): A new "isolate" scope is created for the directive's element. The 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent scope. This is useful when creating reusable components, which should not accidentally read or modify data in the parent scope.

Retrieved 2017-02-13 from https://code.angularjs.org/1.4.11/docs/api/ng/service/$compile#-scope-, licensed as CC-by-SA 3.0

Get the current fragment object

you can check which fragment is currently loaded by this

        supportFragmentManager.addOnBackStackChangedListener {
        val myFragment = supportFragmentManager.fragments.last()

        if (null != myFragment && myFragment is HomeFragment) {
            //HomeFragment is visible or currently loaded
        } else {
            //your code
        }
    }

fe_sendauth: no password supplied

Do not use passwords. Use peer authentication instead:

postgres://myuser@%2Fvar%2Frun%2Fpostgresql/mydb

Write a file in external storage in Android

You should read the documentation on storing stuff externally on Android. There's a multitude of problems that could exist with your current code, and I think going over the documentation might help you iron them out.