Programs & Examples On #Megamenu

Megamenu is a dropdown plugin used similar to the traditional style dropdown menu built to enhance usability and address some drawbacks such as the amount of clicking, navigating and researching is reduced.

Bootstrap 3 - set height of modal window according to screen size

Pure CSS solution, using calc

.modal-body {
    max-height: calc(100vh - 200px);
    overflow-y: auto;
}

200px may be adjusted in accordance to height of header & footer

How to remove specific object from ArrayList in Java?

or you can use java 8 lambda

test.removeIf(i -> i==2);

it will simply remove all object that meet the condition

forward declaration of a struct in C?

Try this

#include <stdio.h>

struct context;

struct funcptrs{
  void (*func0)(struct context *ctx);
  void (*func1)(void);
};

struct context{
    struct funcptrs fps;
}; 

void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }

void getContext(struct context *con){
    con->fps.func0 = func0;  
    con->fps.func1 = func1;  
}

int main(int argc, char *argv[]){
 struct context c;
   c.fps.func0 = func0;
   c.fps.func1 = func1;
   getContext(&c);
   c.fps.func0(&c);
   getchar();
   return 0;
}

Location of sqlite database on the device

If you name your db as a file without giving a path then most common way to get its folder is like:

final File dbFile = new File(getFilesDir().getParent()+"/databases/"+DBAdapter.DATABASE_NAME);

where DBAdapter.DATABASE_NAME is just a String like "mydatabase.db".
Context.getFilesDir() returns path for app's files like: /data/data/<your.app.packagename>/files/ thats why you need to .getParent()+"/databases/", to remove "files" and add "databases" instead.
BTW Eclipse will warn you about hardcoded "data/data/" string but not in this case.

Remove/ truncate leading zeros by javascript/jquery

You can use a regular expression that matches zeroes at the beginning of the string:

s = s.replace(/^0+/, '');

Reading from file using read() function

I am reading some data from a file using read. Here I am reading data in a 2d char pointer but the method is the same for the 1d also. Just read character by character and do not worry about the exceptions because the condition in the while loop is handling the exceptions :D

  while ( (n = read(fd, buffer,1)) > 0 )
{   

if(buffer[0] == '\n')
{
  r++;
  char**tempData=(char**)malloc(sizeof(char*)*r);

  for(int a=0;a<r;a++)
  {
    tempData[a]=(char*)malloc(sizeof(char)*BUF_SIZE);
    memset(tempData[a],0,BUF_SIZE);
  }

  for(int a=0;a<r-1;a++)
  {
    strcpy(tempData[a],data[a]);
  }

   data=tempData;

   c=0;
}

else
{
  data[r-1][c]=buffer[0];
  c++;
  buffer[1]='\0';
}

   }

SQL Switch/Case in 'where' clause

OR operator can be alternative of case when in where condition

ALTER PROCEDURE [dbo].[RPT_340bClinicDrugInventorySummary]
    -- Add the parameters for the stored procedure here
     @ClinicId BIGINT = 0,
     @selecttype int,
     @selectedValue varchar (50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
SELECT
    drugstock_drugname.n_cur_bal,drugname.cdrugname,clinic.cclinicname

FROM drugstock_drugname
INNER JOIN drugname ON drugstock_drugname.drugnameid_FK = drugname.drugnameid_PK
INNER JOIN drugstock_drugndc ON drugname.drugnameid_PK = drugstock_drugndc.drugnameid_FK
INNER JOIN drugndc ON drugstock_drugndc.drugndcid_FK = drugndc.drugid_PK
LEFT JOIN clinic ON drugstock_drugname.clinicid_FK = clinic.clinicid_PK

WHERE   (@ClinicId = 0 AND 1 = 1)
    OR  (@ClinicId != 0 AND drugstock_drugname.clinicid_FK = @ClinicId)

    -- Alternative Case When You can use OR
    AND ((@selecttype = 1 AND 1 = 1)
    OR  (@selecttype = 2 AND drugname.drugnameid_PK = @selectedValue)
    OR  (@selecttype = 3 AND drugndc.drugid_PK = @selectedValue)
    OR  (@selecttype = 4 AND drugname.cdrugclass = 'C2')
    OR  (@selecttype = 5 AND LEFT(drugname.cdrugclass, 1) = 'C'))

ORDER BY clinic.cclinicname, drugname.cdrugname
END

Installing tensorflow with anaconda in windows

1) Update conda

Run the anaconda prompt as administrator

conda update -n base -c defaults conda

2) Create an environment for python new version say, 3.6

conda create --name py36 python=3.6

3) Activate the new environment

conda activate py36

4) Upgrade pip

pip install --upgrade pip

5) Install tensorflow

pip install https://testpypi.python.org/packages/db/d2/876b5eedda1f81d5b5734277a155fa0894d394a7f55efa9946a818ad1190/tensorflow-0.12.1-cp36-cp36m-win_amd64.whl

If it doesn't work

If you have problem with wheel at the environment location, or pywrap_tensorflow problem,

 pip install tensorflow --upgrade --force-reinstall

Defining static const integer members in class definition

Not just int's. But you can't define the value in the class declaration. If you have:

class classname
{
    public:
       static int const N;
}

in the .h file then you must have:

int const classname::N = 10;

in the .cpp file.

Removing all unused references from a project in Visual Studio projects

In VB2008, it works this way:

Project>Add References

Then click on the Recent tab where you can see list of references used recently. Locate the one you do not want and delet it. Then you close without adding anything.

What is the difference between a "function" and a "procedure"?

In general, a procedure is a sequence of instructions.
A function can be the same, but it usually returns a result.

Entity Framework Code First - two Foreign Keys from same table

It's also possible to specify the ForeignKey() attribute on the navigation property:

[ForeignKey("HomeTeamID")]
public virtual Team HomeTeam { get; set; }
[ForeignKey("GuestTeamID")]
public virtual Team GuestTeam { get; set; }

That way you don't need to add any code to the OnModelCreate method

How to scroll to an element?

You can use something like componentDidUpdate

componentDidUpdate() {
  var elem = testNode //your ref to the element say testNode in your case; 
  elem.scrollTop = elem.scrollHeight;
};

Why emulator is very slow in Android Studio?

Check this list:

  1. install Intel HAXM
  2. just use x86 AVD
  3. use small size screen

Python Prime number checker

# is digit prime? we will see (Coder: Chikak)

def is_prime(x): flag = False if x < 2: return False else: for count in range(2, x): if x % count == 0: flag = True break if flag == True: return False return True

Exploring Docker container's file system

another trick is to use the atomic tool to do something like:

mkdir -p /path/to/mnt && atomic mount IMAGE /path/to/mnt

The Docker image will be mounted to /path/to/mnt for you to inspect it.

JavaScript: set dropdown selected item based on option text

This works in latest Chrome, FireFox and Edge, but not IE11:

document.evaluate('//option[text()="Yahoo"]', document).iterateNext().selected = 'selected';

And if you want to ignore spaces around the title:

document.evaluate('//option[normalize-space(text())="Yahoo"]', document).iterateNext().selected = 'selected'

Python 3 string.join() equivalent?

str.join() works fine in Python 3, you just need to get the order of the arguments correct

>>> str.join('.', ('a', 'b', 'c'))
'a.b.c'

Return a string method in C#

You don't have to have a method for that. You could create a property like this instead:

class SalesPerson
{
    string firstName, lastName;
    public string FirstName { get { return firstName; } set { firstName = value; } }
    public string LastName { get { return lastName; } set { lastName = value; } }
    public string FullName { get { return this.FirstName + " " + this.LastName; } }
}

The class could even be shortened to:

class SalesPerson
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName { 
       get { return this.FirstName + " " + this.LastName; } 
    }
}

The property could then be accessed like any other property:

class Program
{
    static void Main(string[] args)
    {
        SalesPerson x = new SalesPerson("John", "Doe");
        Console.WriteLine(x.FullName); // Will print John Doe
    }
}

How to open standard Google Map application from my application?

You should create an Intent object with a geo-URI:

String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
context.startActivity(intent);

If you want to specify an address, you should use another form of geo-URI: geo:0,0?q=address.

reference : https://developer.android.com/guide/components/intents-common.html#Maps

angularjs - ng-repeat: access key and value from JSON array object

You've got an array of objects, so you'll need to use ng-repeat twice, like:

<ul ng-repeat="item in items">
  <li ng-repeat="(key, val) in item">
    {{key}}: {{val}}
  </li>
</ul>

Example: http://jsfiddle.net/Vwsej/

Edit:

Note that properties order in objects are not guaranteed.

<table>
    <tr>
        <th ng-repeat="(key, val) in items[0]">{{key}}</th>
    </tr>
    <tr ng-repeat="item in items">
        <td ng-repeat="(key, val) in item">{{val}}</td>
    </tr>
</table>

Example: http://jsfiddle.net/Vwsej/2/

Check if null Boolean is true results in exception

If you don't like extra null checks:

if (Boolean.TRUE.equals(value)) {...}

How to resolve ambiguous column names when retrieving results?

You can either use the numerical indices ($row[0]) or better, use AS in the MySQL:

SELECT *, user.id AS user_id FROM ...

Call int() function on every list element?

Another way to make it in Python 3:

numbers = [*map(int, numbers)]

Comprehensive beginner's virtualenv tutorial?

For setting up virtualenv on a clean Ubuntu installation, I found this zookeeper tutorial to be the best - you can ignore the parts about zookeper itself. The virtualenvwrapper documentation offers similar content, but it's a bit scarce on telling you what exactly to put into your .bashrc file.

how to use python2.7 pip instead of default pip

as noted here, this is what worked best for me:

sudo apt-get install python3 python3-pip python3-setuptools

sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 10

Sending command line arguments to npm script

You could also do that:

In package.json:

"scripts": {
    "cool": "./cool.js"
}

In cool.js:

 console.log({ myVar: process.env.npm_config_myVar });

In CLI:

npm --myVar=something run-script cool

Should output:

{ myVar: 'something' }

Update: Using npm 3.10.3, it appears that it lowercases the process.env.npm_config_ variables? I'm also using better-npm-run, so I'm not sure if this is vanilla default behavior or not, but this answer is working. Instead of process.env.npm_config_myVar, try process.env.npm_config_myvar

Convert String with Dot or Comma as decimal separator to number in JavaScript

All the other solutions require you to know the format in advance. I needed to detect(!) the format in every case and this is what I end up with.

function detectFloat(source) {
    let float = accounting.unformat(source);
    let posComma = source.indexOf(',');
    if (posComma > -1) {
        let posDot = source.indexOf('.');
        if (posDot > -1 && posComma > posDot) {
            let germanFloat = accounting.unformat(source, ',');
            if (Math.abs(germanFloat) > Math.abs(float)) {
                float = germanFloat;
            }
        } else {
            // source = source.replace(/,/g, '.');
            float = accounting.unformat(source, ',');
        }
    }
    return float;
}

This was tested with the following cases:

        const cases = {
            "0": 0,
            "10.12": 10.12,
            "222.20": 222.20,
            "-222.20": -222.20,
            "+222,20": 222.20,
            "-222,20": -222.20,
            "-2.222,20": -2222.20,
            "-11.111,20": -11111.20,
        };

Suggestions welcome.

javascript Unable to get property 'value' of undefined or null reference

The issue is how you're attempting to get the value. Things like...

if ( document.frm_new_user_request.u_isid.value == '' )

won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.

document.getElementById('[id goes here]').value;

will work. Note: JavaScript is case-sensitive

I would recommend using:

var variablename = document.getElementById('[id goes here]');

or

var variablename = document.getElementById('[id goes here]').value;

How to make a machine trust a self-signed Java application

I had the same problem, but i solved it from Java Control Panel-->Security-->SecurityLevel:MEDIUM. Just so, no Manage certificates, imports ,exports etc..

Read a file one line at a time in node.js?

If you want to read a file line by line and writing this in another:

var fs = require('fs');
var readline = require('readline');
var Stream = require('stream');

function readFileLineByLine(inputFile, outputFile) {

   var instream = fs.createReadStream(inputFile);
   var outstream = new Stream();
   outstream.readable = true;
   outstream.writable = true;

   var rl = readline.createInterface({
      input: instream,
      output: outstream,
      terminal: false
   });

   rl.on('line', function (line) {
        fs.appendFileSync(outputFile, line + '\n');
   });
};

Twitter Bootstrap onclick event on buttons-radio

Looking at the example HTML for radio buttons on the Twitter Bootstrap page (http://twitter.github.com/bootstrap/base-css.html#forms), you can see that each input has a unique ID attribute, i.e. optionsRadios1 and optionsRadios2.

The relevant HTML example snippet is included here for completeness:

<div class="controls">
  <label class="radio">
    <input type="radio" checked="" value="option1" id="optionsRadios1" name="optionsRadios">
    Option one is this and that—be sure to include why it's great
  </label>
  <label class="radio">
    <input type="radio" value="option2" id="optionsRadios2" name="optionsRadios">
    Option two can is something else and selecting it will deselect option one
  </label>
</div>

So you can use a jQuery click event, and then use the this reference to look at the id of the HTML element that was clicked.

$('.controls').find('input').bind('click',function(event){
  if($(this).attr('id')==='optionsRadios1'){
    alert($(this).attr('id'));
  } else {
    //... call some other function
  }
});

How to set an environment variable only for the duration of the script?

Just put

export HOME=/blah/whatever

at the point in the script where you want the change to happen. Since each process has its own set of environment variables, this definition will automatically cease to have any significance when the script terminates (and with it the instance of bash that has a changed environment).

Trim last character from a string

I took the path of writing an extension using the TrimEnd just because I was already using it inline and was happy with it... i.e.:

static class Extensions
{
        public static string RemoveLastChars(this String text, string suffix)
        {            
            char[] trailingChars = suffix.ToCharArray();

            if (suffix == null) return text;
            return text.TrimEnd(trailingChars);
        }

}

Make sure you include the namespace in your classes using the static class ;P and usage is:

string _ManagedLocationsOLAP = string.Empty;
_ManagedLocationsOLAP = _validManagedLocationIDs.RemoveLastChars(",");          

Javascript foreach loop on associative array object

_x000D_
_x000D_
var obj = {_x000D_
  no: ["no", 32],_x000D_
  nt: ["no", 32],_x000D_
  nf: ["no", 32, 90]_x000D_
};_x000D_
_x000D_
count = -1; // which must be static value_x000D_
for (i in obj) {_x000D_
  count++;_x000D_
  if (obj.hasOwnProperty(i)) {_x000D_
    console.log(obj[i][count])_x000D_
  };_x000D_
};
_x000D_
_x000D_
_x000D_

in this code i used brackets method for call values in array because it contained array , however briefly the idea which a variable i has a key of property and with a loop called both values of associate array

perfect Method , if you interested, press like

When to catch java.lang.Error?

Almost never. Errors are designed to be issues that applications generally can't do anything about. The only exception might be to handle the presentation of the error but even that might not go as planned depending on the error.

PHP Header redirect not working

Look at /Applications/MAMP/htdocs/testygubbins/OO/test/header.php line 15.

At that position, it makes some output. Fix it. :)

How to convert 1 to true or 0 to false upon model fetch

Use a double not:

!!1 = true;

!!0 = false;

obj.isChecked = !!parseInt(obj.isChecked);

HTTPS connection Python

Why haven't you tried httplib.HTTPSConnection? It doesn't do SSL validation but this isn't required to connect over https. Your code works fine with https connection:

>>> import httplib
>>> conn = httplib.HTTPSConnection("mail.google.com")
>>> conn.request("GET", "/")
>>> r1 = conn.getresponse()
>>> print r1.status, r1.reason
200 OK

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

For Android SDK, setEndpoint solves the problem, although it's been deprecated.

CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
                context, "identityPoolId", Regions.US_EAST_1);
AmazonS3 s3 = new AmazonS3Client(credentialsProvider);
s3.setEndpoint("s3.us-east-2.amazonaws.com");

In LINQ, select all values of property X where X != null

get one column in the distinct select and ignore null values:

 var items = db.table.Where(p => p.id!=null).GroupBy(p => p.id)
                                .Select(grp => grp.First().id)
                                .ToList();

How to insert an object in an ArrayList at a specific position

Here is the simple arraylist example for insertion at specific index

ArrayList<Integer> str=new ArrayList<Integer>();
    str.add(0);
    str.add(1);
    str.add(2);
    str.add(3); 
    //Result = [0, 1, 2, 3]
    str.add(1, 11);
    str.add(2, 12);
    //Result = [0, 11, 12, 1, 2, 3]

vi/vim editor, copy a block (not usual action)

It sounds like you want to place marks in the file.

mx places a mark named x under the cursor

y'x yanks everything between the cursor's current position and the line containing mark x.

You can use 'x to simply move the cursor to the line with your mark.

You can use `x (a back-tick) to move to the exact location of the mark.


One thing I do all the time is yank everything between the cursor and mark x into the clipboard.

You can do that like this:

"+y'x

NOTE: In some environments the clipboard buffer is represented by a * in stead of a +.


Similar questions with some good answers:

How can you search Google Programmatically Java API

Google TOS have been relaxed a bit in April 2014. Now it states:

"Don’t misuse our Services. For example, don’t interfere with our Services or try to access them using a method other than the interface and the instructions that we provide."

So the passage about "automated means" and scripts is gone now. It evidently still is not the desired (by google) way of accessing their services, but I think it is now formally open to interpretation of what exactly an "interface" is and whether it makes any difference as of how exactly returned HTML is processed (rendered or parsed). Anyhow, I have written a Java convenience library and it is up to you to decide whether to use it or not:

https://github.com/afedulov/google-web-search

ConnectivityManager getNetworkInfo(int) deprecated

This will work in Android 10 as well. It will return true if connected to the internet else return false.

private fun isOnline(): Boolean {
        val connectivityManager =
                getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val capabilities =
                connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        if (capabilities != null) {
            when {
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                    Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR")
                    return true
                }
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                    Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI")
                    return true
                }
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
                    Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET")
                    return true
                }
            }
        }
        return false
    }

Creating a Custom Event

Declare the class containing the event:

class MyClass {
    public event EventHandler MyEvent;

    public void Method() {
        OnEvent();
    }

    private void OnEvent() {
        if (MyEvent != null) {
            MyEvent(this, EventArgs.Empty);
        }
    }
}

Use it like this:

MyClass myObject = new MyClass();
myObject.MyEvent += new EventHandler(myObject_MyEvent);
myObject.Method();

Custom method names in ASP.NET Web API

Web Api by default expects URL in the form of api/{controller}/{id}, to override this default routing. you can set routing with any of below two ways.

First option:

Add below route registration in WebApiConfig.cs

config.Routes.MapHttpRoute(
    name: "CustomApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

Decorate your action method with HttpGet and parameters as below

[HttpGet]
public HttpResponseMessage ReadMyData(string param1,
                        string param2, string param3)

 {

// your code here

}

for calling above method url will be like below

http://localhost:[yourport]/api/MyData/ReadMyData?param1=value1&param2=value2&param3=value3

Second option Add route prefix to Controller class and Decorate your action method with HttpGet as below. In this case no need change any WebApiConfig.cs. It can have default routing.

[RoutePrefix("api/{controller}/{action}")]
public class MyDataController : ApiController
{

[HttpGet]
public HttpResponseMessage ReadMyData(string param1,
                        string param2, string param3)

{

// your code here

}

}

for calling above method url will be like below

http://localhost:[yourport]/api/MyData/ReadMyData?param1=value1&param2=value2&param3=value3

How can I use "e" (Euler's number) and power operation in python 2.7

You can use exp(x) function of math library, which is same as e^x. Hence you may write your code as:

import math
x.append(1 - math.exp( -0.5 * (value1*value2)**2))

I have modified the equation by replacing 1/2 as 0.5. Else for Python <2.7, we'll have to explicitly type cast the division value to float because Python round of the result of division of two int as integer. For example: 1/2 gives 0 in python 2.7 and below.

How to update Ruby with Homebrew?

I would use ruby-build with rbenv. The following lines install Ruby 3.0.0 and set it as your default Ruby version:

$ brew update
$ brew install ruby-build
$ brew install rbenv

$ rbenv install 3.0.0
$ rbenv global 3.0.0

Should each and every table have a primary key?

It is a good practice to have a PK on every table, but it's not a MUST. Most probably you will need a unique index, and/or a clustered index (which is PK or not) depending on your need.

Check out the Primary Keys and Clustered Indexes sections on Books Online (for SQL Server)

"PRIMARY KEY constraints identify the column or set of columns that have values that uniquely identify a row in a table. No two rows in a table can have the same primary key value. You cannot enter NULL for any column in a primary key. We recommend using a small, integer column as a primary key. Each table should have a primary key. A column or combination of columns that qualify as a primary key value is referred to as a candidate key."

But then check this out also: http://www.aisintl.com/case/primary_and_foreign_key.html

Gradle task - pass arguments to Java application

You can find the solution in Problems passing system properties and parameters when running Java class via Gradle . Both involve the use of the args property

Also you should read the difference between passing with -D or with -P that is explained in the Gradle documentation

How to manually deploy artifacts in Nexus Repository Manager OSS 3

This is implemented in Nexus since Version 3.9.0.

  • Login
  • Select Upload

enter image description here

  • Fill out form and upload Artifact

enter image description here

Do I need a content-type header for HTTP GET requests?

Get requests should not have content-type because they do not have request entity (that is, a body)

Is there a way that I can check if a data attribute exists?

var data = $("#dataTable").data('timer');
var diffs = [];

if( data.length > 0 ) {
for(var i = 0; i + 1 < data.length; i++) {
    diffs[i] = data[i + 1] - data[i];
}

alert(diffs.join(', '));
}

Changing the sign of a number in PHP?

A trivial

$num = $num <= 0 ? $num : -$num ;

or, the better solution, IMHO:

$num = -1 * abs($num)

As @VegardLarsen has posted,

the explicit multiplication can be avoided for shortness but I prefer readability over shortness

I suggest to avoid if/else (or equivalent ternary operator) especially if you have to manipulate a number of items (in a loop or using a lambda function), as it will affect performance.

"If the float is a negative, make it a positive."

In order to change the sign of a number you can simply do:

$num = 0 - $num;

or, multiply it by -1, of course :)

How to send string from one activity to another?

TWO CASES

There are two situations possible when we talk about passing data between activities.

Let's say there are two activities A and B and there is a String X. and you are in Activity A.

Now let's see the two cases

  1. A-------->B
  2. A<--------B

CASE 1:
String X is in A and you want to get it in Activity B.

It is very straightforward.

In Activity A.

1) Create Intent
2) Put Extra value
3) startActivity

Intent i = new Intent(A.this, B.class);
i.putExtra("Your_KEY",X);
startActivity(i)

In Activity B

Inside onCreate() method retrieve string X using the key which you used while storing X (Your_KEY).

Intent i = getIntent();
String s = i.getStringExtra("Your_KEY");

Case 2:
This case is little tricky if u are new to Android development Because you are in Activity A, you move to Activity B, collect the string, move back to Activity A and retrieve the collected String or data. Let's see how to deal with this situation.

In Activity A
1) Create Intent
2) start an activity with a request code.

Intent i = new Intent(A.this, B.class);
startActivityForResult(i,your_req_code);

In Activity B
1) Put string X in intent
2) Set result
3) Finish activity

Intent returnIntent = new Intent();
returnIntent .putString("KEY",X);
setResult(resCode,returnIntent);   // for the first argument, you could set Activity.RESULT_OK or your custom rescode too
finish();

Again in Activity A
1) Override onActivityResult method

onActivityResult(int req_code, int res_code, Intent data)
{
       if(req_code==your_req_code)
       {
          String X = data.getStringExtra("KEY")
       }
}

Further understanding of Case 2

You might wonder what is the reqCode, resCode in the onActivityResult(int reqCode, resCode, Intent data)

reqCode is useful when you have to identify from which activity you are getting the result from.

Let's say you have two buttons, one button starts Camera (you click a photo and get the bitmap of that image in your Activity as a result), another button starts GoogleMap( you get back the current coordinates of your location as a result). So to distinguish between the results of both activities you start CameraActivty and MapActivity with different request codes.

resCode: is useful when you have to distinguish between how results are coming back to requesting activity.

For eg: You start Camera Activity. When the camera activity starts, you could either take a photo or just move back to requesting activity without taking a photo with the back button press. So in these two situations, your camera activity sends result with different resCode ACTIVITY.RESULT_OK and ACTIVITY.RESULT_CANCEL respectively.

Relevant Links

Read more on Getting result

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

This seemed to work for me on Max OSX: https://anaconda.org/menpo/opencv3

conda install -c menpo opencv3=3.1.0

I confirmed that you can import cv2 in python using python2.7 and python3

How do I reference tables in Excel using VBA?

The OP asked, is it possible to reference a table, not how to add a table. So the working equivalent of

Sheets("Sheet1").Table("A_Table").Select

would be this statement:

Sheets("Sheet1").ListObjects("A_Table").Range.Select

or to select parts (like only the data in the table):

Dim LO As ListObject
Set LO = Sheets("Sheet1").ListObjects("A_Table")
LO.HeaderRowRange.Select        ' Select just header row
LO.DataBodyRange.Select         ' Select just data cells
LO.TotalsRowRange.Select        ' Select just totals row

For the parts, you may want to test for the existence of the header and totals rows before selecting them.

And seriously, this is the only question on referencing tables in VBA in SO? Tables in Excel make so much sense, but they're so hard to work with in VBA!

JavaScript Promises - reject vs. throw

Yes, the biggest difference is that reject is a callback function that gets carried out after the promise is rejected, whereas throw cannot be used asynchronously. If you chose to use reject, your code will continue to run normally in asynchronous fashion whereas throw will prioritize completing the resolver function (this function will run immediately).

An example I've seen that helped clarify the issue for me was that you could set a Timeout function with reject, for example:

_x000D_
_x000D_
new Promise((resolve, reject) => {
  setTimeout(()=>{reject('err msg');console.log('finished')}, 1000);
  return resolve('ret val')
})
.then((o) => console.log("RESOLVED", o))
.catch((o) => console.log("REJECTED", o));
_x000D_
_x000D_
_x000D_

The above could would not be possible to write with throw.

_x000D_
_x000D_
try{
  new Promise((resolve, reject) => {
    setTimeout(()=>{throw new Error('err msg')}, 1000);
    return resolve('ret val')
  })
  .then((o) => console.log("RESOLVED", o))
  .catch((o) => console.log("REJECTED", o));
}catch(o){
  console.log("IGNORED", o)
}
_x000D_
_x000D_
_x000D_

In the OP's small example the difference in indistinguishable but when dealing with more complicated asynchronous concept the difference between the two can be drastic.

What is a callback in java

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

Paul Jakubik, Callback Implementations in C++.

How to to send mail using gmail in Laravel?

Note: Laravel 7 replaced MAIL_DRIVER by MAIL_MAILER

MAIL_MAILER=smtp    
MAIL_HOST=smtp.gmail.com   
MAIL_PORT=587      
MAIL_USERNAME=yourgmailaddress
MAIL_PASSWORD=yourgmailpassword
MAIL_ENCRYPTION=tls

Allow less secure apps from "Google Account" - https://myaccount.google.com/ - Settings - Less secure app access (Turn On)

Flush cache config:

php artisan config:cache

For Apache:

sudo service apache2 restart

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

I ran into the same error, but I was not using model-first. It turned out that somehow my EDMX file contained a reference to a table even though it did not show up in the designer. Interestingly, when I did a text search for the table name in Visual Studio (2013) the table was not found.

To solve the issue, I used an external editor (Notepad++) to find the reference to the offending table in the EDMX file, and then (carefully) removed all references to the table. I am sorry to say that I do not know how the EDMX file got into this state in the first place.

How can I calculate the difference between two dates?

With Swift 5 and iOS 12, according to your needs, you may use one of the two following ways to find the difference between two dates in days.


#1. Using Calendar's dateComponents(_:from:to:) method

import Foundation

let calendar = Calendar.current

let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!

let dateComponents = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)

print(dateComponents) // prints: day: 1621 isLeapMonth: false
print(String(describing: dateComponents.day)) // prints: Optional(1621)

#2. Using DateComponentsFormatter's string(from:to:) method

import Foundation

let calendar = Calendar.current

let startDate = calendar.date(from: DateComponents(year: 2010, month: 11, day: 22))!
let endDate = calendar.date(from: DateComponents(year: 2015, month: 5, day: 1))!

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full
formatter.allowedUnits = [NSCalendar.Unit.day]

let elapsedTime = formatter.string(from: startDate, to: endDate)
print(String(describing: elapsedTime)) // prints: Optional("1,621 days")

Google Chrome forcing download of "f.txt" file

This issue appears to be causing ongoing consternation, so I will attempt to give a clearer answer than the previously posted answers, which only contain partial hints as to what's happening.

  • Some time around the summer of 2014, IT Security Engineer Michele Spagnuolo (apparently employed at Google Zurich) developed a proof-of-concept exploit and supporting tool called Rosetta Flash that demonstrated a way for hackers to run malicious Flash SWF files from a remote domain in a manner which tricks browsers into thinking it came from the same domain the user was currently browsing. This allows bypassing of the "same-origin policy" and can permit hackers a variety of exploits. You can read the details here: https://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/
    • Known affected browsers: Chrome, IE
    • Possibly unaffected browsers: Firefox
  • Adobe has released at least 5 different fixes over the past year while trying to comprehensively fix this vulnerability, but various major websites also introduced their own fixes earlier on in order to prevent mass vulnerability to their userbases. Among the sites to do so: Google, Youtube, Facebook, Github, and others. One component of the ad-hoc mitigation implemented by these website owners was to force the HTTP Header Content-Disposition: attachment; filename=f.txt on the returns from JSONP endpoints. This has the annoyance of causing the browser to automatically download a file called f.txt that you didn't request—but it is far better than your browser automatically running a possibly malicious Flash file.
  • In conclusion, the websites you were visiting when this file spontaneously downloaded are not bad or malicious, but some domain serving content on their pages (usually ads) had content with this exploit inside it. Note that this issue will be random and intermittent in nature because even visiting the same pages consecutively will often produce different ad content. For example, the advertisement domain ad.doubleclick.net probably serves out hundreds of thousands of different ads and only a small percentage likely contain malicious content. This is why various users online are confused thinking they fixed the issue or somehow affected it by uninstalling this program or running that scan, when in fact it is all unrelated. The f.txt download just means you were protected from a recent potential attack with this exploit and you should have no reason to believe you were compromised in any way.
  • The only way I'm aware that you could stop this f.txt file from being downloaded again in the future would be to block the most common domains that appear to be serving this exploit. I've put a short list below of some of the ones implicated in various posts. If you wanted to block these domains from touching your computer, you could add them to your firewall or alternatively you could use the HOSTS file technique described in the second section of this link: http://www.chromefans.org/chrome-tutorial/how-to-block-a-website-in-google-chrome.htm
  • Short list of domains you could block (by no means a comprehensive list). Most of these are highly associated with adware and malware:
    • ad.doubleclick.net
    • adclick.g.doubleclick.net
    • secure-us.imrworldwide.com
    • d.turn.com
    • ad.turn.com
    • secure.insightexpressai.com
    • core.insightexpressai.com

Android Canvas.drawText

It should be noted that the documentation recommends using a Layout rather than Canvas.drawText directly. My full answer about using a StaticLayout is here, but I will provide a summary below.

String text = "This is some text.";

TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);

int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);

Here is a fuller example in the context of a custom view:

enter image description here

public class MyView extends View {

    String mText = "This is some text.";
    TextPaint mTextPaint;
    StaticLayout mStaticLayout;

    // use this constructor if creating MyView programmatically
    public MyView(Context context) {
        super(context);
        initLabelView();
    }

    // this constructor is used when created from xml
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
    }

    private void initLabelView() {
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);

        // default to a single line of text
        int width = (int) mTextPaint.measureText(mText);
        mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);

        // New API alternate
        //
        // StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
        //        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        //        .setLineSpacing(1, 0) // multiplier, add
        //        .setIncludePad(false);
        // mStaticLayout = builder.build();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Tell the parent layout how big this view would like to be
        // but still respect any requirements (measure specs) that are passed down.

        // determine the width
        int width;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthRequirement;
        } else {
            width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                if (width > widthRequirement) {
                    width = widthRequirement;
                    // too long for a single line so relayout as multiline
                    mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
                }
            }
        }

        // determine the height
        int height;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightRequirement;
        } else {
            height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightRequirement);
            }
        }

        // Required call: set width and height
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // do as little as possible inside onDraw to improve performance

        // draw the text on the canvas after adjusting for padding
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mStaticLayout.draw(canvas);
        canvas.restore();
    }
}

R : how to simply repeat a command?

You could use replicate or sapply:

R> colMeans(replicate(10000, sample(100, size=815, replace=TRUE, prob=NULL))) R> sapply(seq_len(10000), function(...) mean(sample(100, size=815, replace=TRUE, prob=NULL))) 

replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation).

Setting default values to null fields when mapping with Jackson

Make the member private and add a setter/getter pair. In your setter, if null, then set default value instead. Additionally, I have shown the snippet with the getter also returning a default when internal value is null.

class JavaObject {
    private static final String DEFAULT="Default Value";

    public JavaObject() {
    }

    @NotNull
    private String notNullMember;
    public void setNotNullMember(String value){
            if (value==null) { notNullMember=DEFAULT; return; }
            notNullMember=value;
            return;
    }

    public String getNotNullMember(){
            if (notNullMember==null) { return DEFAULT;}
            return notNullMember;
    }

    public String optionalMember;
}

Does file_get_contents() have a timeout setting?

As @diyism mentioned, "default_socket_timeout, stream_set_timeout, and stream_context_create timeout are all the timeout of every line read/write, not the whole connection timeout." And the top answer by @stewe has failed me.

As an alternative to using file_get_contents, you can always use curl with a timeout.

So here's a working code that works for calling links.

$url='http://example.com/';
$ch=curl_init();
$timeout=5;

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$result=curl_exec($ch);
curl_close($ch);
echo $result;

Xampp Access Forbidden php

I had this problem after moving the htdocs folder to outside the xampp folder. If you do this then you need to change the document root in httpd.conf. See https://stackoverflow.com/a/1414/3543329.

How to create a backup of a single table in a postgres database?

If you prefer a graphical user interface, you can use pgAdmin III (Linux/Windows/OS X). Simply right click on the table of your choice, then "backup". It will create a pg_dump command for you.

enter image description here

enter image description here

enter image description here

How do I make an editable DIV look like a text field?

You can place a TEXTAREA of similar size under your DIV, so the standard control's frame would be visible around div.

It's probably good to set it to be disabled, to prevent accidental focus stealing.

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Another way

@Html.TextAreaFor(model => model.Comments[0].Comment)

And in your css do this

textarea
{
    font-family: inherit;
    width: 650px;
    height: 65px;
}

That DataType dealie allows carriage returns in the data, not everybody likes those.

Check if a given time lies between two times regardless of date

strip colons from the $time, $to and $from strings, convert to int and then use the following condition to check if the time is between from and to. Example is in php, but shouldn't matter.

if(($to < $from && ($time >= $from || $time <= $to)) ||
    ($time >= $from && $time <= $to)) {
    return true;
}

Is right click a Javascript event?

If you want to detect right mouse click, you shouldn't use MouseEvent.which property as it is non-standard and there's large incompatibility among browsers. (see MDN) You should instead use MouseEvent.button. It returns a number representing a given button:

  • 0: Main button pressed, usually the left button or the un-initialized state
  • 1: Auxiliary button pressed, usually the wheel button or the middle button (if present)
  • 2: Secondary button pressed, usually the right button
  • 3: Fourth button, typically the Browser Back button
  • 4: Fifth button, typically the Browser Forward button

MouseEvent.button handles more input types than just standard mouse:

Buttons may be configured differently to the standard "left to right" layout. A mouse configured for left-handed use may have the button actions reversed. Some pointing devices only have one button and use keyboard or other input mechanisms to indicate main, secondary, auxilary, etc. Others may have many buttons mapped to different functions and button values.

Reference:

  1. https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  2. https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button

Click event doesn't work on dynamically generated elements

Use 'on' as click gets bind to the elements already present.

For e.g

$('test').on('click',function(){
    alert('Test');
})

This will help.

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

You can fix this issue without opening the storyboard as a source. This warning is triggered by UILabels if numberOfLines !=1 and deployment target is < 8.0

HOW TO FIND IT?

  1. Go to Issue Navigator (CMD+8) and Select latest built with the warning enter image description here
  2. Locate the warning(s) (search for "Automatic Preferred Max Layout") and press expand button on the right
    enter image description here
  3. Find the Object ID of the UILabel enter image description here
  4. Open the Storyboard and SEARCH (CMD+f) for the object. It will SELECT AND HIGHLIGHT the UILabel
  5. Set Preferred Width = 0 "Explicit" as others suggested

jQuery UI Color Picker

Make sure you have jQuery UI base and the color picker widget included on your page (as well as a copy of jQuery 1.3):

<link rel="stylesheet" href="http://dev.jquery.com/view/tags/ui/latest/themes/flora/flora.all.css" type="text/css" media="screen" title="Flora (Default)">

<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.core.js"></script>

<script type="text/javascript" src="http://dev.jquery.com/view/tags/ui/latest/ui/ui.colorpicker.js"></script>

If you have those included, try posting your source so we can see what's going on.

Increase days to php current Date()

The date_add() function should do what you want. In addition, check out the docs (unofficial, but the official ones are a bit sparse) for the DateTime object, it's much nicer to work with than the procedural functions in PHP.

CSS last-child(-1)

Unless you can get PHP to label that element with a class you are better to use jQuery.

jQuery(document).ready(function () {
  $count =  jQuery("ul li").size() - 1;
  alert($count);
  jQuery("ul li:nth-child("+$count+")").css("color","red");
});

How can a Java program get its own process ID?

This is what I used when I had similar requirement. This determines the PID of the Java process correctly. Let your java code spawn a server on a pre-defined port number and then execute OS commands to find out the PID listening on the port. For Linux

netstat -tupln | grep portNumber

Activating Anaconda Environment in VsCode

I found out that if we do not specify which python version we want the environment which is created is completely empty. Thus, to resolve this issue what I did is that I gave the python version as well. i.e

conda create --name env_name python=3.6

so what it does now is that it installs python 3.6 and now we can select the interpreter. For that follow the below-mentioned steps:

  1. Firstly, open the command palette using Ctrl + Shift + P

  2. Secondly, Select Python: select Interpreter

  3. Now, Select Enter interpreter path

  4. We have to add the path where the env is, the default location will be C:\Users\YourUserName\Anaconda3\envs\env_name

Finally, you have successfully activated your environment. It might now be the best way but it worked for me. Let me know if there is any issue.

Saving an image in OpenCV

sorry if this is too obvious. Are you sure the webcam is properly seen and detected by OpenCV in other words, do you get an image when you redirect the captured frame to a "highGui" window? For instance like so:

 frame = cvQueryFrame( capture );
 cvNamedWindow( "myWindow", CV_WINDOW_AUTOSIZE );
 cvShowImage( "myWindow", frame );

AngularJS : ng-model binding not updating when changed with jQuery

You have to trigger the change event of the input element because ng-model listens to input events and the scope will be updated. However, the regular jQuery trigger didn't work for me. But here is what works like a charm

$("#myInput")[0].dispatchEvent(new Event("input", { bubbles: true })); //Works

Following didn't work

$("#myInput").trigger("change"); // Did't work for me

You can read more about creating and dispatching synthetic events.

How to remove item from array by value?

A one-liner will do it,

var ary = ['three', 'seven', 'eleven'];

// Remove item 'seven' from array
var filteredAry = ary.filter(function(e) { return e !== 'seven' })
//=> ["three", "eleven"]

// In ECMA6 (arrow function syntax):
var filteredAry = ary.filter(e => e !== 'seven')

This makes use of the filter function in JS. It's supported in IE9 and up.

What it does (from the doc link)

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

So basically, this is the same as all the other for (var key in ary) { ... } solutions, except that the for in construct is supported as of IE6.

Basically, filter is a convenience method that looks a lot nicer (and is chainable) as opposed to the for in construct (AFAIK).

Windows 7: unable to register DLL - Error Code:0X80004005

Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.

C:\Windows\SysWOW64>regsvr32 "c:\dll.name" 

SQL Server : Transpose rows to columns

Another option that may be suitable in this situation is using XML

The XML option to transposing rows into columns is basically an optimal version of the PIVOT in that it addresses the dynamic column limitation. 

The XML version of the script addresses this limitation by using a combination of XML Path, dynamic T-SQL and some built-in functions (i.e. STUFF, QUOTENAME).

Vertical expansion

Similar to the PIVOT and the Cursor, newly added policies are able to be retrieved in the XML version of the script without altering the original script.

Horizontal expansion

Unlike the PIVOT, newly added documents can be displayed without altering the script.

Performance breakdown

In terms of IO, the statistics of the XML version of the script is almost similar to the PIVOT – the only difference is that the XML has a second scan of dtTranspose table but this time from a logical read – data cache.

You can find some more about these solutions (including some actual T-SQL exmaples) in this article: https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/

How to properly -filter multiple strings in a PowerShell copy script

-Filter only accepts a single string. -Include accepts multiple values, but qualifies the -Path argument. The trick is to append \* to the end of the path, and then use -Include to select multiple extensions. BTW, quoting strings is unnecessary in cmdlet arguments unless they contain spaces or shell special characters.

Get-ChildItem $originalPath\* -Include *.gif, *.jpg, *.xls*, *.doc*, *.pdf*, *.wav*, .ppt*

Note that this will work regardless of whether $originalPath ends in a backslash, because multiple consecutive backslashes are interpreted as a single path separator. For example, try:

Get-ChildItem C:\\\\\Windows

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

I ran into a similar issue today - my ruby version didn't match my rvm installs.

> ruby -v
ruby 2.0.0p481

> rvm list
rvm rubies
   ruby-2.1.2 [ x86_64 ]
=* ruby-2.2.1 [ x86_64 ]
   ruby-2.2.3 [ x86_64 ]

Also, rvm current failed.

> rvm current
Warning! PATH is not properly set up, '/Users/randallreed/.rvm/gems/ruby-2.2.1/bin' is not at first place...

The error message recommended this useful command, which resolved the issue for me:

> rvm get stable --auto-dotfiles

Given an array of numbers, return array of products of all other numbers (no division)

Here's a slightly functional example, using C#:

            Func<long>[] backwards = new Func<long>[input.Length];
            Func<long>[] forwards = new Func<long>[input.Length];

            for (int i = 0; i < input.Length; ++i)
            {
                var localIndex = i;
                backwards[i] = () => (localIndex > 0 ? backwards[localIndex - 1]() : 1) * input[localIndex];
                forwards[i] = () => (localIndex < input.Length - 1 ? forwards[localIndex + 1]() : 1) * input[localIndex];
            }

            var output = new long[input.Length];
            for (int i = 0; i < input.Length; ++i)
            {
                if (0 == i)
                {
                    output[i] = forwards[i + 1]();
                }
                else if (input.Length - 1 == i)
                {
                    output[i] = backwards[i - 1]();
                }
                else
                {
                    output[i] = forwards[i + 1]() * backwards[i - 1]();
                }
            }

I'm not entirely certain that this is O(n), due to the semi-recursion of the created Funcs, but my tests seem to indicate that it's O(n) in time.

Missing Maven dependencies in Eclipse project

So many answers. You see, there could be many reasons, why this is not working, as expected. In my case, I also did not realize the - Tag around my dependencies. facepalm

Example:

...
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>

this only DEFINES the dependency for this and all subprojects with desired version! This is, what it e.g. should look like in the master-POM. To really use the lib in THIS current project, you have too add the depency as following:

...
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${org.slf4j.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
    </dependency>
</dependencies>

NOW it will provide the lib in THIS current project.

Tests not running in Test Explorer

In my case it worked to update the MSTest nuget packages. Could reproduce this problem even on blank MSTest project and updating the packages worked.

What are some alternatives to ReSharper?

VSCommands - not an alternative per se, but rather a complementary tool with plenty of unique features not available in ReSharper, CodeRush, and JustCode.

From the website:

IDE Enhancements

* Custom Formatting
      o Build Output
      o Debug Output
      o Search Output
* Solution Properties
      o Manage Reference Paths
      o Manage Project Properties
* Apply Fix
      o File being used by another process
      o [StyleCop][2] warnings
      o Importing .pfx key file was cancelled
* Search Online
* Cancel Build When First Project Fails
* Advanced Zooming

Solution Explorer Enhancements

* Prevent Accidental Drag & Drop
* Prevent Accidental Linked Item Delete
* Group / Ungroup Items
* Show Assembly Details
* Build Startup Projects
* Open Command Prompt
* Open PowerShell
* Locate Source File
* Open File Location
* Show / Hide All Files
* Edit Project / Solution File
* Copy / Paste As Link
* Copy / Paste Reference
* Open In Expression Blend
* Collapse All
* Clean All Build Configurations

Debugging Assistance

* Attach To Local IIS
* Debug As Administrator
* Debug As Normal user
* Debug As Different user

Code Assistance

* Create Code Contract

TypeLoadException says 'no implementation', but it is implemented

I encountered this when I renamed a project (and the assembly name), which was depended upon by an ASP.NET project. Types in the web project implemented interfaces in the dependent assembly. Despite executing Clean Solution from the Build menu, the assembly with the previous name remained in the bin folder, and when my web project executed

var types = AppDomain.CurrentDomain.
   GetAssemblies().
   ToList().
   SelectMany( s => s.GetTypes() /* exception thrown in this call */ )
;

the above exception was thrown, complaining that interface methods in the implementing web types were not actually implemented. Manually deleting the assembly in the web project's bin folder resolved the problem.

Throwing exceptions from constructors

Although I have not worked C++ at a professional level, in my opinion, it is OK to throw exceptions from the constructors. I do that(if needed) in .Net. Check out this and this link. It might be of your interest.

Xcode - How to fix 'NSUnknownKeyException', reason: … this class is not key value coding-compliant for the key X" error?

I had the same issue.This happened with my project because I changed my product name but in interface builder I had the old name as Module, this leads to crash so be sure to check all the xib module name also has been changed or not.

Map with Key as String and Value as List in Groovy

Groovy accepts nearly all Java syntax, so there is a spectrum of choices, as illustrated below:

// Java syntax 

Map<String,List> map1  = new HashMap<>();
List list1 = new ArrayList();
list1.add("hello");
map1.put("abc", list1); 
assert map1.get("abc") == list1;

// slightly less Java-esque

def map2  = new HashMap<String,List>()
def list2 = new ArrayList()
list2.add("hello")
map2.put("abc", list2)
assert map2.get("abc") == list2

// typical Groovy

def map3  = [:]
def list3 = []
list3 << "hello"
map3.'abc'= list3
assert map3.'abc' == list3

How do I refresh a DIV content?

You can use jQuery to achieve this using simple $.get method. .html work like innerHtml and replace the content of your div.

$.get("/YourUrl", {},
      function (returnedHtml) {
      $("#here").html(returnedHtml);
});

And call this using javascript setInterval method.

Swift how to sort array of custom objects by property value

With Swift 5, Array has two methods called sorted() and sorted(by:). The first method, sorted(), has the following declaration:

Returns the elements of the collection, sorted.

func sorted() -> [Element]

The second method, sorted(by:), has the following declaration:

Returns the elements of the collection, sorted using the given predicate as the comparison between elements.

func sorted(by areInIncreasingOrder: (Element, Element) throws -> Bool) rethrows -> [Element]

#1. Sort with ascending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will be able to use sorted() in order to sort your elements with ascending order. The following Playground code shows how to use sorted():

class ImageFile: CustomStringConvertible, Comparable {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }

    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted()
print(sortedImages)

/*
 prints: [ImageFile with ID: 100, ImageFile with ID: 200, ImageFile with ID: 300]
 */

#2. Sort with descending order for comparable objects

If the element type inside your collection conforms to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with a descending order.

class ImageFile: CustomStringConvertible, Comparable {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

    static func ==(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID == rhs.fileID
    }

    static func <(lhs: ImageFile, rhs: ImageFile) -> Bool {
        return lhs.fileID < rhs.fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0 > img1
})
//let sortedImages = images.sorted(by: >) // also works
//let sortedImages = images.sorted { $0 > $1 } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

#3. Sort with ascending or descending order for non-comparable objects

If the element type inside your collection DOES NOT conform to Comparable protocol, you will have to use sorted(by:) in order to sort your elements with ascending or descending order.

class ImageFile: CustomStringConvertible {

    let fileName: String
    let fileID: Int
    var description: String { return "ImageFile with ID: \(fileID)" }

    init(fileName: String, fileID: Int) {
        self.fileName = fileName
        self.fileID = fileID
    }

}

let images = [
    ImageFile(fileName: "Car", fileID: 300),
    ImageFile(fileName: "Boat", fileID: 100),
    ImageFile(fileName: "Plane", fileID: 200)
]

let sortedImages = images.sorted(by: { (img0: ImageFile, img1: ImageFile) -> Bool in
    return img0.fileID < img1.fileID
})
//let sortedImages = images.sorted { $0.fileID < $1.fileID } // also works
print(sortedImages)

/*
 prints: [ImageFile with ID: 300, ImageFile with ID: 200, ImageFile with ID: 100]
 */

Note that Swift also provides two methods called sort() and sort(by:) as counterparts of sorted() and sorted(by:) if you need to sort your collection in-place.

What are the most common naming conventions in C?

Well firstly C doesn't have public/private/virtual functions. That's C++ and it has different conventions. In C typically you have:

  • Constants in ALL_CAPS
  • Underscores to delimit words in structs or function names, hardly ever do you see camel case in C;
  • structs, typedefs, unions, members (of unions and structs) and enum values typically are in lower case (in my experience) rather than the C++/Java/C#/etc convention of making the first letter a capital but I guess it's possible in C too.

C++ is more complex. I've seen a real mix here. Camel case for class names or lowercase+underscores (camel case is more common in my experience). Structs are used rarely (and typically because a library requires them, otherwise you'd use classes).

How to get all count of mongoose model?

Background for the solution

As stated in the mongoose documentation and in the answer by Benjamin, the method Model.count() is deprecated. Instead of using count(), the alternatives are the following:

Model.countDocuments(filterObject, callback)

Counts how many documents match the filter in a collection. Passing an empty object {} as filter executes a full collection scan. If the collection is large, the following method might be used.

Model.estimatedDocumentCount()

This model method estimates the number of documents in the MongoDB collection. This method is faster than the previous countDocuments(), because it uses collection metadata instead of going through the entire collection. However, as the method name suggests, and depending on db configuration, the result is an estimate as the metadata might not reflect the actual count of documents in a collection at the method execution moment.

Both methods return a mongoose query object, which can be executed in one of the following two ways. Use .exec() if you want to execute a query at a later time.

The solution

Option 1: Pass a callback function

For example, count all documents in a collection using .countDocuments():

someModel.countDocuments({}, function(err, docCount) {
    if (err) { return handleError(err) } //handle possible errors
    console.log(docCount)
    //and do some other fancy stuff
})

Or, count all documents in a collection having a certain name using .countDocuments():

someModel.countDocuments({ name: 'Snow' }, function(err, docCount) {
    //see other example
}

Option 2: Use .then()

A mongoose query has .then() so it’s “thenable”. This is for a convenience and query itself is not a promise.

For example, count all documents in a collection using .estimatedDocumentCount():

someModel
    .estimatedDocumentCount()
    .then(docCount => {
        console.log(docCount)
        //and do one super neat trick
    })
    .catch(err => {
        //handle possible errors
    })

Option 3: Use async/await

When using async/await approach, the recommended way is to use it with .exec() as it provides better stack traces.

const docCount = await someModel.countDocuments({}).exec();

Learning by stackoverflowing,

How to get public directory?

The best way to retrieve your public folder path from your Laravel config is the function:

$myPublicFolder = public_path();
$savePath = $mypublicPath."enter_path_to_save";
$path = $savePath."filename.ext";
return File::put($path , $data);

There is no need to have all the variables, but this is just for a demonstrative purpose.

Hope this helps, GRnGC

Opening port 80 EC2 Amazon web services

  1. Check what security group you are using for your instance. See value of Security Groups column in row of your instance. It's important - I changed rules for default group, but my instance was under quickstart-1 group when I had similar issue.
  2. Go to Security Groups tab, go to Inbound tab, select HTTP in Create a new rule combo-box, leave 0.0.0.0/0 in source field and click Add Rule, then Apply rule changes.

BeautifulSoup: extract text from anchor tag

I would suggest going the lxml route and using xpath.

from lxml import etree
# data is the variable containing the html
data = etree.HTML(data)
anchor = data.xpath('//a[@class="title"]/text()')

ActionController::UnknownFormat

You can also modify your config/routes.rb file like:

 get 'ajax/:action', to: 'ajax#:action', :defaults => { :format => 'json' }

Which will default the format to json. It is working fine for me in Rails 4.

Or if you want to go even further and you are using namespaces, you can cut down the duplicates:

namespace :api, defaults: {format: 'json'} do
   #your controller routes here ...
end

with the above everything under /api will be formatted as json by default.

Get current AUTO_INCREMENT value for any table

You can get all of the table data by using this query:

SHOW TABLE STATUS FROM `DatabaseName` WHERE `name` LIKE 'TableName' ;

You can get exactly this information by using this query:

SELECT `AUTO_INCREMENT`
FROM  INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA = 'DatabaseName'
AND   TABLE_NAME   = 'TableName';

Laravel Mail::send() sending to multiple to or bcc addresses

I am using Laravel 5.6 and the Notifications Facade.

If I set a variable with comma separating the e-mails and try to send it, I get the error: "Address in mail given does not comply with RFC 2822, 3.6.2"

So, to solve the problem, I got the solution idea from @Toskan, coding the following.

        // Get data from Database
        $contacts = Contacts::select('email')
            ->get();

        // Create an array element
        $contactList = [];
        $i=0;

        // Fill the array element
        foreach($contacts as $contact){
            $contactList[$i] = $contact->email;
            $i++;
        }

        .
        .
        .

        \Mail::send('emails.template', ['templateTitle'=>$templateTitle, 'templateMessage'=>$templateMessage, 'templateSalutation'=>$templateSalutation, 'templateCopyright'=>$templateCopyright], function($message) use($emailReply, $nameReply, $contactList) {
                $message->from('[email protected]', 'Some Company Name')
                        ->replyTo($emailReply, $nameReply)
                        ->bcc($contactList, 'Contact List')
                        ->subject("Subject title");
            });

It worked for me to send to one or many recipients.

How to read Data from Excel sheet in selenium webdriver

i have used following method to use input data from excel sheet: Need to import following as well

import jxl.Workbook;

then

Workbook wBook = Workbook.getWorkbook(new File("E:\\Testdata\\ShellData.xls"));
//get sheet
jxl.Sheet Sheet = wBook.getSheet(0); 
//Now in application i have given my Username and Password input in following way
driver.findElement(By.xpath("//input[@id='UserName']")).sendKeys(Sheet.getCell(0, i).getContents());
driver.findElement(By.xpath("//input[@id='Password']")).sendKeys(Sheet.getCell(1, i).getContents());
driver.findElement(By.xpath("//input[@name='Login']")).click();

it will Work

How do I open a new fragment from another fragment?

Add following code in your click listener function,

NextFragment nextFrag= new NextFragment();
getActivity().getSupportFragmentManager().beginTransaction()
             .replace(R.id.Layout_container, nextFrag, "findThisFragment")
             .addToBackStack(null)
             .commit();

The string "findThisFragment" can be used to find the fragment later, if you need.

How to thoroughly purge and reinstall postgresql on ubuntu?

I know an answer has already been provided, but dselect didn't work for me. Here is what worked to find the packages to remove:

# search postgr  | grep ^i
i   postgresql                      - object-relational SQL database (supported 
i A postgresql-8.4                  - object-relational SQL database, version 8.
i A postgresql-client-8.4           - front-end programs for PostgreSQL 8.4     
i A postgresql-client-common        - manager for multiple PostgreSQL client ver
i A postgresql-common               - PostgreSQL database-cluster manager       

# aptitude purge postgresql-8.4 postgresql-client-8.4 postgresql-client-common postgresql-common postgresql

rm -r /etc/postgresql/
rm -r /etc/postgresql-common/
rm -r /var/lib/postgresql/

Finally, editing /etc/passwd and /etc/group

Possible to iterate backwards through a foreach?

This works pretty well

List<string> list = new List<string>();

list.Add("Hello");
list.Add("Who");
list.Add("Are");
list.Add("You");

foreach (String s in list)
{
    Console.WriteLine(list[list.Count - list.IndexOf(s) - 1]);
}

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Different connections pools have different configs.

For example Tomcat (default) expects:

spring.datasource.ourdb.url=...

and HikariCP will be happy with:

spring.datasource.ourdb.jdbc-url=...

We can satisfy both without boilerplate configuration:

spring.datasource.ourdb.jdbc-url=${spring.datasource.ourdb.url}

There is no property to define connection pool provider.

Take a look at source DataSourceBuilder.java

If Tomcat, HikariCP or Commons DBCP are on the classpath one of them will be selected (in that order with Tomcat first).

... so, we can easily replace connection pool provider using this maven configuration (pom.xml):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.apache.tomcat</groupId>
                <artifactId>tomcat-jdbc</artifactId>
            </exclusion>
        </exclusions>
    </dependency>       

    <dependency>
        <groupId>com.zaxxer</groupId>
        <artifactId>HikariCP</artifactId>
    </dependency>

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

Showing Difference between two datetime values in hours

var startTime = new TimeSpan(6, 0, 0); // 6:00 AM
var endTime = new TimeSpan(5, 30, 0); // 5:30 AM 
var hours24 = new TimeSpan(24, 0, 0);
var difference = endTime.Subtract(startTime); // (-00:30:00)
difference = (difference.Duration() != difference) ? hours24.Subtract(difference.Duration()) : difference; // (23:30:00)

can also add difference between the dates if we compare two different dates

new TimeSpan(24 * days, 0, 0)

Database design for a survey

No 2 looks fine.

For a table with only 4 columns it shouldn't be a problem, even with a good few million rows. Of course this can depend on what database you are using. If its something like SQL Server then it would be no problem.

You'd probably want to create an index on the QuestionID field, on the tblAnswer table.

Of course, you need to specify what Database you are using as well as estimated volumes.

Replace tabs with spaces in vim

first search for tabs in your file : /^I :set expandtab :retab

will work.

Sorting by date & time in descending order?

Following Query works for me. Database Tabel t_sonde_results has domain d_date (datatype DATE) and d_time (datatype TIME) The intention is to query for last entry in t_sonde_results sorted by Date and Time

select * from (select * from (SELECT * FROM t_sonde_results WHERE d_user_name = 'kenis' and d_smartbox_id = 6 order by d_time asc) AS tmp order by d_date and d_time limit 1) as tmp1

Finding element in XDocument?

Sebastian's answer was the only answer that worked for me while examining a xaml document. If, like me, you'd like a list of all the elements then the method would look a lot like Sebastian's answer above but just returning a list...

    private static List<XElement> GetElements(XDocument doc, string elementName)
    {
        List<XElement> elements = new List<XElement>();

        foreach (XNode node in doc.DescendantNodes())
        {
            if (node is XElement)
            {
                XElement element = (XElement)node;
                if (element.Name.LocalName.Equals(elementName))
                    elements.Add(element);
            }
        }
        return elements;
    }

Call it thus:

var elements = GetElements(xamlFile, "Band");

or in the case of my xaml doc where I wanted all the TextBlocks, call it thus:

var elements = GetElements(xamlFile, "TextBlock");

How to quickly and conveniently create a one element arraylist

Seeing as Guava gets a mention, I thought I would also suggest Eclipse Collections (formerly known as GS Collections).

The following examples all return a List with a single item.

Lists.mutable.of("Just one item");
Lists.mutable.with("Or use with");
Lists.immutable.of("Maybe it must be immutable?");
Lists.immutable.with("And use with if you want");

There are similar methods for other collections.

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

How does Access-Control-Allow-Origin header work?

Whenever I start thinking about CORS, my intuition about which site hosts the headers is incorrect, just as you described in your question. For me, it helps to think about the purpose of the same origin policy.

The purpose of the same origin policy is to protect you from malicious JavaScript on siteA.com accessing private information you've chosen to share only with siteB.com. Without the same origin policy, JavaScript written by the authors of siteA.com could make your browser make requests to siteB.com, using your authentication cookies for siteB.com. In this way, siteA.com could steal the secret information you share with siteB.com.

Sometimes you need to work cross domain, which is where CORS comes in. CORS relaxes the same origin policy for domainB.com, using the Access-Control-Allow-Origin header to list other domains (domainA.com) that are trusted to run JavaScript that can interact with domainA.com.

To understand which domain should serve the CORS headers, consider this. You visit malicious.com, which contains some JavaScript that tries to make a cross domain request to mybank.com. It should be up to mybank.com, not malicious.com, to decide whether or not it sets CORS headers that relax the same origin policy allowing the JavaScript from malicious.com to interact with it. If malicous.com could set its own CORS headers allowing its own JavaScript access to mybank.com, this would completely nullify the same origin policy.

I think the reason for my bad intuition is the point of view I have when developing a site. It's my site, with all my JavaScript, therefore it isn't doing anything malicious and it should be up to me to specify which other sites my JavaScript can interact with. When in fact I should be thinking which other sites JavaScript are trying to interact with my site and should I use CORS to allow them?

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

Windows Batch Files: if else

Surround your %1 with something.

Eg:

if not "%1" == ""

Another one I've seen fairly often:

if not {%1} == {}

And so on...

The problem, as you can likely guess, is that the %1 is literally replaced with emptiness. It is not 'an empty string' it is actually a blank spot in your source file at that point.

Then after the replacement, the interpreter tries to parse the if statement and gets confused.

Add ripple effect to my button with button background color?

setForeground is added in API level 23. Leverage the power of RevealAnimator in case u need to relay on foreground property !

 <View
   android:id="@+id/circular_reveal"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:background="@color/primaryMilk_22"
   android:elevation="@dimen/margin_20"
   android:visibility="invisible" />

With kotlin ext function, it's way osm !

fun View.circularReveal() {
    val cx: Int = width / 2
    val cy: Int = height / 2
    val finalRadius: Int =
        width.coerceAtLeast(height)
    val anim: Animator = ViewAnimationUtils.createCircularReveal(
        this,
        cx,
        cy,
        0f,
        finalRadius.toFloat()
    )
    anim.interpolator = AccelerateDecelerateInterpolator()
    anim.duration = 400
    isVisible = true
    anim.start()
    anim.doOnEnd {
        isVisible = false
    }
}

Data structure for maintaining tabular data in memory?

I personally would use the list of row lists. Because the data for each row is always in the same order, you can easily sort by any of the columns by simply accessing that element in each of the lists. You can also easily count based on a particular column in each list, and make searches as well. It's basically as close as it gets to a 2-d array.

Really the only disadvantage here is that you have to know in what order the data is in, and if you change that ordering, you'll have to change your search/sorting routines to match.

Another thing you can do is have a list of dictionaries.

rows = []
rows.append({"ID":"1", "name":"Cat", "year":"1998", "priority":"1"})

This would avoid needing to know the order of the parameters, so you can look through each "year" field in the list.

Pass multiple values with onClick in HTML link

Please try this

for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"

AngularJS not detecting Access-Control-Allow-Origin header?

If you guys are having this problem in sails.js just set your cors.js to include Authorization as the allowed header

_x000D_
_x000D_
/***************************************************************************_x000D_
  *                                                                          *_x000D_
  * Which headers should be allowed for CORS requests? This is only used in  *_x000D_
  * response to preflight requests.                                          *_x000D_
  *                                                                          *_x000D_
  ***************************************************************************/_x000D_
_x000D_
  headers: 'Authorization' // this line here
_x000D_
_x000D_
_x000D_

Get Element value with minidom with Python

I had a similar case, what worked for me was:

name.firstChild.childNodes[0].data

XML is supposed to be simple and it really is and I don't know why python's minidom did it so complicated... but it's how it's made

How to align linearlayout to vertical center?

use android:layout_gravity instead of android:gravity

android:gravity sets the gravity of the content of the View its used on. android:layout_gravity sets the gravity of the View or Layout in its parent.

Back to previous page with header( "Location: " ); in PHP

Its so simple just use this

header("location:javascript://history.go(-1)");

Its working fine for me

Scala list concatenation, ::: vs ++

Always use :::. There are two reasons: efficiency and type safety.

Efficiency

x ::: y ::: z is faster than x ++ y ++ z, because ::: is right associative. x ::: y ::: z is parsed as x ::: (y ::: z), which is algorithmically faster than (x ::: y) ::: z (the latter requires O(|x|) more steps).

Type safety

With ::: you can only concatenate two Lists. With ++ you can append any collection to List, which is terrible:

scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)

++ is also easy to mix up with +:

scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab

iOS 7 UIBarButton back button arrow color

You can set the color on the entire app navigation's bar using the method

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:
(NSDictionary *)launchOptions{
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
}

Bootstrap modal: close current, open new

I have exact same problem, and my solution is only if modal dialog have [role="dialog"] attribute :

/*
* Find and Close current "display:block" dialog,
* if another data-toggle=modal is clicked
*/
jQuery(document).on('click','[data-toggle*=modal]',function(){
  jQuery('[role*=dialog]').each(function(){
    switch(jQuery(this).css('display')){
      case('block'):{jQuery('#'+jQuery(this).attr('id')).modal('hide'); break;}
    }
  });
});

Switch between python 2.7 and python 3.5 on Mac OS X

IMHO, the best way to use two different Python versions on macOS is via homebrew. After installing homebrew on macOS, run the commands below on your terminal.

brew install python@2
brew install python

Now you can run Python 2.7 by invoking python2 or Python 3 by invoking python3. In addition to this, you can use virtualenv or pyenv to manage different versions of python environments.

I have never personally used miniconda but from the documentation, it looks like it is similar to using pip and virtualenv in combination.

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Correcting gradle settings is quite difficult. If you don't know much about Gradle it requires you to learn alot. Instead you can do the following:

1) Start a new project in a new folder. Choose the same settings with your project with gradle problem but keep it simple: Choose an empty main activity. 2) Delete all the files in ...\NewProjectName\app\src\main folder 3) Copy all the files in ...\ProjectWithGradleProblem\app\src\main folder to ...\NewProjectName\app\src\main folder. 4) If you are using the Test project (\ProjectWithGradleProblem\app\src\AndroidTest) you can do the same for that too.

this method works fine if your Gradle installation is healthy. If you just installed Android studio and did not modify it, the Gradle installation should be fine.

How can I perform a short delay in C# without using sleep?

Sorry for awakening an old question like this. But I think what the original author wanted as an answer was:

You need to force your program to make the graphic update after you make the change to the textbox1. You can do that by invoking Update();

textBox1.Text += "\r\nThread Sleeps!";
textBox1.Update();
System.Threading.Thread.Sleep(4000);
textBox1.Text += "\r\nThread awakens!";
textBox1.Update();

Normally this will be done automatically when the thread is done. Ex, you press a button, changes are made to the text, thread dies, and then .Update() is fired and you see the changes. (I'm not an expert so I cant really tell you when its fired, but its something similar to this any way.)

In this case, you make a change, pause the thread, and then change the text again, and when the thread finally dies the .Update() is fired. This resulting in you only seeing the last change made to the text.

You would experience the same issue if you had a long execution between the text changes.

How to compare datetime with only date in SQL Server

According to your query Select * from [User] U where U.DateCreated = '2014-02-07'

SQL Server is comparing exact date and time i.e (comparing 2014-02-07 12:30:47.220 with 2014-02-07 00:00:00.000 for equality). that's why result of comparison is false

Therefore, While comparing dates you need to consider time also. You can use
Select * from [User] U where U.DateCreated BETWEEN '2014-02-07' AND '2014-02-08'.

HTML button calling an MVC Controller and Action method

Building on couple of the above answers, you could do this:

<button onclick="location.href='@Url.Action("ActionName", "ControllerName")'" />

Adding POST parameters before submit

You can do a form.serializeArray(), then add name-value pairs before posting:

var form = $(this).closest('form');

form = form.serializeArray();

form = form.concat([
    {name: "customer_id", value: window.username},
    {name: "post_action", value: "Update Information"}
]);

$.post('/change-user-details', form, function(d) {
    if (d.error) {
        alert("There was a problem updating your user details")
    } 
});

Java escape JSON String?

The best method would be using some JSON library, e.g. Jackson ( http://jackson.codehaus.org ).

But if this is not an option simply escape msget before adding it to your string:

The wrong way to do this is

String msgetEscaped = msget.replaceAll("\"", "\\\"");

Either use (as recommended in the comments)

String msgetEscaped = msget.replace("\"", "\\\"");

or

String msgetEscaped = msget.replaceAll("\"", "\\\\\"");

A sample with all three variants can be found here: http://ideone.com/Nt1XzO

Convert date from String to Date format in Dataframes

Since your main aim was to convert the type of a column in a DataFrame from String to Timestamp, I think this approach would be better.

import org.apache.spark.sql.functions.{to_date, to_timestamp}
val modifiedDF = DF.withColumn("Date", to_date($"Date", "MM/dd/yyyy"))

You could also use to_timestamp (I think this is available from Spark 2.x) if you require fine grained timestamp.

Python strftime - date without leading 0?

Some platforms may support width and precision specification between % and the letter (such as 'd' for day of month), according to http://docs.python.org/library/time.html -- but it's definitely a non-portable solution (e.g. doesn't work on my Mac;-). Maybe you can use a string replace (or RE, for really nasty format) after the strftime to remedy that? e.g.:

>>> y
(2009, 5, 7, 17, 17, 17, 3, 127, 1)
>>> time.strftime('%Y %m %d', y)
'2009 05 07'
>>> time.strftime('%Y %m %d', y).replace(' 0', ' ')
'2009 5 7'

Stored procedure or function expects parameter which is not supplied

Your stored procedure expects 5 parameters as input

@userID int, 
@userName varchar(50), 
@password nvarchar(50), 
@emailAddress nvarchar(50), 
@preferenceName varchar(20) 

So you should add all 5 parameters to this SP call:

    cmd.CommandText = "SHOWuser";
    cmd.Parameters.AddWithValue("@userID",userID);
    cmd.Parameters.AddWithValue("@userName", userName);
    cmd.Parameters.AddWithValue("@password", password);
    cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
    cmd.Parameters.AddWithValue("@preferenceName", preferences);
    dbcon.Open();

PS: It's not clear what these parameter are for. You don't use these parameters in your SP body so your SP should looks like:

ALTER PROCEDURE [dbo].[SHOWuser] AS BEGIN ..... END

Could not reliably determine the server's fully qualified domain name

Yes, you should set ServerName:

http://wiki.apache.org/httpd/CouldNotDetermineServerName

http://httpd.apache.org/docs/current/mod/core.html#servername

You can find information on the layouts used by the various httpd distributions here:

http://wiki.apache.org/httpd/DistrosDefaultLayout

In your case the file to edit is /etc/httpd/conf/httpd.conf

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

This is a simple example of JSON parsing by taking example of google map API. This will return City name of given zip code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Net;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        WebClient client = new WebClient();
        string jsonstring;
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            jsonstring = client.DownloadString("http://maps.googleapis.com/maps/api/geocode/json?address="+txtzip.Text.Trim());
            dynamic dynObj = JsonConvert.DeserializeObject(jsonstring);

            Response.Write(dynObj.results[0].address_components[1].long_name);
        }
    }
}

Get the week start date and week end date from week number

Week Start & End Date From Date For Power BI Dax Formula

WeekStartDate = [DateColumn] - (WEEKDAY([DateColumn])-1)
WeekEndDate = [DateColumn] + (7-WEEKDAY([DateColumn]))

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

How to enable cross-origin resource sharing (CORS) in the express.js framework on node.js

app.use(function(req, res, next) {
var allowedOrigins = [
  "http://localhost:4200"
];
var origin = req.headers.origin;
console.log(origin)
console.log(allowedOrigins.indexOf(origin) > -1)
// Website you wish to allow to
if (allowedOrigins.indexOf(origin) > -1) {
  res.setHeader("Access-Control-Allow-Origin", origin);
}

// res.setHeader("Access-Control-Allow-Origin", "http://localhost:4200");

// Request methods you wish to allow
res.setHeader(
  "Access-Control-Allow-Methods",
  "GET, POST, OPTIONS, PUT, PATCH, DELETE"
);

// Request headers you wish to allow
res.setHeader(
  "Access-Control-Allow-Headers",
  "X-Requested-With,content-type,Authorization"
);

// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader("Access-Control-Allow-Credentials", true);

// Pass to next layer of middleware
next();

});

Add this code in your index.js or server.js file and change the allowed origin array according to your requirement.

How do I commit only some files?

I suppose you want to commit the changes to one branch and then make those changes visible in the other branch. In git you should have no changes on top of HEAD when changing branches.

You commit only the changed files by:

git commit [some files]

Or if you are sure that you have a clean staging area you can

git add [some files]       # add [some files] to staging area
git add [some more files]  # add [some more files] to staging area
git commit                 # commit [some files] and [some more files]

If you want to make that commit available on both branches you do

git stash                     # remove all changes from HEAD and save them somewhere else
git checkout <other-project>  # change branches
git cherry-pick <commit-id>   # pick a commit from ANY branch and apply it to the current
git checkout <first-project>  # change to the other branch
git stash pop                 # restore all changes again

gnuplot - adjust size of key/legend

To adjust the length of the samples:

set key samplen X

(default is 4)

To adjust the vertical spacing of the samples:

set key spacing X

(default is 1.25)

and (for completeness), to adjust the fontsize:

set key font "<face>,<size>"

(default depends on the terminal)

And of course, all these can be combined into one line:

set key samplen 2 spacing .5 font ",8"

Note that you can also change the position of the key using set key at <position> or any one of the pre-defined positions (which I'll just defer to help key at this point)

HTML5 Canvas Rotate Image

Quickest 2D context image rotation method

A general purpose image rotation, position, and scale.

// no need to use save and restore between calls as it sets the transform rather 
// than multiply it like ctx.rotate ctx.translate ctx.scale and ctx.transform
// Also combining the scale and origin into the one call makes it quicker
// x,y position of image center
// scale scale of image
// rotation in radians.
function drawImage(image, x, y, scale, rotation){
    ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
    ctx.rotate(rotation);
    ctx.drawImage(image, -image.width / 2, -image.height / 2);
} 

If you wish to control the rotation point use the next function

// same as above but cx and cy are the location of the point of rotation
// in image pixel coordinates
function drawImageCenter(image, x, y, cx, cy, scale, rotation){
    ctx.setTransform(scale, 0, 0, scale, x, y); // sets scale and origin
    ctx.rotate(rotation);
    ctx.drawImage(image, -cx, -cy);
} 

To reset the 2D context transform

ctx.setTransform(1,0,0,1,0,0); // which is much quicker than save and restore

Thus to rotate image to the left (anti clockwise) 90 deg

drawImage(image, canvas.width / 2, canvas.height / 2, 1, - Math.PI / 2);

Thus to rotate image to the right (clockwise) 90 deg

drawImage(image, canvas.width / 2, canvas.height / 2, 1, Math.PI / 2);

Example draw 500 images translated rotated scaled

_x000D_
_x000D_
var image = new Image;_x000D_
image.src = "https://i.stack.imgur.com/C7qq2.png?s=328&g=1";_x000D_
var canvas = document.createElement("canvas");_x000D_
var ctx = canvas.getContext("2d");_x000D_
canvas.style.position = "absolute";_x000D_
canvas.style.top = "0px";_x000D_
canvas.style.left = "0px";_x000D_
document.body.appendChild(canvas);_x000D_
var w,h;_x000D_
function resize(){ w = canvas.width = innerWidth; h = canvas.height = innerHeight;}_x000D_
resize();_x000D_
window.addEventListener("resize",resize);_x000D_
function rand(min,max){return Math.random() * (max ?(max-min) : min) + (max ? min : 0) }_x000D_
function DO(count,callback){ while (count--) { callback(count) } }_x000D_
const sprites = [];_x000D_
DO(500,()=>{_x000D_
    sprites.push({_x000D_
       x : rand(w), y : rand(h),_x000D_
       xr : 0, yr : 0, // actual position of sprite_x000D_
       r : rand(Math.PI * 2),_x000D_
       scale : rand(0.1,0.25),_x000D_
       dx : rand(-2,2), dy : rand(-2,2),_x000D_
       dr : rand(-0.2,0.2),_x000D_
    });_x000D_
});_x000D_
function drawImage(image, spr){_x000D_
    ctx.setTransform(spr.scale, 0, 0, spr.scale, spr.xr, spr.yr); // sets scales and origin_x000D_
    ctx.rotate(spr.r);_x000D_
    ctx.drawImage(image, -image.width / 2, -image.height / 2);_x000D_
}_x000D_
function update(){_x000D_
    var ihM,iwM;_x000D_
    ctx.setTransform(1,0,0,1,0,0);_x000D_
    ctx.clearRect(0,0,w,h);_x000D_
    if(image.complete){_x000D_
      var iw = image.width;_x000D_
      var ih = image.height;_x000D_
      for(var i = 0; i < sprites.length; i ++){_x000D_
          var spr = sprites[i];_x000D_
          spr.x += spr.dx;_x000D_
          spr.y += spr.dy;_x000D_
          spr.r += spr.dr;_x000D_
          iwM = iw * spr.scale * 2 + w;_x000D_
          ihM = ih * spr.scale * 2 + h;_x000D_
          spr.xr = ((spr.x % iwM) + iwM) % iwM - iw * spr.scale;_x000D_
          spr.yr = ((spr.y % ihM) + ihM) % ihM - ih * spr.scale;_x000D_
          drawImage(image,spr);_x000D_
      }_x000D_
    }    _x000D_
    requestAnimationFrame(update);_x000D_
}_x000D_
requestAnimationFrame(update);
_x000D_
_x000D_
_x000D_

How to determine the version of android SDK installed in computer?

I develope cross-plateform mobile applications Using Xamarin integrated in Visual Studio 2017.

I prefer to install and check all details of Android SDK from within the Visual Studio 2017. This can be found under the menu TOOLS -> Android -> Android SDK Manager.

Bellow is the Visual representation of the Adroid SDK Manager.enter image description here

Why is the minidlna database not being refreshed?

AzP already provided most of the information, but some of it is incorrect.

First of all, there is no such option inotify_interval. The only option that exists is notify_interval and has nothing to do with inotify.

So to clarify, notify_interval controls how frequently the (mini)dlna server announces itself in the network. The default value of 895 means it will announce itself about once every 15 minutes, meaning clients will need at most 15 minutes to find the server. I personally use 1-5 minutes depending on client volatility in the network.

In terms of getting minidlna to find files that have been added, there are two options:

  • The first is equivalent to removing the file files.db and consists in restarting minidlna while passing the -R argument, which forces a full rescan and builds the database from scratch. Since version 1.2.0 there's now also the -r argument which performs a rebuild action. This preserves any existing database and drops and adds old and new records, respectively.
  • The second is to rely on inotify events by setting inotify=yes and restarting minidlna. If inotify is set to =no, the only option to update the file database is the forced full rescan.

Additionally, in order to have inotify working, the file-system must support inotify events, which is not the case in most remote file-systems. If you have minidlna running over NFS it will not see any inotify events because these are generated on the server side and not on the client.

Finally, even if inotify is working and is supported by the file-system, the user under which minidlna is running must be able to read the file, otherwise it will not be able to retrieve necessary metadata. In this case, the logfile (usually /var/log/minidlna.log) should contain useful information.

How to easily initialize a list of Tuples?

c# 7.0 lets you do this:

  var tupleList = new List<(int, string)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

If you don't need a List, but just an array, you can do:

  var tupleList = new(int, string)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

And if you don't like "Item1" and "Item2", you can do:

  var tupleList = new List<(int Index, string Name)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

or for an array:

  var tupleList = new (int Index, string Name)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

which lets you do: tupleList[0].Index and tupleList[0].Name

Framework 4.6.2 and below

You must install System.ValueTuple from the Nuget Package Manager.

Framework 4.7 and above

It is built into the framework. Do not install System.ValueTuple. In fact, remove it and delete it from the bin directory.

note: In real life, I wouldn't be able to choose between cow, chickens or airplane. I would be really torn.

How can I drop a table if there is a foreign key constraint in SQL Server?

To drop a table if there is a foreign key constraint in MySQL Server?

Run the sql query:

SET FOREIGN_KEY_CHECKS = 0; DROP TABLE table_name

Hope it helps!

What is the syntax for Typescript arrow functions with generics?

In case you'd like to do it with async:

const request = async <T>(param1: string, param2: number) => {
  const res = await func();
  return res.response() as T;
}

And a more complex pattern, in case you'd like to wrap your function inside a generic counterpart, such as memoization (Example uses fast-memoize):

const request = memoize(
  async <T>(
    url: string,
    token?: string
  ) => {
    // Perform your code here
  }
);

See how you define the generic after the memoizing function.

Add a common Legend for combined ggplots

You may also use ggarrange from ggpubr package and set "common.legend = TRUE":

library(ggpubr)

dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
p1 <- qplot(carat, price, data = dsamp, colour = clarity)
p2 <- qplot(cut, price, data = dsamp, colour = clarity)
p3 <- qplot(color, price, data = dsamp, colour = clarity)
p4 <- qplot(depth, price, data = dsamp, colour = clarity) 

ggarrange(p1, p2, p3, p4, ncol=2, nrow=2, common.legend = TRUE, legend="bottom")

enter image description here

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

Changing your lists to numpy arrays will do the job!!

import matplotlib.pyplot as plt
from scipy import stats
import numpy as np 

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78]) # x is a numpy array now
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,0.478,0.335,0.365,0.424,0.390,0.585,0.511]) # y is a numpy array now
xerr = [0.01]*15
yerr = [0.001]*15

plt.rc('font', family='serif', size=13)
m, b = np.polyfit(x, y, 1)
plt.plot(x,y,'s',color='#0066FF')
plt.plot(x, m*x + b, 'r-') #BREAKS ON THIS LINE
plt.errorbar(x,y,xerr=xerr,yerr=0,linestyle="None",color='black')
plt.xlabel('$\Delta t$ $(s)$',fontsize=20)
plt.ylabel('$\Delta p$ $(hPa)$',fontsize=20)
plt.autoscale(enable=True, axis=u'both', tight=False)
plt.grid(False)
plt.xlim(0.2,1.2)
plt.ylim(0,0.8)
plt.show()

enter image description here

How do I write a compareTo method which compares objects?

Listen to @milkplusvellocet, I'd recommend you to implement the Comparable interface to your class as well.

Just contributing to the answers of others:

String.compareTo() will tell you how different a string is from another.

e.g. System.out.println( "Test".compareTo("Tesu") ); will print -1 and System.out.println( "Test".compareTo("Tesa") ); will print 19

and nerdy and geeky one-line solution to this task would be:

return this.lastName.equals(s.getLastName()) ? this.lastName.compareTo(s.getLastName()) : this.firstName.compareTo(s.getFirstName());

Explanation:

this.lastName.equals(s.getLastName()) checks whether lastnames are the same or not this.lastName.compareTo(s.getLastName()) if yes, then returns comparison of last name. this.firstName.compareTo(s.getFirstName()) if not, returns the comparison of first name.

Setting selected option in laravel form

You can also try this for limited options:

          <select class="form-control required" id="assignedRole">
            <option id = "employeeRole" selected ="@if($employee->employee_role=='Employee'){'selected'}else{''} @endif">Employee</option>
            <option id = "adminRole" selected ="@if($employee->employee_role=='Admin'){'selected'}else{''} @endif">Admin</option>
            <option id = "employerRole" selected ="@if($employee->employee_role=='Employer'){'selected'}else{''} @endif">Employer</option>
          </select>

When should I use curly braces for ES6 import?

Dan Abramov's answer explains about the default exports and named exports.

Which to use?

Quoting David Herman: ECMAScript 6 favors the single/default export style, and gives the sweetest syntax to importing the default. Importing named exports can and even should be slightly less concise.

However, in TypeScript named export is favored because of refactoring. Example, if you default export a class and rename it, the class name will change only in that file and not in the other references, with named exports class name will be renamed in all the references. Named exports is also preferred for utilities.

Overall use whatever you prefer.

Additional

Default export is actually a named export with name default, so default export can be imported as:

import {default as Sample} from '../Sample.js';

install apt-get on linux Red Hat server

wget http://dag.wieers.com/packages/apt/apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

rpm -ivh apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

wget http://dag.wieers.com/packages/rpmforge-release/rpmforge-release-0.3.4-1.el4.rf.i386.rpm

rpm -Uvh rpmforge-release-0.3.4-1.el4.rf.i386.rpm

maybe some URL is broken,please research it. Enjoy~~

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

From Object Explorer in SQL Server Management Studio, find your database and expand the node (click on the + sign beside your database). The first item from that expanded tree is Database Diagrams. Right-click on that and you'll see various tasks including creating a new database diagram. If you've never created one before, it'll ask if you want to install the components for creating diagrams. Click yes then proceed.

did you specify the right host or port? error on Kubernetes

The correct answer, from all above, is to run the commands below:

sudo cp /etc/kubernetes/admin.conf $HOME/

sudo chown $(id -u):$(id -g) $HOME/admin.conf

export KUBECONFIG=$HOME/admin.conf

How to find text in a column and saving the row number where it is first found - Excel VBA

I'm not really familiar with all those parameters of the Find method; but upon shortening it, the following is working for me:

With WB.Sheets("ECM Overview")
    Set FindRow = .Range("A:A").Find(What:="ProjTemp", LookIn:=xlValues)
End With

And if you solely need the row number, you can use this after:

Dim FindRowNumber As Long
.....
FindRowNumber = FindRow.Row

Java Runtime.getRuntime(): getting output from executing a command line program

Besides using ProcessBuilder as suggested Senthil, be sure to read and implement all the recommendations of When Runtime.exec() won't.

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

I'm currently learning iOS development and going through the "Beginning iOS6 Development" book by aPress. I was getting the same error in Chapter 10:Storyboards.

It took me two days to figure it out but found out I accidentally set the TableView cell's tag to 1 when I shouldn't have. For anyone else doing this book and receive a similar error I hope this helps.

I really hope future errors in my code are easier to find! hahaha. The debug error did nothing to push me in the right direction to figuring it out (or at least I'm too new to understand the debugger, lol).

div with dynamic min-height based on browser window height

As mentioned elsewhere, the CSS function calc() can work nicely here. It is now mostly supported. You could use like:

.container
{
    min-height: 70%;
    min-height: -webkit-calc(100% - 300px);
    min-height: -moz-calc(100% - 300px);
    min-height: calc(100% - 300px);
}

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

Make cross-domain ajax JSONP request with jQuery

Try

alert(xml.Data[0].City)

Case sensitivly!

What does `dword ptr` mean?

It is a 32bit declaration. If you type at the top of an assembly file the statement [bits 32], then you don't need to type DWORD PTR. So for example:

[bits 32]
.
.
and  [ebp-4], 0

PNG transparency issue in IE8

Just want to add (since I googled for this problem, and this question popped first) IE6 and other versions render PNG transparency very ugly. If you have PNG image that is alpha transparent (32bit) and want to show it over some complex background, you can never do this simply in IE. But you can display it correctly over a single colour background as long as you set that PNG images (or divs) CSS attribute background-color to be the same as the parents background-color.

So this will render black where image should be alpha transparent, and transparent where alpha byte is 0:

<div style="background-color: white;">    
    <div style="background-image: url(image.png);"/>    
</div>

And this will render correctly (note the background-color attribute in the inner div):

<div style="background-color: white;">    
    <div style="background-color: white; background-image: url(image.png);"/>    
</div>

Complex alternative to this which enables alpha image over a complex background is to use AlphaImageLoader to load up and render image of the certain opacity. This works until you want to change that opacity... Problem in detail and its solution (javascript) can be found HERE.

Progress Bar with HTML and CSS

In modern browsers you could use a CSS3 & HTML5 progress Element!

_x000D_
_x000D_
progress {_x000D_
  width: 40%;_x000D_
  display: block; /* default: inline-block */_x000D_
  margin: 2em auto;_x000D_
  padding: 3px;_x000D_
  border: 0 none;_x000D_
  background: #444;_x000D_
  border-radius: 14px;_x000D_
}_x000D_
progress::-moz-progress-bar {_x000D_
  border-radius: 12px;_x000D_
  background: orange;_x000D_
_x000D_
}_x000D_
/* webkit */_x000D_
@media screen and (-webkit-min-device-pixel-ratio:0) {_x000D_
  progress {_x000D_
    height: 25px;_x000D_
  }_x000D_
}_x000D_
progress::-webkit-progress-bar {_x000D_
    background: transparent;_x000D_
}  _x000D_
progress::-webkit-progress-value {  _x000D_
  border-radius: 12px;_x000D_
  background: orange;_x000D_
} 
_x000D_
<progress max="100" value="40"></progress>
_x000D_
_x000D_
_x000D_

R apply function with multiple parameters

If your function have two vector variables and must compute itself on each value of them (as mentioned by @Ari B. Friedman) you can use mapply as follows:

vars1<-c(1,2,3)
vars2<-c(10,20,30)
mult_one<-function(var1,var2)
{
   var1*var2
}
mapply(mult_one,vars1,vars2)

which gives you:

> mapply(mult_one,vars1,vars2)
[1] 10 40 90

Get current date/time in seconds

 Date.now()

gives milliseconds since epoch. No need to use new.

Check out the reference here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now

(Not supported in IE8.)

Move SQL Server 2008 database files to a new folder location

You forgot to mention the name of your database (is it "my"?).

ALTER DATABASE my SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

ALTER DATABASE my SET OFFLINE;

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Data,
   Filename = 'D:\DATA\my.MDF'
);

ALTER DATABASE my MODIFY FILE 
(
   Name = my_Log, 
   Filename = 'D:\DATA\my_1.LDF'
);

Now here you must manually move the files from their current location to D:\Data\ (and remember to rename them manually if you changed them in the MODIFY FILE command) ... then you can bring the database back online:

ALTER DATABASE my SET ONLINE;

ALTER DATABASE my SET MULTI_USER;

This assumes that the SQL Server service account has sufficient privileges on the D:\Data\ folder. If not you will receive errors at the SET ONLINE command.

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

Sorry this is and old thread but some people would still need this I guess,

Note: I achieved this using Animate.css library for animating the fade.

I used your code and just added .hidden class (using bootstrap's hidden class) but you can still just define .hidden { opacity: 0; }

$(document).ready(function() {

/* Every time the window is scrolled ... */

$(window).scroll( function(){

/* Check the location of each desired element */
$('.hideme').each( function(i){

    var bottom_of_object = $(this).position().top + $(this).outerHeight();
    var bottom_of_window = $(window).scrollTop() + $(window).height();


    /* If the object is completely visible in the window, fade it it */
    if( bottom_of_window > bottom_of_object ){

        $(this).removeClass('hidden');
        $(this).addClass('animated fadeInUp');
    }    else {
            $(this).addClass('hidden');
               }

}); 
}); 
});

Another Note: Applying this to containers might cause it to be glitchy.

How to add java plugin for Firefox on Linux?

you should add plug in to your local setting of firefox in your user home

 vladimir@shinsengumi ~/.mozilla/plugins $ pwd
 /home/vladimir/.mozilla/plugins 
 vladimir@shinsengumi ~/.mozilla/plugins $ ls -ltr
 lrwxrwxrwx 1 vladimir vladimir 60 Jan  1 23:06 libnpjp2.so -> /home/vladimir/Install/jdk1.6.0_32/jre/lib/amd64/libnpjp2.so

Need to get a string after a "word" in a string in c#

string originalSting = "This is my string";
string texttobesearched = "my";
string dataAfterTextTobeSearch= finalCommand.Split(new string[] { texttobesearched     }, StringSplitOptions.None).Last();
if(dataAfterTextobeSearch!=originalSting)
{
    //your action here if data is found
}
else
{
    //action if the data being searched was not found
}

Convert a char to upper case using regular expressions (EditPad Pro)

You can also capitalize the first letter of the match using \I1 and \I2 etc instead of $1 and $2.

How does one capture a Mac's command key via JavaScript?

Here is how I did it in AngularJS

app = angular.module('MM_Graph')

class Keyboard
  constructor: ($injector)->
    @.$injector  = $injector
    @.$window    = @.$injector.get('$window')                             # get reference to $window and $rootScope objects
    @.$rootScope = @.$injector.get('$rootScope')

  on_Key_Down:($event)=>
    @.$rootScope.$broadcast 'keydown', $event                             # broadcast a global keydown event

    if $event.code is 'KeyS' and ($event.ctrlKey or $event.metaKey)       # detect S key pressed and either OSX Command or Window's Control keys pressed
      @.$rootScope.$broadcast '', $event                                  # broadcast keyup_CtrS event
      #$event.preventDefault()                                             # this should be used by the event listeners to prevent default browser behaviour

  setup_Hooks: ()=>
    angular.element(@.$window).bind "keydown", @.on_Key_Down              # hook keydown event in window (only called once per app load)
    @

app.service 'keyboard', ($injector)=>
  return new Keyboard($injector).setup_Hooks()

How to round a number to significant figures in Python

I modified indgar's solution to handle negative numbers and small numbers (including zero).

from math import log10, floor
def round_sig(x, sig=6, small_value=1.0e-9):
    return round(x, sig - int(floor(log10(max(abs(x), abs(small_value))))) - 1)

Transfer data between iOS and Android via Bluetooth?

You could use p2pkit, or the free solution it was based on: https://github.com/GitGarage. Doesn't work very well, and its a fixer-upper for sure, but its, well, free. Works for small amounts of data transfer right now.

How to use a RELATIVE path with AuthUserFile in htaccess?

I know this is an old question, but I just searched for the same thing and probably there are many others searching for a quick, mobile solution. Here is what I finally come up with:

# We set production environment by default
SetEnv PROD_ENV 1

<IfDefine DEV_ENV>
  # If 'DEV_ENV' has been defined, then unset the PROD_ENV
  UnsetEnv PROD_ENV

  AuthType Basic
  AuthName "Protected Area"
  AuthUserFile /var/www/foo.local/.htpasswd
  Require valid-user
</IfDefine>

<IfDefine PROD_ENV>
  AuthType Basic
  AuthName "Protected Area"
  AuthUserFile /home/foo/public_html/.htpasswd
  Require valid-user
</IfDefine>

Pretty-print a Map in Java

When I have org.json.JSONObject in the classpath, I do:

Map<String, Object> stats = ...;
System.out.println(new JSONObject(stats).toString(2));

(this beautifully indents lists, sets and maps which may be nested)

How do I display the current value of an Android Preference in the Preference summary?

According to Android docs you can use app:useSimpleSummaryProvider="true" in ListPreference and EditTextPreference components.

DbEntityValidationException - How can I easily tell what caused the error?

Actually, this is just the validation issue, EF will validate the entity properties first before making any changes to the database. So, EF will check whether the property's value is out of range, like when you designed the table. Table_Column_UserName is varchar(20). But, in EF, you entered a value that longer than 20. Or, in other cases, if the column does not allow to be a Null. So, in the validation process, you have to set a value to the not null column, no matter whether you are going to make the change on it. I personally, like the Leniel Macaferi answer. It can show you the detail of the validation issues

Directly export a query to CSV using SQL Developer

You can use the spool command (SQL*Plus documentation, but one of many such commands SQL Developer also supports) to write results straight to disk. Each spool can change the file that's being written to, so you can have several queries writing to different files just by putting spool commands between them:

spool "\path\to\spool1.txt"

select /*csv*/ * from employees;

spool "\path\to\spool2.txt"

select /*csv*/ * from locations;

spool off;

You'd need to run this as a script (F5, or the second button on the command bar above the SQL Worksheet). You might also want to explore some of the formatting options and the set command, though some of those do not translate to SQL Developer.

Since you mentioned CSV in the title I've included a SQL Developer-specific hint that does that formatting for you.

A downside though is that SQL Developer includes the query in the spool file, which you can avoid by having the commands and queries in a script file that you then run as a script.

Center/Set Zoom of Map to cover all visible Markers?

There is this MarkerClusterer client side utility available for google Map as specified here on Google Map developer Articles, here is brief on what's it's usage:

There are many approaches for doing what you asked for:

  • Grid based clustering
  • Distance based clustering
  • Viewport Marker Management
  • Fusion Tables
  • Marker Clusterer
  • MarkerManager

You can read about them on the provided link above.

Marker Clusterer uses Grid Based Clustering to cluster all the marker wishing the grid. Grid-based clustering works by dividing the map into squares of a certain size (the size changes at each zoom) and then grouping the markers into each grid square.

Before Clustering Before Clustering

After Clustering After Clustering

I hope this is what you were looking for & this will solve your problem :)

Multiple values in single-value context

No, but that is a good thing since you should always handle your errors.

There are techniques that you can employ to defer error handling, see Errors are values by Rob Pike.

ew := &errWriter{w: fd}
ew.write(p0[a:b])
ew.write(p1[c:d])
ew.write(p2[e:f])
// and so on
if ew.err != nil {
    return ew.err
}

In this example from the blog post he illustrates how you could create an errWriter type that defers error handling till you are done calling write.

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

Adding this answer partially because it fixed my problem of the same issue and so I can bookmark this question myself.

I was able to fix it by doing the following:

sudo apt-get install gcc-multilib g++-multilib

If you've installed a version of gcc / g++ that doesn't ship by default (such as g++-4.8 on lucid) you'll want to match the version as well:

sudo apt-get install gcc-4.8-multilib g++-4.8-multilib

JQuery select2 set default value from an option in list?

For ajax select2 multiple select dropdown i did like this;

  //preset element values
  //topics is an array of format [{"id":"","text":""}, .....]
        $(id).val(topics);
          setTimeout(function(){
           ajaxTopicDropdown(id,
                2,location.origin+"/api for gettings topics/",
                "Pick a topic", true, 5);                      
            },1);
        // ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

How does DISTINCT work when using JPA and Hibernate

Update: See the top-voted answer please.

My own is currently obsolete. Only kept here for historical reasons.


Distinct in HQL is usually needed in Joins and not in simple examples like your own.

See also How do you create a Distinct query in HQL

Get current value selected in dropdown using jQuery

This is what you need :)

$('._someDropDown').live('change', function(e) {
    console.log(e.target.options[e.target.selectedIndex].text);
});

For new jQuery use on

$(document).on('change', '._someDropDown', function(e) {
    console.log(this.options[e.target.selectedIndex].text);
});

Run parallel multiple commands at once in the same terminal

This bash script is for N parallel threads. Each argument is a command.

trap will kill all subprocesses when SIGINT is catched.
wait $PID_LIST is waiting each process to complete. When all processes have completed, the program exits.

#!/bin/bash

for cmd in "$@"; do {
  echo "Process \"$cmd\" started";
  $cmd & pid=$!
  PID_LIST+=" $pid";
} done

trap "kill $PID_LIST" SIGINT

echo "Parallel processes have started";

wait $PID_LIST

echo
echo "All processes have completed";

Save this script as parallel_commands and make it executable.
This is how to use this script:

parallel_commands "cmd arg0 arg1 arg2" "other_cmd arg0 arg2 arg3"

Example:

parallel_commands "sleep 1" "sleep 2" "sleep 3" "sleep 4"

Start 4 parallel sleep and waits until "sleep 4" finishes.

Git pull till a particular commit

I've found the updated answer from this video, the accepted answer didn't work for me.

First clone the latest repo from git (if haven't) using git clone <HTTPs link of the project> (or using SSH) then go to the desire branch using git checkout <branch name> .

Use the command

git log

to check the latest commits. Copy the shal of the particular commit. Then use the command

git fetch origin <Copy paste the shal here>

After pressing enter key. Now use the command

git checkout FETCH_HEAD

Now the particular commit will be available to your local. Change anything and push the code using git push origin <branch name> . That's all. Check the video for reference.