Programs & Examples On #Libgcj

Ambiguous overload call to abs(double)

Its boils down to this: math.h is from C and was created over 10 years ago. In math.h, due to its primitive nature, the abs() function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs(). When C++ was created it took math.h and made it cmath. cmath is essentially math.h but improved for C++. It improved things like having to distinguish between fabs() and abs, and just made abs() for both doubles and integer types. In summary either: Use math.h and use abs() for integers, fabs() for doubles or use cmath and just have abs for everything (easier and recommended)

Hope this helps anyone who is having the same problem!

Best C++ IDE or Editor for Windows

How about CodeBlocks, i find it so fine with me, especially the new 10.05 version.

How to create a jQuery function (a new jQuery method or plugin)?

Yup — what you’re describing is a jQuery plugin.

To write a jQuery plugin, you create a function in JavaScript, and assign it to a property on the object jQuery.fn.

E.g.

jQuery.fn.myfunction = function(param) {
    // Some code
}

Within your plugin function, the this keyword is set to the jQuery object on which your plugin was invoked. So, when you do:

$('#my_div').myfunction()

Then this inside myfunction will be set to the jQuery object returned by $('#my_div').

See http://docs.jquery.com/Plugins/Authoring for the full story.

Force "portrait" orientation mode

Note that

android:screenOrientation="portrait"     
android:configChanges="orientation|keyboardHidden"

is added in the manifest file - where the activity is defined.

UML diagram shapes missing on Visio 2013

If you don't find Stencils you can locate them in your install location. C:\Program Files\Microsoft Office\Office15\Visio Content\1033 for UML Sequcen Stencies you can open

C# how to use enum with switch

Since C# 8.0 introduced a new switch expression for enums you can do it even more elegant:

public double Calculate(int left, int right, Operator op) =>
            op switch 
        {
            Operator.PLUS => left + right,
            Operator.MINUS => left - right,
            Operator.MULTIPLY => left * right,
            Operator.DIVIDE => left / right,
            _    =>  0
        }

Ref. https://docs.microsoft.com/en-us/dotnet/csharp/whats-new/csharp-8

How can I add a string to the end of each line in Vim?

If u want to add Hello world at the end of each line:

:%s/$/HelloWorld/

If you want to do this for specific number of line say, from 20 to 30 use:

:20,30s/$/HelloWorld/

If u want to do this at start of each line then use:

:20,30s/^/HelloWorld/

How to retrieve a single file from a specific revision in Git?

Get the file from a previous commit through checking-out previous commit and copying file.

  • Note which branch you are on: git branch
  • Checkout the previous commit you want: git checkout 27cf8e84bb88e24ae4b4b3df2b77aab91a3735d8
  • Copy the file you want to a temporary location
  • Checkout the branch you started from: git checkout theBranchYouNoted
  • Copy in the file you placed in a temporary location
  • Commit your change to git: git commit -m "added file ?? from previous commit"

Config Error: This configuration section cannot be used at this path

I ran these two commands from an elevated command prompt:

%windir%/system32/inetsrv/appcmd unlock config /section:anonymousAuthentication

%windir%/system32/inetsrv/appcmd unlock config /section:windowsAuthentication

SQL statement to select all rows from previous day

Can't test it right now, but:

select * from tablename where date >= dateadd(day, datediff(day, 1, getdate()), 0) and date < dateadd(day, datediff(day, 0, getdate()), 0)

How to concat string + i?

You can concatenate strings using strcat. If you plan on concatenating numbers as strings, you must first use num2str to convert the numbers to strings.

Also, strings can't be stored in a vector or matrix, so f must be defined as a cell array, and must be indexed using { and } (instead of normal round brackets).

f = cell(N, 1);
for i=1:N
   f{i} = strcat('f', num2str(i));
end

Requested registry access is not allowed

As a temporary fix, users can right click the utility and select "Run as administrator."

Remove a fixed prefix/suffix from a string in Bash

Do you know the length of your prefix and suffix? In your case:

result=$(echo $string | cut -c5- | rev | cut -c3- | rev)

Or more general:

result=$(echo $string | cut -c$((${#prefix}+1))- | rev | cut -c$((${#suffix}+1))- | rev)

But the solution from Adrian Frühwirth is way cool! I didn't know about that!

Finding the type of an object in C++

Use overloaded functions. Does not require dynamic_cast or even RTTI support:

class A {};
class B : public A {};

class Foo {
public:
    void Bar(A& a) {
        // do something
    }
    void Bar(B& b) {
        Bar(static_cast<A&>(b));
        // do B specific stuff
    }
};

Windows task scheduler error 101 launch failure code 2147943785

The user that is configured to run this scheduled task must have "Log on as a batch job" rights on the computer that hosts the exe you are launching. This can be configured on the local security policy of the computer that hosts the exe. You can change the policy (on the server hosting the exe) under

Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment -> Log On As Batch Job

Add your user to this list (you could also make the user account a local admin on the machine hosting the exe).

Finally, you could also simply copy your exe from the network location to your local computer and run it from there instead.

Note also that a domain policy could be restricting "Log on as a batch job" rights at your organization.

Get the date (a day before current time) in Bash

date +%Y:%m:%d|awk -vFS=":" -vOFS=":" '{$3=$3-1;print}'
2009:11:9

How to remove a build from itunes connect?

In our case, deletion was not possible due to already having an app that we were in pre-release. The fix was not to delete but rather to edit each section, including version number, that needed to change for the new candidate.

Vertical and horizontal align (middle and center) with CSS

There are many methods :

  1. Center horizontal and vertical align of an element with fixed measure

CSS

 <div style="width:200px;height:100px;position:absolute;left:50%;top:50%;
margin-left:-100px;margin-top:-50px;">
<!–content–>
</div> 

2 . Center horizontally and vertically a single line of text

CSS

<div style="width:400px;height:200px;text-align:center;line-height:200px;">
<!–content–>
</div>  

3 . Center horizontal and vertical align of an element with no specific measure

CSS

<div style="display:table;height:300px;text-align:center;">
<div style="display:table-cell;vertical-align:middle;">
<!–content–>
</div>
</div>  

Split string with JavaScript

var wrapper = $(document.body);

strings = [
    "19 51 2.108997",
    "20 47 2.1089"
];

$.each(strings, function(key, value) {
    var tmp = value.split(" ");
    $.each([
        tmp[0] + " " + tmp[1],
        tmp[2]
    ], function(key, value) {
        $("<span>" + value + "</span>").appendTo(wrapper);
    }); 
});

Getting the actual usedrange

Readify made a very complete answer. Yet, I wanted to add the End statement, you can use:

Find the last used cell, before a blank in a Column:

Sub LastCellBeforeBlankInColumn()
Range("A1").End(xldown).Select
End Sub

Find the very last used cell in a Column:

Sub LastCellInColumn()
Range("A" & Rows.Count).End(xlup).Select
End Sub

Find the last cell, before a blank in a Row:

Sub LastCellBeforeBlankInRow()
Range("A1").End(xlToRight).Select
End Sub

Find the very last used cell in a Row:

Sub LastCellInRow()
Range("IV1").End(xlToLeft).Select
End Sub

See here for more information (and the explanation why xlCellTypeLastCell is not very reliable).

Android ListView headers

What I did to make the Date (e.g December 01, 2016) as header. I used the StickyHeaderListView library

https://github.com/emilsjolander/StickyListHeaders

Convert the date to long in millis [do not include the time] and make it as the header Id.

@Override
public long getHeaderId(int position) {
    return <date in millis>;
}

How to "properly" create a custom object in JavaScript?

Douglas Crockford discusses that topic extensively in The Good Parts. He recommends to avoid the new operator to create new objects. Instead he proposes to create customized constructors. For instance:

var mammal = function (spec) {     
   var that = {}; 
   that.get_name = function (  ) { 
      return spec.name; 
   }; 
   that.says = function (  ) { 
      return spec.saying || ''; 
   }; 
   return that; 
}; 

var myMammal = mammal({name: 'Herb'});

In Javascript a function is an object, and can be used to construct objects out of together with the new operator. By convention, functions intended to be used as constructors start with a capital letter. You often see things like:

function Person() {
   this.name = "John";
   return this;
}

var person = new Person();
alert("name: " + person.name);**

In case you forget to use the new operator while instantiating a new object, what you get is an ordinary function call, and this is bound to the global object instead to the new object.

Appending the same string to a list of strings in Python

new_list = [word_in_list + end_string for word_in_list in old_list]

Using names such as "list" for your variable names is bad since it will overwrite/override the builtins.

Passing 'this' to an onclick event

Yeah first method will work on any element called from elsewhere since it will always take the target element irrespective of id.

check this fiddle

http://jsfiddle.net/8cvBM/

Xcode couldn't find any provisioning profiles matching

You can get this issue if Apple update their terms. Simply log into your dev account and accept any updated terms and you should be good (you will need to goto Xcode -> project->signing and capabilities and retry the certificate check. This should get you going if terms are the issue.

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

The Android Studio website has recently (I think) provided some advice what kind of messages to expect from different log levels that may be useful along with Kurtis' answer:

  • Verbose - Show all log messages (the default).
  • Debug - Show debug log messages that are useful during development only, as well as the message levels lower in this list.
  • Info - Show expected log messages for regular usage, as well as the message levels lower in this list.
  • Warn - Show possible issues that are not yet errors, as well as the message levels lower in this list.
  • Error - Show issues that have caused errors, as well as the message level lower in this list.
  • Assert - Show issues that the developer expects should never happen.

Where is the Docker daemon log?

Also you can see logs by this command:

docker service ps --no-trunc {serviceName}

Get all table names of a particular database by SQL query?

In order if someone would like to list all tables within specific database without using the "use" keyword:

SELECT TABLE_NAME FROM databasename.INFORMATION_SCHEMA.TABLES

How can I display a tooltip message on hover using jQuery?

take a look at the jQuery Tooltip plugin. You can pass in an options object for different options.

There are also other alternative tooltip plugins available, of which a few are

Take look at the demos and documentation and please update your question if you have specific questions about how to use them in your code.

Lambda function in list comprehensions

The first one

f = lambda x: x*x
[f(x) for x in range(10)]

runs f() for each value in the range so it does f(x) for each value

the second one

[lambda x: x*x for x in range(10)]

runs the lambda for each value in the list, so it generates all of those functions.

Use RSA private key to generate public key?

here in this code first we are creating RSA key which is private but it has pair of its public key as well so to get your actual public key we simply do this

openssl rsa -in mykey.pem -pubout > mykey.pub

hope you get it for more info check this

How to get EditText value and display it on screen through TextView?

in "String.xml" you can notice any String or value you want to use, here are two examples:

<string name="app_name">My Calculator App
    </string>
<color name="color_menu_home">#ffcccccc</color>

Used for the layout.xml: android:text="@string/app_name"

The advantage: you can use them as often you want, you only need to link them in your Layout-xml, and you can change the String-Content easily in the strings.xml, without searching in your source-code for the right position. Important for changing language, you only need to replace the strings.xml - file

$(document).ready shorthand

What about this?

(function($) { 
   $(function() {
     // more code using $ as alias to jQuery
     // will be fired when document is ready
   });
})(jQuery);

Python multiprocessing PicklingError: Can't pickle <type 'function'>

When this problem comes up with multiprocessing a simple solution is to switch from Pool to ThreadPool. This can be done with no change of code other than the import-

from multiprocessing.pool import ThreadPool as Pool

This works because ThreadPool shares memory with the main thread, rather than creating a new process- this means that pickling is not required.

The downside to this method is that python isn't the greatest language with handling threads- it uses something called the Global Interpreter Lock to stay thread safe, which can slow down some use cases here. However, if you're primarily interacting with other systems (running HTTP commands, talking with a database, writing to filesystems) then your code is likely not bound by CPU and won't take much of a hit. In fact I've found when writing HTTP/HTTPS benchmarks that the threaded model used here has less overhead and delays, as the overhead from creating new processes is much higher than the overhead for creating new threads.

So if you're processing a ton of stuff in python userspace this might not be the best method.

Retrieve a Fragment from a ViewPager

This is based on Steven's answer above. This will return actual instance of the fragment which is already attached to the parent activity.

FragmentPagerAdapter fragmentPagerAdapter = (FragmentPagerAdapter) mViewPager.getAdapter();
    for(int i = 0; i < fragmentPagerAdapter.getCount(); i++) {

        Fragment viewPagerFragment = (Fragment) mViewPager.getAdapter().instantiateItem(mViewPager, i);
        if(viewPagerFragment != null && viewPagerFragment.isAdded()) {

            if (viewPagerFragment instanceof FragmentOne){
                FragmentOne oneFragment = (FragmentOne) viewPagerFragment;
                if (oneFragment != null){
                    oneFragment.update(); // your custom method
                }
            } else if (viewPagerFragment instanceof FragmentTwo){
                FragmentTwo twoFragment = (FragmentTwo) viewPagerFragment;

                if (twoFragment != null){
                    twoFragment.update(); // your custom method
                }
            }
        }
    }

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

define() vs. const

Yes, const are defined at compile-time and as nikic states cannot be assigned an expression, as define()'s can. But also const's cannot be conditionally declared (for the same reason). ie. You cannot do this:

if (/* some condition */) {
  const WHIZZ = true;  // CANNOT DO THIS!
}

Whereas you could with a define(). So, it doesn't really come down to personal preference, there is a correct and a wrong way to use both.

As an aside... I would like to see some kind of class const that can be assigned an expression, a sort of define() that can be isolated to classes?

Python if-else short-hand

The most readable way is

x = 10 if a > b else 11

but you can use and and or, too:

x = a > b and 10 or 11

The "Zen of Python" says that "readability counts", though, so go for the first way.

Also, the and-or trick will fail if you put a variable instead of 10 and it evaluates to False.

However, if more than the assignment depends on this condition, it will be more readable to write it as you have:

if A[i] > B[j]:
  x = A[i]
  i += 1
else:
  x = A[j]
  j += 1

unless you put i and j in a container. But if you show us why you need it, it may well turn out that you don't.

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I would change the query in the following ways:

  1. Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the group by.
  2. Combine the second and third subqueries. They are aggregating on the same column. This requires using a left outer join to ensure that all data is available.
  3. By using count(<fieldname>) you can eliminate the comparisons to is null. This is important for the second and third calculated values.
  4. To combine the second and third queries, it needs to count an id from the mde table. These use mde.mdeid.

The following version follows your example by using union all:

SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
       SUM(TOTALMAILED) as TotalMailed,
       SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
       SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
              NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract
       where SentDate is not null
       group by SentDate
      ) union all
      (select MDE.ReturnMailDate AS ReceiptDate, 0,
              COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
              SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract MDE left outer join
            DTSharedData.dbo.ScanData SD
            ON SD.ScanDataID = MDE.ReturnScanDataID
       group by MDE.ReturnMailDate;
      )
     ) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;

The following does something similar using full outer join:

SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
       sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
       mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
      from MailDataExtract
      where SentDate is not null
      group by cast(SentDate as date)
     ) sd full outer join
    (select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
            COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
            SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
     from MailDataExtract MDE left outer join
          DTSharedData.dbo.ScanData SD
          ON SD.ScanDataID = MDE.ReturnScanDataID
     group by cast(MDE.ReturnMailDate as date)
    ) mde
    on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;

change image opacity using javascript

Supposing you're using plain JS (see other answers for jQuery), to change an element's opacity, write:

var element = document.getElementById('id');
element.style.opacity = "0.9";
element.style.filter  = 'alpha(opacity=90)'; // IE fallback

Removing element from array in component state

You could make the code more readable with a one line helper function:

const removeElement = (arr, i) => [...arr.slice(0, i), ...arr.slice(i+1)];

then use it like so:

this.setState(state => ({ places: removeElement(state.places, index) }));

How can I order a List<string>?

Other answers are correct to suggest Sort, but they seem to have missed the fact that the storage location is typed as IList<string. Sort is not part of the interface.

If you know that ListaServizi will always contain a List<string>, you can either change its declared type, or use a cast. If you're not sure, you can test the type:

if (typeof(List<string>).IsAssignableFrom(ListaServizi.GetType()))
    ((List<string>)ListaServizi).Sort();
else
{
    //... some other solution; there are a few to choose from.
}

Perhaps more idiomatic:

List<string> typeCheck = ListaServizi as List<string>;
if (typeCheck != null)
    typeCheck.Sort();
else
{
    //... some other solution; there are a few to choose from.
}

If you know that ListaServizi will sometimes hold a different implementation of IList<string>, leave a comment, and I'll add a suggestion or two for sorting it.

Changing image sizes proportionally using CSS?

if you know the spect ratio you can use padding-bottom with percentage to set the hight depending on with of the diff.

<div>
   <div style="padding-bottom: 33%;">
      i have 33% height of my parents width
   </div>
</div>

How to delete duplicate rows in SQL Server?

-- this query will keep only one instance of a duplicate record.
;WITH cte
     AS (SELECT ROW_NUMBER() OVER (PARTITION BY col1, col2, col3-- based on what? --can be multiple columns
                                       ORDER BY ( SELECT 0)) RN
         FROM   Mytable)



delete  FROM cte
WHERE  RN > 1

Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."

Whenever got error -1005 then need to call API Again.

AFHTTPRequestOperationManager *manager = 
[AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:policy];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

[manager POST:<example-url>
   parameters:<parameteres>
    success:^(AFHTTPRequestOperation *operation, id responseObject) {
      NSLog(@“Success: %@", responseObject);
  } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      NSLog(@"Error: %@", error);
      if (error.code == -1005) {
          // Call method again... 
       }
  }];

You need to Add your code to call function again. MakeSure that you were call method once otherwise its call recursive loop.

Excel formula to get cell color

Anticipating that I already had the answer, which is that there is no built-in worksheet function that returns the background color of a cell, I decided to review this article, in case I was wrong. I was amused to notice a citation to the very same MVP article that I used in the course of my ongoing research into colors in Microsoft Excel.

While I agree that, in the purest sense, color is not data, it is meta-data, and it has uses as such. To that end, I shall attempt to develop a function that returns the color of a cell. If I succeed, I plan to put it into an add-in, so that I can use it in any workbook, where it will join a growing legion of other functions that I think Microsoft left out of the product.

Regardless, IMO, the ColorIndex property is virtually useless, since there is essentially no connection between color indexes and the colors that can be selected in the standard foreground and background color pickers. See Color Combinations: Working with Colors in Microsoft Office and the associated binary workbook, Color_Combinations Workbook.

Makefile: How to correctly include header file and its directory?

These lines in your makefile,

INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)
DEPS = split.h

and this line in your .cpp file,

#include "StdCUtil/split.h"

are in conflict.

With your makefile in your source directory and with that -I option you should be using #include "split.h" in your source file, and your dependency should be ../StdCUtil/split.h.

Another option:

INC_DIR = ../StdCUtil
CFLAGS=-c -Wall -I$(INC_DIR)/..  # Ugly!
DEPS = $(INC_DIR)/split.h

With this your #include directive would remain as #include "StdCUtil/split.h".

Yet another option is to place your makefile in the parent directory:

root
  |____Makefile
  |
  |___Core
  |     |____DBC.cpp
  |     |____Lock.cpp
  |     |____Trace.cpp
  |
  |___StdCUtil
        |___split.h

With this layout it is common to put the object files (and possibly the executable) in a subdirectory that is parallel to your Core and StdCUtil directories. Object, for example. With this, your makefile becomes:

INC_DIR = StdCUtil
SRC_DIR = Core
OBJ_DIR = Object
CFLAGS  = -c -Wall -I.
SRCS = $(SRC_DIR)/Lock.cpp $(SRC_DIR)/DBC.cpp $(SRC_DIR)/Trace.cpp
OBJS = $(OBJ_DIR)/Lock.o $(OBJ_DIR)/DBC.o $(OBJ_DIR)/Trace.o
# Note: The above will soon get unwieldy.
# The wildcard and patsubt commands will come to your rescue.

DEPS = $(INC_DIR)/split.h
# Note: The above will soon get unwieldy.
# You will soon want to use an automatic dependency generator.


all: $(OBJS)

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
  $(CC) $(CFLAGS) -c $< -o $@

$(OBJ_DIR)/Trace.o: $(DEPS)

How to revert to origin's master branch's version of file

Assuming you did not commit the file, or add it to the index, then:

git checkout -- filename

Assuming you added it to the index, but did not commit it, then:

git reset HEAD filename
git checkout -- filename

Assuming you did commit it, then:

git checkout origin/master filename

Assuming you want to blow away all commits from your branch (VERY DESTRUCTIVE):

git reset --hard origin/master

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

Unable to set default python version to python3 in ubuntu

At first, Make sure Python3 is installed on your computer

Go to your terminal and type:

cd ~/ to go to your home directory

If you didn't set up your .bash_profile yet, type touch .bash_profile to create your .bash_profile.

Or, type open -e .bash_profile to edit the file.

Copy and save alias python=python3 in the .bash_profile.

Close and reopen your Terminal. Then type the following command to check if Python3 is your default version now:

python --version

You should see python 3.x.y is your default version.

Cheers!

How to execute my SQL query in CodeIgniter

$this->db->select('id, name, price, author, category, language, ISBN, publish_date');

       $this->db->from('tbl_books');

Finding an item in a List<> using C#

var myItem = myList.Find(item => item.property == "something");

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

For plain ASP.NET MVC Controllers

Create a new attribute

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

Tag your action:

[AllowCrossSiteJson]
public ActionResult YourMethod()
{
    return Json("Works better?");
}

For ASP.NET Web API

using System;
using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

Tag a whole API controller:

[AllowCrossSiteJson]
public class ValuesController : ApiController
{

Or individual API calls:

[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
    ...
}

For Internet Explorer <= v9

IE <= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).

Download it using nuget corsproxy and follow the included instructions.

Blog post | Source code

Trim a string based on the string length

Or you can just use this method in case you don't have StringUtils on hand:

public static String abbreviateString(String input, int maxLength) {
    if (input.length() <= maxLength) 
        return input;
    else 
        return input.substring(0, maxLength-2) + "..";
}

Precision String Format Specifier In Swift

A version of Vincent Guerci's ruby / python % operator, updated for Swift 2.1:

func %(format:String, args:[CVarArgType]) -> String {
  return String(format:format, arguments:args)
}

"Hello %@, This is pi : %.2f" % ["World", M_PI]

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

This error occurs when the project you are running is not an angular project. Though you have downloaded an angular project but have not installed all the dependencies thats why the ng serve command is not available to you.

Just navigate to the path where the project is stored and use the command

npm install

(Note - Node.js should be installed in your system and if you are using Angular 2 or above angular cli should also be installed in your system before you run this command. To check if the node.js is installed n your system 1) Open cmd (any path- as node should be globally installed in your system) 2) use command

node -v
npm -v

to get node and npm version)

One more important thing: The angular cli version won't make a difference if the version installed in your system is higher than the version required by the project. It will give a warning but you can ignore the warning.

How to convert java.lang.Object to ArrayList?

I hope this will be help you

import java.util.ArrayList; 
public class Demo {

 public static void main(String[] args) {
    Object obj2 =null;
    ArrayList al1 = (ArrayList) obj2;
    al1 = (ArrayList) obj2;
    System.out.println("List2 Value: " + al1);
    }
 }

obj2 Object is default null before you cast it to ArrayList. That's why print 'al1' as null.

How do I use tools:overrideLibrary in a build.gradle file?

As soulution for all libraries we can match sdk version of them so no unexpected event may happen

subprojects { 
afterEvaluate {project -> 
    if (project.hasProperty("android")) { 
        android { 
            compileSdkVersion 28 
            buildToolsVersion '28.0.3'
            defaultConfig {
                //It's kinda tricking android studio but anyway it works
                minSdkVersion 17
            }
        } 
    } 
    if (project.hasProperty("dependencies")) {
        dependencies {
            implementation 'com.android.support:support-core-utils:28.0.0'
            implementation 'com.android.support:appcompat-v7:28.0.0'
            implementation 'com.google.android.gms:play-services-base:16.1.0'
        }
    }
} 
}

Remove libraries that you do not use in your project (gms) and make sure that sdk version matches your app level gradle data

How to open CSV file in R when R says "no such file or directory"?

  1. Kindly check whether the file name has an extension for example:

    abc.csv
    

    if so remove the .csv extension.

  2. set wd to the folder containing the file (~)

  3. data<-read.csv("abc.csv")

Your data has been read the data object

Selecting a row in DataGridView programmatically

Try This:

datagridview.Rows[currentRow].Cells[0];

Why is my JQuery selector returning a n.fn.init[0], and what is it?

Here is how to do a quick check to see if n.fn.init[0] is caused by your DOM-elements not loading in time. Delay your selector function by wrapping it in setTimeout function like this:

function timeout(){ 

    ...your selector function that returns n.fn.init[0] goes here...

}

setTimeout(timeout, 5000)

This will cause your selector function to execute with a 5 second delay, which should be enough for pretty much anything to load.

This is just a coarse hack to check if DOM is ready for your selector function or not. This is not a (permanent) solution.

The preferred ways to check if the DOM is loaded before executing your function are as follows:

1) Wrap your selector function in

$(document).ready(function(){  ... your selector function...  };

2) If that doesn't work, use DOMContentLoaded

3) Try window.onload, which waits for all the images to load first, so its least preferred

window.onload = function () {  ... your selector function...  }

4) If you are waiting for a library to load that loads in several steps or has some sort of delay of its own, then you might need some complicated custom solution. This is what happened to me with "MathJax" library. This question discusses how to check when MathJax library loaded its DOM elements, if it is of any help.

5) Finally, you can stick with hard-coded setTimeout function, making it maybe 1-3 seconds. This is actually the very least preferred method in my opinion.

This list of fixes is probably far from perfect so everyone is welcome to edit it.

Best way to parse command-line parameters?

Here is mine 1-liner

    def optArg(prefix: String) = args.drop(3).find { _.startsWith(prefix) }.map{_.replaceFirst(prefix, "")}
    def optSpecified(prefix: String) = optArg(prefix) != None
    def optInt(prefix: String, default: Int) = optArg(prefix).map(_.toInt).getOrElse(default)

It drops 3 mandatory arguments and gives out the options. Integers are specified like notorious -Xmx<size> java option, jointly with the prefix. You can parse binaries and integers as simple as

val cacheEnabled = optSpecified("cacheOff")
val memSize = optInt("-Xmx", 1000)

No need to import anything.

how to transfer a file through SFTP in java?

Try this code.

public void send (String fileName) {
    String SFTPHOST = "host:IP";
    int SFTPPORT = 22;
    String SFTPUSER = "username";
    String SFTPPASS = "password";
    String SFTPWORKINGDIR = "file/to/transfer";

    Session session = null;
    Channel channel = null;
    ChannelSftp channelSftp = null;
    System.out.println("preparing the host information for sftp.");

    try {
        JSch jsch = new JSch();
        session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
        session.setPassword(SFTPPASS);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.connect();
        System.out.println("Host connected.");
        channel = session.openChannel("sftp");
        channel.connect();
        System.out.println("sftp channel opened and connected.");
        channelSftp = (ChannelSftp) channel;
        channelSftp.cd(SFTPWORKINGDIR);
        File f = new File(fileName);
        channelSftp.put(new FileInputStream(f), f.getName());
        log.info("File transfered successfully to host.");
    } catch (Exception ex) {
        System.out.println("Exception found while tranfer the response.");
    } finally {
        channelSftp.exit();
        System.out.println("sftp Channel exited.");
        channel.disconnect();
        System.out.println("Channel disconnected.");
        session.disconnect();
        System.out.println("Host Session disconnected.");
    }
}   

Check that an email address is valid on iOS

Heres a good one with NSRegularExpression that's working for me.

[text rangeOfString:@"^.+@.+\\..{2,}$" options:NSRegularExpressionSearch].location != NSNotFound;

You can insert whatever regex you want but I like being able to do it in one line.

What are the best practices for SQLite on Android?

after struggling with this for a couple of hours, I've found that you can only use one db helper object per db execution. For example,

for(int x = 0; x < someMaxValue; x++)
{
    db = new DBAdapter(this);
    try
    {

        db.addRow
        (
                NamesStringArray[i].toString(), 
                StartTimeStringArray[i].toString(),
                EndTimeStringArray[i].toString()
        );

    }
    catch (Exception e)
    {
        Log.e("Add Error", e.toString());
        e.printStackTrace();
    }
    db.close();
}

as apposed to:

db = new DBAdapter(this);
for(int x = 0; x < someMaxValue; x++)
{

    try
    {
        // ask the database manager to add a row given the two strings
        db.addRow
        (
                NamesStringArray[i].toString(), 
                StartTimeStringArray[i].toString(),
                EndTimeStringArray[i].toString()
        );

    }
    catch (Exception e)
    {
        Log.e("Add Error", e.toString());
        e.printStackTrace();
    }

}
db.close();

creating a new DBAdapter each time the loop iterates was the only way I could get my strings into a database through my helper class.

Execute bash script from URL

Use:

curl -s -L URL_TO_SCRIPT_HERE | bash

For example:

curl -s -L http://bitly/10hA8iC | bash

How to downgrade python from 3.7 to 3.6

Here is a canonical summary which sums up different solutions for the variety of operating system Python runs on. What follows are possibilities for Microsoft Windows, Linux, macOS and Misc.

As mentioned those are just possibilities - by no means do I claim to have a complete list whatsoever.


Microsoft Windows

Option 1

In general, it's suggested to use virtual environments (I highly suggest looking at the official Python documentation). With this approach, you easily can set up project-specific Python versions (as well as libraries). Easily manageable and the best part: There are lots of tutorials on the internet on how to approach this:

1.) Open command prompt ("cmd") and enter pip install virtualenv.

2.) Install your desired Python version via https://www.python.org/downloads/release; Remember: Do not add to PATH!

3.) Type into the command prompt: virtualenv \path\to\env -p \path\to\python_install.exe, whereas \path\to\env shall be the path where your virtual environment is going to be and \path\to\python_install.exe the one where your freshly (presumably) installed Python version resides.

4.) Done! You now have a virtual environment set up! Now, to activate the virtual environment execute the batch file which is located inside the \path\to\env\Scripts\activate.bat. (cf. this website or an official Python guide)

Option 2

The basic option would be to uninstall the unwanted Python version and re-install the favored one from https://www.python.org/downloads/. To remove the "old" version go to Control Panel -> "Uninstall a program" -> Search for "Python" -> Right-click on the Python name -> Uninstall. Bear in mind that Python usually has a PATH variable stored, hence you should remove it as well - Check the following links for this:

Now double-check whether there are any remaining files where Python used to be stored. Usually, you can find all the Python files at either C:\Program Files (x86)\Pythonxx, C:\Users\username\AppData\Local\Programs\Pythonxx or C:\Pythonxx or all of them. You might have installed it in another directory - check where it once was.

Now after de-installing just re-install the wanted version by going to the download page and follow the usual installation process. I won't go into details on how to install Python.. Lastly, you might check which version is currently installed by opening the command prompt and typing python -V.

Option 3

This approach is pretty similar to the second one - you basically uninstall the old one and replace it by your favored version. The only thing that changes it the part regarding how to uninstall the unwanted Python distribution: Simply execute the Python3 installer you originally used to install Python (it's usually stored in your Python directory as mentioned above; for more assistance check out this). There you get an option to repair or uninstall, proceed by choosing uninstall, and follow the steps provided via the uninstaller.

No matter how you uninstall Python (there are many resources on this topic, for example this Stack Overflow question or a problem thread a user by the name of Vincent Tang posted on the Stack Exchange site Super User, etc.), just reinstall the wanted Python version by following the steps mentioned in Option 2.

Option 4

Option 4 deals with Anaconda. Please refer to this site on how to install Anaconda on Windows. Step 9 is important as you don't want to install it as your default Python - you want to run multiple versions of Python:

Choose whether to register Anaconda as your default Python. Unless you plan on installing and running multiple versions of Anaconda or multiple versions of Python, accept the default and leave this box checked.

Follow the official tutorial I linked above.

Once done you can create the following commands individually in the anaconda prompt: To overwrite the default python version system-wise use conda install python=3.6 or to create a virtual environment go ahead and use conda create -n $PYTHON36_ENV_NAME python=3.6 anaconda whereas $PYTHON36_ENV_NAME is the custom name you can set. Credit where credit is due - the user @CermakM from this thread strongly influenced this snippet.

In my research I encountered a bunch of useful Stack Overflow threads - you might check them out if you go the tough road with Anaconda:

Option 5

What follows isn't a downgrade in the classical sense - though for the sake of completeness I decided to mention this approach as well. On Windows you're also able to run multiple Python versions - an infamous thread on StackOverflow deals with this question, thus I politely refer you to there for further reading purposes.


Linux

Option 1

Pretty analog to the third option for Windows I highly suggest you use a virtual environment such as Anaconda. Anaconda - or short conda - is also available on Linux. Check the official installation documentation here. Once again this thread is highly suggested on how to overwrite a Python version, respectively how to specifically create an environment with your wanted Python version.

Option 2

Another highly suggested virtual environment is Pyenv. The user @Sawan Vaidya described in this Stack Overflow question on how to up-or downgrade a Python version with the help of Pyenv. You can either set a Python version globally or create a local environment - both explained in the mentioned thread.

Option 3

Another user, namely @Jeereddy, has suggested to use the software package management system Homebrew. He explained this option thoroughly in this current question:

$ brew unlink python
$ brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/e128fa1bce3377de32cbf11bd8e46f7334dfd7a6/Formula/python.rb
$ brew switch python 3.6.5

Option 5

No need to reinvent the wheel - this thread is filled with lots of beautiful running approaches such as the one by @Sidharth Taneja.

  1. Download your wanted Python version from https://www.python.org/downloads/release and install it as a normal package.
  2. Run cd /Library/Frameworks/Python.framework/Version
  3. Execute ls to list all installed Python versions
  4. Run sudo rm -rf 3.7, removing Python version 3.7 - can be repeated for whatever version(s) you want to delete
  5. Check python3 -v, it should display the version you originally wanted to have installed

Option 6

What a goldmine this thread is! As @nondetermistic has described in-depth (direct link to his post):

Install Python source code as it is like this:

#Taken Python 3.6 as an example
$ mkdir /home/<user>/python3.6
$ ./configure --prefix=/home/<user>/python3.6/
$ make altinstall

You're now able to either add the downloaded version (/home/<user>/python3.6/bin) to PATH as well as lib to LD_LIBRARY_PATH or just create a virtual environment by: /home/<user>/python3.6/bin/python3.6 -m venv env-python3.6. A very aesthetic and simple solution to run multiple Python versions on your system.


macOS

Option 1

Using pyenv with Homebrew - credit to @Shayan with his reply here:

1.) Installing pyenv with Homebrew:

brew update
brew install pyenv

2.) Cloning the GitHub repository to get latest pyenv version:

 git clone https://github.com/pyenv/pyenv.git ~/.pyenv

3.) Defining the environment variables as follows

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bash_profile
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bash_profile

4.) Restarting shell so PATH change works

exec "$SHELL"

5.) Checking the available Python versions

pyenv install --list

6.) Installing the wanted Python version, e.g. 3.6

pyenv install 3.6

7.) Setting it globally (you can also go ahead and only use it in a certain environment)

pyenv global 3.6

8.) Check the Python version the system is using - your wanted / downgraded version should be displayed here.

python3 --version

Option 2

Similar to previous approaches you can download Anaconda on macOS as well. For an installation guide click here. The usage is pretty much the same as I've already described in Option 4 of the Windows guide. Please check out above.

Other options

In this case it's getting pretty repetitive. I kindly suggest you to check the following resources for further reading:


Misc

When writing this post I had the problem of not knowing where to draw the line. When looking up the operating systems Python currently supports you get a huge list, including the ones I mentioned, i.e. Linux, Microsoft Windows and macOS, though obviously different Linux distributions are single-handedly treated, e.g. CentOS, Arch Linux or Fedora should deserve a spot as well - or shall I make separate options for Windows 10, 7, etc.?

Due to the high degree of repetitiveness as far as modules like Homebrew, Conda or alike are concerned I decided to limit my list to the "main three" operating systems - distributions like Ubuntu (How do I downgrade my version of python from 3.7.5 to 3.6.5 on ubuntu), CentOS (How to downgrade python version on CentOS?) can be easily researched on Stack Overflow. Most often than not you can apply solutions from the Linux tab for said distributions. The same goes with Windows and macOS (versions).

Define global constants

The best way to create application wide constants in Angular 2 is by using environment.ts files. The advantage of declaring such constants is that you can vary them according to the environment as there can be a different environment file for each environment.

500 Internal Server Error for php file not for html

It was changing the line endings (from Windows CRLF to Unix LF) in the .htaccess file that fixed it for me.

Select query with date condition

select Qty, vajan, Rate,Amt,nhamali,ncommission,ntolai from SalesDtl,SalesMSt where SalesDtl.PurEntryNo=1 and SalesMST.SaleDate=  (22/03/2014) and SalesMST.SaleNo= SalesDtl.SaleNo;

That should work.

How can I import Swift code to Objective-C?

There's one caveat if you're importing Swift code into your Objective-C files within the same framework. You have to do it with specifying the framework name and angle brackets:

#import <MyFramework/MyFramework-Swift.h>

MyFramework here is the "Product Module Name" build setting (PRODUCT_NAME = MyFramework).

Simply adding #import "MyFramework-Swift.h" won't work. If you check the built products directory (before such an #import is added, so you've had at least one successful build with some Swift code in the target), then you should still see the file MyFramework-Swift.h in the Headers directory.

What does question mark and dot operator ?. mean in C# 6.0?

This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.

old way to achieve the same thing was:

var functionCaller = this.member;
if (functionCaller!= null)
    functionCaller.someFunction(var someParam);

and now it has been made much easier with just:

member?.someFunction(var someParam);

I strongly recommend this doc page.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

Export/import jobs in Jenkins

Jenkins export jobs to a directory

 #! /bin/bash
    SAVEIFS=$IFS
    IFS=$(echo -en "\n\b")
    declare -i j=0
    for i in $(java -jar jenkins-cli.jar -s http://server:8080/jenkins list-jobs  --username **** --password ***);
    do
    let "j++";
    echo $j;
    if [ $j -gt 283 ] // If you have more jobs do it in chunks as it will terminate in the middle of the process. So Resume your job from where it ends.
     then
    java -jar jenkins-cli.jar -s http://lxvbmcbma:8080/jenkins get-job --username **** --password **** ${i} > ${i}.xml;
    echo "done";
    fi
    done

Import jobs

for f in *.xml;
do
echo "Processing ${f%.*} file.."; //truncate the .xml extention and load the xml file for job creation
java -jar jenkins-cli.jar -s http://server:8080/jenkins create-job ${f%.*}  < $f
done

React passing parameter via onclick event using ES6 syntax

TL;DR:

Don't bind function (nor use arrow functions) inside render method. See official recommendations.

https://reactjs.org/docs/faq-functions.html


So, there's an accepted answer and a couple more that points the same. And also there are some comments preventing people from using bind within the render method, and also avoiding arrow functions there for the same reason (those functions will be created once again and again on each render). But there's no example, so I'm writing one.

Basically, you have to bind your functions in the constructor.

class Actions extends Component {

    static propTypes = {
        entity_id: PropTypes.number,
        contact_id: PropTypes.number,
        onReplace: PropTypes.func.isRequired,
        onTransfer: PropTypes.func.isRequired
    }

    constructor() {
        super();
        this.onReplace = this.onReplace.bind(this);
        this.onTransfer = this.onTransfer.bind(this);
    }

    onReplace() {
        this.props.onReplace(this.props.entity_id, this.props.contact_id);
    }

    onTransfer() {
        this.props.onTransfer(this.props.entity_id, this.props.contact_id);
    }

    render() {
        return (
            <div className="actions">
                <button className="btn btn-circle btn-icon-only btn-default"
                    onClick={this.onReplace}
                    title="Replace">
                        <i className="fa fa-refresh"></i>
                </button>
                <button className="btn btn-circle btn-icon-only btn-default"
                    onClick={this.onTransfer}
                    title="Transfer">
                    <i className="fa fa-share"></i>
                </button>                                 
            </div>
        )
    }
}

export default Actions

Key lines are:

constructor

this.onReplace = this.onReplace.bind(this);

method

onReplace() {
    this.props.onReplace(this.props.entity_id, this.props.contact_id);
}

render

onClick={this.onReplace}

How can I specify the required Node.js version in package.json?

I think you can use the "engines" field:

{ "engines" : { "node" : ">=0.12" } }

As you're saying your code definitely won't work with any lower versions, you probably want the "engineStrict" flag too:

{ "engineStrict" : true }

Documentation for the package.json file can be found on the npmjs site

Update

engineStrict is now deprecated, so this will only give a warning. It's now down to the user to run npm config set engine-strict true if they want this.

Update 2

As ben pointed out below, creating a .npmrc file at the root of your project (the same level as your package.json file) with the text engine-strict=true will force an error during installation if the Node version is not compatible.

How can I get System variable value in Java?

As mentioned by sombody above, restarting eclipse worked for me for the user defined environment variable. After I restart eclipse IDE, System.getenv() is picking up my environment variable.

When and how should I use a ThreadLocal variable?

The ThreadLocal class in Java enables you to create variables that can only be read and written by the same thread. Thus, even if two threads are executing the same code, and the code has a reference to a ThreadLocal variable, then the two threads cannot see each other's ThreadLocal variables.

Read more

How could I use requests in asyncio?

DISCLAMER: Following code creates different threads for each function.

This might be useful for some of the cases as it is simpler to use. But know that it is not async but gives illusion of async using multiple threads, even though decorator suggests that.

To make any function non blocking, simply copy the decorator and decorate any function with a callback function as parameter. The callback function will receive the data returned from the function.

import asyncio
import requests


def run_async(callback):
    def inner(func):
        def wrapper(*args, **kwargs):
            def __exec():
                out = func(*args, **kwargs)
                callback(out)
                return out

            return asyncio.get_event_loop().run_in_executor(None, __exec)

        return wrapper

    return inner


def _callback(*args):
    print(args)


# Must provide a callback function, callback func will be executed after the func completes execution !!
@run_async(_callback)
def get(url):
    return requests.get(url)


get("https://google.com")
print("Non blocking code ran !!")

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

Java 32-bit vs 64-bit compatibility

I accidentally ran our (largeish) application on a 64bit VM rather than a 32bit VM and didn't notice until some external libraries (called by JNI) started failing.

Data serialized on a 32bit platform was read in on the 64bit platform with no issues at all.

What sort of issues are you getting? Do some things work and not others? Have you tried attaching JConsole etc and have a peak around?

If you have a very big VM you may find that GC issues in 64 bit can affect you.

jQuery - multiple $(document).ready ...?

Not to necro a thread, but under the latest version of jQuery the suggested syntax is:

$( handler )

Using an anonymous function, this would look like

$(function() { ... insert code here ... });

See this link:

https://api.jquery.com/ready/

Setting a backgroundImage With React Inline Styles

Sometimes your SVG will be inlined by React so you need quotes around it:

     backgroundImage: `url("${Background}")`

otherwise it's invalid CSS and the browser dev tools will not show that you've set background-image at all.

How do I get an Excel range using row and column numbers in VSTO / C#?

Try this, works!

Excel.Worksheet sheet = xlWorkSheet;
Excel.Series series1 = seriesCollection.NewSeries();
Excel.Range rng = (Excel.Range)xlWorkSheet.Range[xlWorkSheet.Cells[3, 13], xlWorkSheet.Cells[pp, 13]].Cells;
series1.Values = rng;

Any way to make plot points in scatterplot more transparent in R?

If you are using the hex codes, you can add two more digits at the end of the code to represent the alpha channel:

E.g. half-transparency red:

plot(1:100, main="Example of Plot With Transparency")
lines(1:100 + sin(1:100*2*pi/(20)), col='#FF000088', lwd=4)
mtext("use `col='#FF000088'` for the lines() function")

example plot of color with transparency

How do you search an amazon s3 bucket?

AWS released a new Service to query S3 buckets with SQL: Amazon Athena https://aws.amazon.com/athena/

Build unsigned APK file with Android Studio

Now in Android Studio v1.1.0 should be:

  1. select Run > Run <your app>
  2. find .apk file in <your app>\build\outputs\apk

Adding Lombok plugin to IntelliJ project

I would like to add that in my case (My OS is Linux Mint and using IntelliJ IDEA). My compiler complaining about these annotations I was using: @Data @RequiredArgsConstructor, even though I had installed and activated the Lombok plugin.Install Lombok in IntelliJ Idea. I am using Maven. So I had to add this dependency in my configuration file (pom.xml file):

dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>

How to find encoding of a file via script on Linux?

here is an example script using file -I and iconv which works on MacOsX For your question you need to use mv instead of iconv

#!/bin/bash
# 2016-02-08
# check encoding and convert files
for f in *.java
do
  encoding=`file -I $f | cut -f 2 -d";" | cut -f 2 -d=`
  case $encoding in
    iso-8859-1)
    iconv -f iso8859-1 -t utf-8 $f > $f.utf8
    mv $f.utf8 $f
    ;;
  esac
done

Update multiple tables in SQL Server using INNER JOIN

You can't update more that one table in a single statement, however the error message you get is because of the aliases, you could try this :

BEGIN TRANSACTION

update A
set A.ORG_NAME =  @ORG_NAME
from table1 A inner join table2 B
on B.ORG_ID = A.ORG_ID
and A.ORG_ID = @ORG_ID

update B
set B.REF_NAME = @REF_NAME
from table2 B inner join table1 A
    on B.ORG_ID = A.ORG_ID
    and A.ORG_ID = @ORG_ID

COMMIT

How to delete a specific line in a file?

The issue with reading lines in first pass and making changes (deleting specific lines) in the second pass is that if you file sizes are huge, you will run out of RAM. Instead, a better approach is to read lines, one by one, and write them into a separate file, eliminating the ones you don't need. I have run this approach with files as big as 12-50 GB, and the RAM usage remains almost constant. Only CPU cycles show processing in progress.

Oracle ORA-12154: TNS: Could not resolve service name Error?

I just spend an hour on this, I'm new to Oracle so i was thoroughly confused..

the situation:

just installed visual studio 2012 Oracle developer tools. When i did this I lost the items in my drop down which contained my TNS entries in TOAD. I was getting this error from Visual studio AND TOAD!! WTH! so i added the environmental Variable TNS_ADMIN under "ALL USERS" with the path to my .ora file (which i now worked fine because it worked until I broke it). Toad picked up that change. Still Visual Studio wouldn't give me any love... still getting same error. THEN, i added the environmental Variable TO MY USER VARIABLES.. VIOLA!!

ENSURE THE ENVIRONMENTAL VARIABLES ARE SET FOR THE SYSTEM AND THE USER

How to Rotate a UIImage 90 degrees?

I like the simple elegance of Peter Sarnowski's answer, but it can cause problems when you can't rely on EXIF metadata and the like. In situations where you need to rotate the actual image data I would recommend something like this:

- (UIImage *)rotateImage:(UIImage *) img
{
    CGSize imgSize = [img size];
    UIGraphicsBeginImageContext(imgSize);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextRotateCTM(context, M_PI_2);
    CGContextTranslateCTM(context, 0, -640);
    [img drawInRect:CGRectMake(0, 0, imgSize.height, imgSize.width)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

The above code takes an image whose orientation is Landscape (can't remember if it's Landscape Left or Landscape Right) and rotates it into Portrait. It is an example which can be modified for your needs.

The key arguments you would have to play with are CGContextRotateCTM(context, M_PI_2) where you decide how much you want to rotate by, but then you have to make sure the picture still draws on the screen using CGContextTranslateCTM(context, 0, -640). This last part is quite important to make sure you see the image and not a blank screen.

For more info check out the source.

How to set timeout on python's socket recv method?

The timeout that you are looking for is the connection socket's timeout not the primary socket's, if you implement the server side. In other words, there is another timeout for the connection socket object, which is the output of socket.accept() method. Therefore:

sock.listen(1)
connection, client_address = sock.accept()
connection.settimeout(5)    # This is the one that affects recv() method.
connection.gettimeout()     # This should result 5
sock.gettimeout()           # This outputs None when not set previously, if I remember correctly.

If you implement the client side, it would be simple.

sock.connect(server_address)
sock.settimeout(3)

How to replace unicode characters in string with something else python?

Funny the answer is hidden in among the answers.

str.replace("•", "something") 

would work if you use the right semantics.

str.replace(u"\u2022","something") 

works wonders ;) , thnx to RParadox for the hint.

HTML Input="file" Accept Attribute File Type (CSV)

After my test, on ?macOS 10.15.7 Catalina?, the answer of ?Dom / Rikin Patel? cannot recognize the [.xlsx] file normally.

I personally summarized the practice of most of the existing answers and passed personal tests. Sum up the following answers:

accept=".csv, .xls, .xlsx, text/csv, application/csv,
text/comma-separated-values, application/csv, application/excel,
application/vnd.msexcel, text/anytext, application/vnd. ms-excel,
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

How to specify the actual x axis values to plot as x axis ticks in R

In case of plotting time series, the command ts.plot requires a different argument than xaxt="n"

require(graphics)
ts.plot(ldeaths, mdeaths, xlab="year", ylab="deaths", lty=c(1:2), gpars=list(xaxt="n"))
axis(1, at = seq(1974, 1980, by = 2))

Position Relative vs Absolute?

Marco Pellicciotta: The position of the element inside another element can be relative or absolute, about the element it's inside.

If you need to position the element in the browser window point of view it's best to use position:fixed

How to determine if object is in array

You could use jQuery's grep method:

$.grep(carBrands, function(obj) { return obj.name == "ford"; });

But as you specify no jQuery, you could just make a derivative of the function. From the source code:

function grepArray( elems, callback, inv ) {  
    var ret = [];  

    // Go through the array, only saving the items  
    // that pass the validator function  
    for ( var i = 0, length = elems.length; i < length; i++ ) {  
        if ( !inv !== !callback( elems[ i ], i ) ) {  
            ret.push( elems[ i ] );  
        }  
    }  

    return ret;  
}  

grepArray(carBrands, function(obj) { return obj.name == "ford"; });

How to find top three highest salary in emp table in oracle?

SELECT salary,first_name||' '||last_name "Name of the employee" 
FROM hr.employees 
WHERE rownum <= 3 
ORDER BY salary desc ;

Select the top N values by group

# start with the mtcars data frame (included with your installation of R)
mtcars

# pick your 'group by' variable
gbv <- 'cyl'
# IMPORTANT NOTE: you can only include one group by variable here
# ..if you need more, the `order` function below will need
# one per inputted parameter: order( x$cyl , x$am )

# choose whether you want to find the minimum or maximum
find.maximum <- FALSE

# create a simple data frame with only two columns
x <- mtcars

# order it based on 
x <- x[ order( x[ , gbv ] , decreasing = find.maximum ) , ]

# figure out the ranks of each miles-per-gallon, within cyl columns
if ( find.maximum ){
    # note the negative sign (which changes the order of mpg)
    # *and* the `rev` function, which flips the order of the `tapply` result
    x$ranks <- unlist( rev( tapply( -x$mpg , x[ , gbv ] , rank ) ) )
} else {
    x$ranks <- unlist( tapply( x$mpg , x[ , gbv ] , rank ) )
}
# now just subset it based on the rank column
result <- x[ x$ranks <= 3 , ]

# look at your results
result

# done!

# but note only *two* values where cyl == 4 were kept,
# because there was a tie for third smallest, and the `rank` function gave both '3.5'
x[ x$ranks == 3.5 , ]

# ..if you instead wanted to keep all ties, you could change the
# tie-breaking behavior of the `rank` function.
# using the `min` *includes* all ties.  using `max` would *exclude* all ties
if ( find.maximum ){
    # note the negative sign (which changes the order of mpg)
    # *and* the `rev` function, which flips the order of the `tapply` result
    x$ranks <- unlist( rev( tapply( -x$mpg , x[ , gbv ] , rank , ties.method = 'min' ) ) )
} else {
    x$ranks <- unlist( tapply( x$mpg , x[ , gbv ] , rank , ties.method = 'min' ) )
}
# and there are even more options..
# see ?rank for more methods

# now just subset it based on the rank column
result <- x[ x$ranks <= 3 , ]

# look at your results
result
# and notice *both* cyl == 4 and ranks == 3 were included in your results
# because of the tie-breaking behavior chosen.

Reset the Value of a Select Box

use the .val('') setter

jsfiddle example

$('select').val('1');

SQLAlchemy: What's the difference between flush() and commit()?

This does not strictly answer the original question but some people have mentioned that with session.autoflush = True you don't have to use session.flush()... And this is not always true.

If you want to use the id of a newly created object in the middle of a transaction, you must call session.flush().

# Given a model with at least this id
class AModel(Base):
   id = Column(Integer, primary_key=True)  # autoincrement by default on integer primary key

session.autoflush = True

a = AModel()
session.add(a)
a.id  # None
session.flush()
a.id  # autoincremented integer

This is because autoflush does NOT auto fill the id (although a query of the object will, which sometimes can cause confusion as in "why this works here but not there?" But snapshoe already covered this part).


One related aspect that seems pretty important to me and wasn't really mentioned:

Why would you not commit all the time? - The answer is atomicity.

A fancy word to say: an ensemble of operations have to all be executed successfully OR none of them will take effect.

For example, if you want to create/update/delete some object (A) and then create/update/delete another (B), but if (B) fails you want to revert (A). This means those 2 operations are atomic.

Therefore, if (B) needs a result of (A), you want to call flush after (A) and commit after (B).

Also, if session.autoflush is True, except for the case that I mentioned above or others in Jimbo's answer, you will not need to call flush manually.

C# Remove object from list of objects

First you have to find out the object in the list. Then you can remove from the list.

       var item = myList.Find(x=>x.ItemName == obj.ItemName);
       myList.Remove(item);

Java constructor/method with optional parameters?

Why do you want to do that?

However, You can do this:

public void foo(int param1)
{
    int param2 = 2;
    // rest of code
}

or:

public void foo(int param1, int param2)
{
    // rest of code
}

public void foo(int param1)
{
    foo(param1, 2);
}

Map HTML to JSON

Thank you @Gorge Reith. Working off the solution provided by @George Reith, here is a function that furthers (1) separates out the individual 'hrefs' links (because they might be useful), (2) uses attributes as keys (since attributes are more descriptive), and (3) it's usable within Node.js without needing Chrome by using the 'jsdom' package:

const jsdom = require('jsdom') // npm install jsdom provides in-built Window.js without needing Chrome


// Function to map HTML DOM attributes to inner text and hrefs
function mapDOM(html_string, json) {
    treeObject = {}

    // IMPT: use jsdom because of in-built Window.js
    // DOMParser() does not provide client-side window for element access if coding in Nodejs
    dom = new jsdom.JSDOM(html_string)
    document = dom.window.document
    element = document.firstChild

    // Recursively loop through DOM elements and assign attributes to inner text object
    // Why attributes instead of elements? 1. attributes more descriptive, 2. usually important and lesser
    function treeHTML(element, object) {
        var nodeList = element.childNodes;
        if (nodeList != null) {
           if (nodeList.length) {
               object[element.nodeName] = []  // IMPT: empty [] array for non-text recursivable elements (see below)
               for (var i = 0; i < nodeList.length; i++) {
                   // if final text
                   if (nodeList[i].nodeType == 3) {
                       if (element.attributes != null) {
                           for (var j = 0; j < element.attributes.length; j++) {
                                if (element.attributes[j].nodeValue !== '' && 
                                    nodeList[i].nodeValue !== '') {
                                    if (element.attributes[j].name === 'href') { // separate href
                                        object[element.attributes[j].name] = element.attributes[j].nodeValue;
                                    } else {
                                        object[element.attributes[j].nodeValue] = nodeList[i].nodeValue;
                                    }

                                }
                           }
                       }
                   // else if non-text then recurse on recursivable elements
                   } else {
                       object[element.nodeName].push({}); // if non-text push {} into empty [] array
                       treeHTML(nodeList[i], object[element.nodeName][object[element.nodeName].length -1]);
                   }
               }
           }
        }
    }
    treeHTML(element, treeObject);

    return (json) ? JSON.stringify(treeObject) : treeObject;
}

How do I determine the size of my array in C?

#define SIZE_OF_ARRAY(_array) (sizeof(_array) / sizeof(_array[0]))

MS-DOS Batch file pause with enter key

You can do it with the pause command, example:

dir
pause
echo Now about to end...
pause

Bootstrap Accordion button toggle "data-parent" not working

Here is a (hopefully) universal patch I developed to fix this problem for BootStrap V3. No special requirements other than plugging in the script.

$(':not(.panel) > [data-toggle="collapse"][data-parent]').click(function() {
    var parent = $(this).data('parent');
    var items = $('[data-toggle="collapse"][data-parent="' + parent + '"]').not(this);
    items.each(function() {
        var target = $(this).data('target') || '#' + $(this).prop('href').split('#')[1];
        $(target).filter('.in').collapse('hide');
    });
});

EDIT: Below is a simplified answer which still meets my needs, and I'm now using a delegated click handler:

$(document.body).on('click', ':not(.panel) > [data-toggle="collapse"][data-parent]', function() {
    var parent = $(this).data('parent');
    var target = $(this).data('target') || $(this).prop('hash');
    $(parent).find('.collapse.in').not(target).collapse('hide');
});

Get the value of a dropdown in jQuery

var sal = $('.selectSal option:selected').eq(0).val();

selectSal is a class.

How to hide a button programmatically?

Please used below

View.GONE and View.VISIBLE

pass JSON to HTTP POST Request

       var request = require('request');
        request({
            url: "http://localhost:8001/xyz",
            json: true,
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify(requestData)
        }, function(error, response, body) {
            console.log(response);
        });

Reading PDF content with itextsharp dll in VB.NET or C#

In my case, I just wanted the text from a specific area of the PDF document so I used a rectangle around the area and extracted the text from it. In the sample below the coordinates are for the entire page. I don't have PDF authoring tools so when it came time to narrow down the rectangle to the specific location I took a few guesses at the coordinates until the area was found.

Rectangle _pdfRect = new Rectangle(0f, 0f, 612f, 792f); // Entire page - PDF coordinate system 0,0 is bottom left corner.  72 points / inch
RenderFilter _renderfilter = new RegionTextRenderFilter(_pdfRect);
ITextExtractionStrategy _strategy = new FilteredTextRenderListener(new LocationTextExtractionStrategy(), _filter);
string _text = PdfTextExtractor.GetTextFromPage(_pdfReader, 1, _strategy);

As noted by the above comments the resulting text doesn't maintain any of the formatting found in the PDF document, however, I was happy that it did preserve the carriage returns. In my case, there were enough constants in the text that I was able to extract the values that I required.

Removing cordova plugins from the project

This is the commandline for removing plugins in Cordova

cordova plugin remove <pluginid>

For example I ran cordova plugin and got a list of plugins then I used the id for the plugin to uninstall

cordova plugin remove com.monday.contact-chooser

You can get help in the commandline by typing

cordova help <command>

How do I find the length/number of items present for an array?

If the array is statically allocated, use sizeof(array) / sizeof(array[0])

If it's dynamically allocated, though, unfortunately you're out of luck as this trick will always return sizeof(pointer_type)/sizeof(array[0]) (which will be 4 on a 32 bit system with char*s) You could either a) keep a #define (or const) constant, or b) keep a variable, however.

Printing one character at a time from a string, using the while loop

I'm quite sure, that the internet is full of python while-loops, but one example:

i=0

while i < len(text):
    print text[i]
    i += 1

Why are only a few video games written in Java?

Performance issue is the first reason. When you see the kind of hyper optimized C++ code that are in the Quake engines ( http://www.codemaestro.com/reviews/9 ), you know they're not gonna waste their time with a virtual machine.

Sure there may be some .NET games (which ones ? I'm interested. Are there some really CPU/GPU-intensive ones ?), but I guess it's more because lot of people are experts in MS technologies and followed Microsoft when they launched their new technology.

Oh and cross-platform just isn't in the mind of video games companies. Linux is just around 1% of market, Mac OS a few % more. They definitely think it's not worth dumping Windows-only technologies and librairies such as DirectX.

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

You probably want to use something like jQuery, which makes JS programming easier.

Something like:

$(document).ready(function(){
   // Your code here
});

Would seem to do what you are after.

how can get index & count in vuejs

The optional SECOND argument is the index, starting at 0. So to output the index and total length of an array called 'some_list':

<div>Total Length: {{some_list.length}}</div>
<div v-for="(each, i) in some_list">
  {{i + 1}} : {{each}}
</div>

If instead of a list, you were looping through an object, then the second argument is key of the key/value pair. So for the object 'my_object':

var an_id = new Vue({
  el: '#an_id',
  data: {
    my_object: {
        one: 'valueA',
        two: 'valueB'
    }
  }
})

The following would print out the key : value pairs. (you can name 'each' and 'i' whatever you want)

<div id="an_id">
  <span v-for="(each, i) in my_object">
    {{i}} : {{each}}<br/>
  </span>
</div>

For more info on Vue list rendering: https://vuejs.org/v2/guide/list.html

Current date without time

If you need exact your example, you should add format to ToString()

    string test = DateTime.ParseExact(DateTime.Now.ToString("dd.MM.yyyy"), "dd.MM.yyyy", CultureInfo.InvariantCulture).ToString("yyyy-MM-dd");

But it's better to use straight formatting:

    string test = DateTime.Now.ToString("yyyy-MM-dd")

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

How to get last N records with activerecord?

This is the Rails 3 way

SomeModel.last(5) # last 5 records in ascending order

SomeModel.last(5).reverse # last 5 records in descending order

AngularJS open modal on button click

Set Jquery in scope

$scope.$ = $;

and call in html

ng-click="$('#novoModelo').modal('show')"

PHP How to find the time elapsed since a date time?

If you use the php Datetime class you could use:

function time_ago(Datetime $date) {
  $time_ago = '';

  $diff = $date->diff(new Datetime('now'));


  if (($t = $diff->format("%m")) > 0)
    $time_ago = $t . ' months';
  else if (($t = $diff->format("%d")) > 0)
    $time_ago = $t . ' days';
  else if (($t = $diff->format("%H")) > 0)
    $time_ago = $t . ' hours';
  else
    $time_ago = 'minutes';

  return $time_ago . ' ago (' . $date->format('M j, Y') . ')';
}

How to create a DateTime equal to 15 minutes ago?

datetime.datetime.now() - datetime.timedelta(0, 15 * 60)

timedelta is a "change in time". It takes days as the first parameter and seconds in the second parameter. 15 * 60 seconds is 15 minutes.

Assigning default value while creating migration file

Yes, I couldn't see how to use 'default' in the migration generator command either but was able to specify a default value for a new string column as follows by amending the generated migration file before applying "rake db:migrate":

class AddColumnToWidgets < ActiveRecord::Migration
  def change
    add_column :widgets, :colour, :string, default: 'red'
  end
end

This adds a new column called 'colour' to my 'Widget' model and sets the default 'colour' of new widgets to 'red'.

Using node.js as a simple web server

Check out this gist. I'm reproducing it here for reference, but the gist has been regularly updated.

Node.JS static file web server. Put it in your path to fire up servers in any directory, takes an optional port argument.

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs"),
    port = process.argv[2] || 8888;

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) filename += '/index.html';

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {        
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      response.writeHead(200);
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");

Update

The gist does handle css and js files. I've used it myself. Using read/write in "binary" mode isn't a problem. That just means that the file isn't interpreted as text by the file library and is unrelated to content-type returned in the response.

The problem with your code is you're always returning a content-type of "text/plain". The above code does not return any content-type, but if you're just using it for HTML, CSS, and JS, a browser can infer those just fine. No content-type is better than a wrong one.

Normally the content-type is a configuration of your web server. So I'm sorry if this doesn't solve your problem, but it worked for me as a simple development server and thought it might help some other people. If you do need correct content-types in the response, you either need to explicitly define them as joeytwiddle has or use a library like Connect that has sensible defaults. The nice thing about this is that it's simple and self-contained (no dependencies).

But I do feel your issue. So here is the combined solution.

var http = require("http"),
    url = require("url"),
    path = require("path"),
    fs = require("fs")
    port = process.argv[2] || 8888;

http.createServer(function(request, response) {

  var uri = url.parse(request.url).pathname
    , filename = path.join(process.cwd(), uri);

  var contentTypesByExtension = {
    '.html': "text/html",
    '.css':  "text/css",
    '.js':   "text/javascript"
  };

  fs.exists(filename, function(exists) {
    if(!exists) {
      response.writeHead(404, {"Content-Type": "text/plain"});
      response.write("404 Not Found\n");
      response.end();
      return;
    }

    if (fs.statSync(filename).isDirectory()) filename += '/index.html';

    fs.readFile(filename, "binary", function(err, file) {
      if(err) {        
        response.writeHead(500, {"Content-Type": "text/plain"});
        response.write(err + "\n");
        response.end();
        return;
      }

      var headers = {};
      var contentType = contentTypesByExtension[path.extname(filename)];
      if (contentType) headers["Content-Type"] = contentType;
      response.writeHead(200, headers);
      response.write(file, "binary");
      response.end();
    });
  });
}).listen(parseInt(port, 10));

console.log("Static file server running at\n  => http://localhost:" + port + "/\nCTRL + C to shutdown");

Environment variable substitution in sed

Your two examples look identical, which makes problems hard to diagnose. Potential problems:

  1. You may need double quotes, as in sed 's/xxx/'"$PWD"'/'

  2. $PWD may contain a slash, in which case you need to find a character not contained in $PWD to use as a delimiter.

To nail both issues at once, perhaps

sed 's@xxx@'"$PWD"'@'

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

I try this it solved.

 AlertDialog.Builder builder = new AlertDialog.Builder(
                   this);
            builder.setCancelable(true);
            builder.setTitle("Opss!!");

            builder.setMessage("You Don't have anough coins to withdraw. ");
            builder.setMessage("Please read the Withdraw rules.");
            builder.setInverseBackgroundForced(true);
            builder.setPositiveButton("OK",
                    (dialog, which) -> dialog.dismiss());
            builder.create().show();

Using Node.JS, how do I read a JSON file into (server) memory?

The easiest way I have found to do this is to just use require and the path to your JSON file.

For example, suppose you have the following JSON file.

test.json

{
  "firstName": "Joe",
  "lastName": "Smith"
}

You can then easily load this in your node.js application using require

var config = require('./test.json');
console.log(config.firstName + ' ' + config.lastName);

Call a function with argument list in python

To expand a little on the other answers:

In the line:

def wrapper(func, *args):

The * next to args means "take the rest of the parameters given and put them in a list called args".

In the line:

    func(*args)

The * next to args here means "take this list called args and 'unwrap' it into the rest of the parameters.

So you can do the following:

def wrapper1(func, *args): # with star
    func(*args)

def wrapper2(func, args): # without star
    func(*args)

def func2(x, y, z):
    print x+y+z

wrapper1(func2, 1, 2, 3)
wrapper2(func2, [1, 2, 3])

In wrapper2, the list is passed explicitly, but in both wrappers args contains the list [1,2,3].

Where is virtualenvwrapper.sh after pip install?

I have the same problem. If you have older version of virtualenvwrapper, then pip wont work.

download src from http://pypi.python.org/pypi/virtualenvwrapper/3.6 and python setup.py install. Then the problem solved.

Copying one structure to another

If the structures are of compatible types, yes, you can, with something like:

memcpy (dest_struct, source_struct, sizeof (*dest_struct));

The only thing you need to be aware of is that this is a shallow copy. In other words, if you have a char * pointing to a specific string, both structures will point to the same string.

And changing the contents of one of those string fields (the data that the char * points to, not the char * itself) will change the other as well.

If you want a easy copy without having to manually do each field but with the added bonus of non-shallow string copies, use strdup:

memcpy (dest_struct, source_struct, sizeof (*dest_struct));
dest_struct->strptr = strdup (source_struct->strptr);

This will copy the entire contents of the structure, then deep-copy the string, effectively giving a separate string to each structure.

And, if your C implementation doesn't have a strdup (it's not part of the ISO standard), get one from here.

Proxy with express.js

request has been deprecated as of February 2020, I'll leave the answer below for historical reasons, but please consider moving to an alternative listed in this issue.

Archive

I did something similar but I used request instead:

var request = require('request');
app.get('/', function(req,res) {
  //modify the url in any way you want
  var newurl = 'http://google.com/';
  request(newurl).pipe(res);
});

I hope this helps, took me a while to realize that I could do this :)

How do I set a textbox's text to bold at run time?

The bold property of the font itself is read only, but the actual font property of the text box is not. You can change the font of the textbox to bold as follows:

  textBox1.Font = new Font(textBox1.Font, FontStyle.Bold);

And then back again:

  textBox1.Font = new Font(textBox1.Font, FontStyle.Regular);

Android simple alert dialog

No my friend its very simple, try using this:

AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);

alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
    public void onClick(DialogInterface dialog, int which) {
        Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
    }
});

alertDialog.show();

This tutorial shows how you can create custom dialog using xml and then show them as an alert dialog.

jquery - How to determine if a div changes its height or any css attribute?

For future sake I'll post this. If you do not need to support < IE11 then you should use MutationObserver.

Here is a link to the caniuse js MutationObserver

Simple usage with powerful results.

    var observer = new MutationObserver(function (mutations) {
        //your action here
    });

    //set up your configuration
    //this will watch to see if you insert or remove any children
    var config = { subtree: true, childList: true };

    //start observing
    observer.observe(elementTarget, config);

When you don't need to observe any longer just disconnect.

    observer.disconnect();

Check out the MDN documentation for more information

How to center content in a bootstrap column?

Use:

<!-- unsupported by HTML5 -->
<div class="col-xs-1" align="center">

instead of

<div class="col-xs-1 center-block">

You can also use bootstrap 3 css:

<!-- recommended method -->
<div class="col-xs-1 text-center">

Bootstrap 4 now has flex classes that will center the content:

<div class="d-flex justify-content-center">
   <div>some content</div>
</div>

Note that by default it will be x-axis unless flex-direction is column

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

This has worked for me. I have tried different methods but this was my best solution.

Open command prompt and type the following; pip install opencv-python. (make sure your internet is on). after that try importing it again.

What's a good hex editor/viewer for the Mac?

  1. Open file with Xcode and press Command + Shift + J
  2. Right click file name in left pane
  3. Open as -> Hex

C#: Printing all properties of an object

Regarding TypeDescriptor from Sean's reply (I can't comment because I have a bad reputation)... one advantage to using TypeDescriptor over GetProperties() is that TypeDescriptor has a mechanism for dynamically attaching properties to objects at runtime and normal reflection will miss these.

For example, when working with PowerShell's PSObject, which can have properties and methods added at runtime, they implemented a custom TypeDescriptor which merges these members in with the standard member set. By using TypeDescriptor, your code doesn't need to be aware of that fact.

Components, controls, and I think maybe DataSets also make use of this API.

How to use a switch case 'or' in PHP

I won't repost the other answers because they're all correct, but I'll just add that you can't use switch for more "complicated" statements, eg: to test if a value is "greater than 3", "between 4 and 6", etc. If you need to do something like that, stick to using if statements, or if there's a particularly strong need for switch then it's possible to use it back to front:

switch (true) {
    case ($value > 3) :
        // value is greater than 3
    break;
    case ($value >= 4 && $value <= 6) :
        // value is between 4 and 6
    break;
}

but as I said, I'd personally use an if statement there.

How do I get specific properties with Get-AdUser

using select-object for example:

Get-ADUser -Filter * -SearchBase 'OU=Users & Computers, DC=aaaaaaa, DC=com' -Properties DisplayName | select -expand displayname | Export-CSV "ADUsers.csv" 

Ruby array to string conversion

suppose your array :

arr=["1","2","3","4"]

Method to convert array to string:

Array_name.join(",")

Example:

arr.join(",")

Result:

"'1','2','3','4'"

How can I do an OrderBy with a dynamic string parameter?

Another solution from codeConcussion (https://stackoverflow.com/a/7265394/2793768)

var param = "Address";    
var pi = typeof(Student).GetProperty(param);    
var orderByAddress = items.OrderBy(x => pi.GetValue(x, null));

How to transfer paid android apps from one google account to another google account

It's totally feasible now. Google now allow you to transfer Android apps between accounts. Please take a look at this link: https://support.google.com/googleplay/android-developer/checklist/3294213?hl=en

How do you delete all text above a certain line

dgg

will delete everything from your current line to the top of the file.

d is the deletion command, and gg is a movement command that says go to the top of the file, so when used together, it means delete from my current position to the top of the file.

Also

dG

will delete all lines at or below the current one

Dynamic SQL - EXEC(@SQL) versus EXEC SP_EXECUTESQL(@SQL)

Microsoft's Using sp_executesql article recommends using sp_executesql instead of execute statement.

Because this stored procedure supports parameter substitution, sp_executesql is more versatile than EXECUTE; and because sp_executesql generates execution plans that are more likely to be reused by SQL Server, sp_executesql is more efficient than EXECUTE.

So, the take away: Do not use execute statement. Use sp_executesql.

How much overhead does SSL impose?

Assuming you don't count connection set-up (as you indicated in your update), it strongly depends on the cipher chosen. Network overhead (in terms of bandwidth) will be negligible. CPU overhead will be dominated by cryptography. On my mobile Core i5, I can encrypt around 250 MB per second with RC4 on a single core. (RC4 is what you should choose for maximum performance.) AES is slower, providing "only" around 50 MB/s. So, if you choose correct ciphers, you won't manage to keep a single current core busy with the crypto overhead even if you have a fully utilized 1 Gbit line. [Edit: RC4 should not be used because it is no longer secure. However, AES hardware support is now present in many CPUs, which makes AES encryption really fast on such platforms.]

Connection establishment, however, is different. Depending on the implementation (e.g. support for TLS false start), it will add round-trips, which can cause noticable delays. Additionally, expensive crypto takes place on the first connection establishment (above-mentioned CPU could only accept 14 connections per core per second if you foolishly used 4096-bit keys and 100 if you use 2048-bit keys). On subsequent connections, previous sessions are often reused, avoiding the expensive crypto.

So, to summarize:

Transfer on established connection:

  • Delay: nearly none
  • CPU: negligible
  • Bandwidth: negligible

First connection establishment:

  • Delay: additional round-trips
  • Bandwidth: several kilobytes (certificates)
  • CPU on client: medium
  • CPU on server: high

Subsequent connection establishments:

  • Delay: additional round-trip (not sure if one or multiple, may be implementation-dependant)
  • Bandwidth: negligible
  • CPU: nearly none

What is an index in SQL?

A clustered index is like the contents of a phone book. You can open the book at 'Hilditch, David' and find all the information for all of the 'Hilditch's right next to each other. Here the keys for the clustered index are (lastname, firstname).

This makes clustered indexes great for retrieving lots of data based on range based queries since all the data is located next to each other.

Since the clustered index is actually related to how the data is stored, there is only one of them possible per table (although you can cheat to simulate multiple clustered indexes).

A non-clustered index is different in that you can have many of them and they then point at the data in the clustered index. You could have e.g. a non-clustered index at the back of a phone book which is keyed on (town, address)

Imagine if you had to search through the phone book for all the people who live in 'London' - with only the clustered index you would have to search every single item in the phone book since the key on the clustered index is on (lastname, firstname) and as a result the people living in London are scattered randomly throughout the index.

If you have a non-clustered index on (town) then these queries can be performed much more quickly.

Hope that helps!

How do I rename both a Git local and remote branch name?

I had to do the following task to rename local and remote branch:

# Rename the local branch to the new name
git branch -m <old_name> <new_name>

#  Delete the old remote branch
git push origin --delete <old_name>

# push to new remote branch - creates new remote branch
git push origin <new_name>

# set new remote branch as default remote branch for local branch
git branch --set-upstream-to=origin/<new_name> <new_name>

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

The solution is to use the same IP and Port number in both client and server. Try, in client to use TCP_IP = 'write the ip number here' TCP_PORT = writ the port number here s.connect((TCP_IP, TCP_PORT))

Delete commits from a branch in Git

Careful: git reset --hard WILL DELETE YOUR WORKING DIRECTORY CHANGES. Be sure to stash any local changes you want to keep before running this command.

Assuming you are sitting on that commit, then this command will wack it...

git reset --hard HEAD~1

The HEAD~1 means the commit before head.

Or, you could look at the output of git log, find the commit id of the commit you want to back up to, and then do this:

git reset --hard <sha1-commit-id>

If you already pushed it, you will need to do a force push to get rid of it...

git push origin HEAD --force

However, if others may have pulled it, then you would be better off starting a new branch. Because when they pull, it will just merge it into their work, and you will get it pushed back up again.

If you already pushed, it may be better to use git revert, to create a "mirror image" commit that will undo the changes. However, both commits will be in the log.


FYI -- git reset --hard HEAD is great if you want to get rid of WORK IN PROGRESS. It will reset you back to the most recent commit, and erase all the changes in your working tree and index.


Lastly, if you need to find a commit that you "deleted", it is typically present in git reflog unless you have garbage collected your repository.

php stdClass to array

This function worked for me:

function cvf_convert_object_to_array($data) {

    if (is_object($data)) {
        $data = get_object_vars($data);
    }

    if (is_array($data)) {
        return array_map(__FUNCTION__, $data);
    }
    else {
        return $data;
    }
}

Reference: http://carlofontanos.com/convert-stdclass-object-to-array-in-php/

How to load a controller from another controller in codeigniter?

There are many ways by which you can access one controller into another.

class Test1 extends CI_controller
{
    function testfunction(){
        return 1;
    }
}

Then create another class, and include first Class in it, and extend it with your class.

include 'Test1.php';

class Test extends Test1
{
    function myfunction(){
        $this->test();
        echo 1;
    }
}

How to automatically select all text on focus in WPF TextBox?

Taken from here:

Register global event handler in App.xaml.cs file:

protected override void OnStartup(StartupEventArgs e)
{
    EventManager.RegisterClassHandler(typeof(TextBox),TextBox.GotFocusEvent,
    new RoutedEventHandler(TextBox_GotFocus));

    base.OnStartup(e);
}

Then the handler is as simple as:

private void TextBox_GotFocus(object sender, RoutedEventArgs e)
{
    (sender as TextBox).SelectAll();
}

How to play videos in android from assets folder or raw folder?

It sounds maybe like you have the same issue as i do. instead of using MP4, is 3GPP possible? i think i used like HandBrake or something as the video converter... you just need to make sure you have the right encoder, like H.264x or something. sorry for being a little vague, it's been a while. Also, if it's possible, don't bother worrying about android 2.1 anymore, and also, something things just WILL NOT WORK IN EMULATOR. so if it works on a lot of devices, then just assume it works (especially with different manufacurers)

here, you can read my problem and how i solved the issue (after a long time and no one had an answer). i explained in a lot more detail here: android media player not working

How do I create a HTTP Client Request with a cookie?

You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.

To perform a request with a cookie attached just do the following:

var requestify = require('requestify');
requestify.post('http://google.com', {}, {
    cookies: {
        sessionCookie: 'session-cookie-data'   
    }
});

Sql Server equivalent of a COUNTIF aggregate function

Adding on to Josh's answer,

SELECT COUNT(CASE WHEN myColumn=1 THEN AD_CurrentView.PrimaryKeyColumn ELSE NULL END)
FROM AD_CurrentView

Worked well for me (in SQL Server 2012) without changing the 'count' to a 'sum' and the same logic is portable to other 'conditional aggregates'. E.g., summing based on a condition:

SELECT SUM(CASE WHEN myColumn=1 THEN AD_CurrentView.NumberColumn ELSE 0 END)
FROM AD_CurrentView

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

It could be because of the property pageable -> pageSizes: true.

Remove this and check again.

what's the default value of char?

The default char is the character with an int value of 0 (zero).

char NULLCHAR = (char) 0;

char NULLCHAR = '\0';

ImportError: libSM.so.6: cannot open shared object file: No such file or directory

There is now a headless version of opencv-python which removes the graphical dependencies (like libSM). You can see the normal / headless version on the releases page (and the GitHub issue leading to this); just add -headless when installing, e.g.,

pip install opencv-python-headless
# also contrib, if needed
pip install opencv-contrib-python-headless

Call a VBA Function into a Sub Procedure

Calling a Sub Procedure – 3 Way technique

Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it.

Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"

msgbox strFullName
End Sub

Sub Exercise()
    CreateCustomer
End Sub

Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    Call CreateCustomer
End Sub

When calling a procedure, without or without the Call keyword, you can optionally type an opening and a closing parentheses on the right side of its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    CreateCustomer()
End Sub

Procedures and Access Levels

Like a variable access, the access to a procedure can be controlled by an access level. A procedure can be made private or public. To specify the access level of a procedure, precede it with the Private or the Public keyword. Here is an example:

Private Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

The rules that were applied to global variables are the same:

Private: If a procedure is made private, it can be called by other procedures of the same module. Procedures of outside modules cannot access such a procedure.

Also, when a procedure is private, its name does not appear in the Macros dialog box

Public: A procedure created as public can be called by procedures of the same module and by procedures of other modules.

Also, if a procedure was created as public, when you access the Macros dialog box, its name appears and you can run it from there

Node.js EACCES error when listening on most ports

#Windows

Another one reason - maybe your port has been excluded by some reasons.

So, try open CMD under admin rights and run :

  1. net stop winnat
  2. net start winnat

In my case it was enough.

Solution found here : https://medium.com/@Bartleby/ports-are-not-available-listen-tcp-0-0-0-0-3000-165892441b9d

Python math module

You can also import as

from math import *

Then you can use any mathematical function without prefixing math. e.g.

sqrt(4)

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to read the output from git diff?

It's unclear from your question which part of the diffs you find confusing: the actually diff, or the extra header information git prints. Just in case, here's a quick overview of the header.

The first line is something like diff --git a/path/to/file b/path/to/file - obviously it's just telling you what file this section of the diff is for. If you set the boolean config variable diff.mnemonic prefix, the a and b will be changed to more descriptive letters like c and w (commit and work tree).

Next, there are "mode lines" - lines giving you a description of any changes that don't involve changing the content of the file. This includes new/deleted files, renamed/copied files, and permissions changes.

Finally, there's a line like index 789bd4..0afb621 100644. You'll probably never care about it, but those 6-digit hex numbers are the abbreviated SHA1 hashes of the old and new blobs for this file (a blob is a git object storing raw data like a file's contents). And of course, the 100644 is the file's mode - the last three digits are obviously permissions; the first three give extra file metadata information (SO post describing that).

After that, you're on to standard unified diff output (just like the classic diff -U). It's split up into hunks - a hunk is a section of the file containing changes and their context. Each hunk is preceded by a pair of --- and +++ lines denoting the file in question, then the actual diff is (by default) three lines of context on either side of the - and + lines showing the removed/added lines.

Why doesn't CSS ellipsis work in table cell?

Just offering an alternative as I had this problem and none of the other answers here had the desired effect I wanted. So instead I used a list. Now semantically the information I was outputting could have been regarded as both tabular data but also listed data.

So in the end what I did was:

<ul>
    <li class="group">
        <span class="title">...</span>
        <span class="description">...</span>
        <span class="mp3-player">...</span>
        <span class="download">...</span>
        <span class="shortlist">...</span>
    </li>
    <!-- looped <li> -->
</ul>

So basically ul is table, li is tr, and span is td.

Then in CSS I set the span elements to be display:block; and float:left; (I prefer that combination to inline-block as it'll work in older versions of IE, to clear the float effect see: http://css-tricks.com/snippets/css/clear-fix/) and to also have the ellipses:

span {
    display: block;
    float: left;
    width: 100%;

    // truncate when long
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

Then all you do is set the max-widths of your spans and that'll give the list an appearance of a table.

ImportError: cannot import name main when running pip --version command in windows7 32 bit

It works on ubuntu 16.04. Step 1:

 sudo gedit /home/user_name/.local/bin/pip

a file opens with the content:

#!/usr/bin/python

# -*- coding: utf-8 -*-
import re
import sys

from pip import main

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(main())

Change the main to __main__ as it appears below:

#!/usr/bin/python

# -*- coding: utf-8 -*-
import re
import sys

from pip import __main__

if __name__ == '__main__':
    sys.argv[0] = re.sub(r'(-script\.pyw|\.exe)?$', '', sys.argv[0])
    sys.exit(__main__._main())

Save the file and close it. And you are done!

Why does make think the target is up to date?

Maybe you have a file/directory named test in the directory. If this directory exists, and has no dependencies that are more recent, then this target is not rebuild.

To force rebuild on these kind of not-file-related targets, you should make them phony as follows:

.PHONY: all test clean

Note that you can declare all of your phony targets there.

A phony target is one that is not really the name of a file; rather it is just a name for a recipe to be executed when you make an explicit request.

ImportError: No module named 'pygame'

First execute python3 then type the command import pygame,now you can see the output

vuejs update parent data from child component

I agree with the event emitting and v-model answers for those above. However, I thought I would post what I found about components with multiple form elements that want to emit back to their parent since this seems one of the first articles returned by google.

I know the question specifies a single input, but this seemed the closest match and might save people some time with similar vue components. Also, no one has mentioned the .sync modifier yet.

As far as I know, the v-model solution is only suited to one input returning to their parent. I took a bit of time looking for it but Vue (2.3.0) documentation does show how to sync multiple props sent into the component back to the parent (via emit of course).

It is appropriately called the .sync modifier.

Here is what the documentation says:

In some cases, we may need “two-way binding” for a prop. Unfortunately, true two-way binding can create maintenance issues, because child components can mutate the parent without the source of that mutation being obvious in both the parent and the child.

That’s why instead, we recommend emitting events in the pattern of update:myPropName. For example, in a hypothetical component with a title prop, we could communicate the intent of assigning a new value with:

this.$emit('update:title', newTitle)

Then the parent can listen to that event and update a local data property, if it wants to. For example:

<text-document   
 v-bind:title="doc.title"  
 v-on:update:title="doc.title = $event"
></text-document>

For convenience, we offer a shorthand for this pattern with the .sync modifier:

<text-document v-bind:title.sync="doc.title"></text-document>

You can also sync multiple at a time by sending through an object. Check out the documentation here

Trigger change() event when setting <select>'s value with val() function

I had a very similar issue and I'm not quite sure what you're having a problem with, as your suggested code worked great for me. It immediately (a requirement of yours) triggers the following change code.

$('#selectField').change(function(){
    if($('#selectField').val() == 'N'){
        $('#secondaryInput').hide();
    } else {
        $('#secondaryInput').show();
}
});

Then I take the value from the database (this is used on a form for both new input and editing existing records), set it as the selected value, and add the piece I was missing to trigger the above code, ".change()".

$('#selectField').val(valueFromDatabase).change();

So that if the existing value from the database is 'N', it immediately hides the secondary input field in my form.

Pass Model To Controller using Jquery/Ajax

//C# class

public class DashBoardViewModel 
{
    public int Id { get; set;} 
    public decimal TotalSales { get; set;} 
    public string Url { get; set;} 
     public string MyDate{ get; set;} 
}

//JavaScript file
//Create dashboard.js file
$(document).ready(function () {

    // See the html on the View below
    $('.dashboardUrl').on('click', function(){
        var url = $(this).attr("href"); 
    });

    $("#inpDateCompleted").change(function () {   

        // Construct your view model to send to the controller
        // Pass viewModel to ajax function 

        // Date
        var myDate = $('.myDate').val();

        // IF YOU USE @Html.EditorFor(), the myDate is as below
        var myDate = $('#MyDate').val();
        var viewModel = { Id : 1, TotalSales: 50, Url: url, MyDate: myDate };


        $.ajax({
            type: 'GET',
            dataType: 'json',
            cache: false,
            url: '/Dashboard/IndexPartial',
            data: viewModel ,
            success: function (data, textStatus, jqXHR) {
                //Do Stuff 
                $("#DailyInvoiceItems").html(data.Id);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                //Do Stuff or Nothing
            }
        });

    });
});

//ASP.NET 5 MVC 6 Controller
public class DashboardController {

    [HttpGet]
    public IActionResult IndexPartial(DashBoardViewModel viewModel )
    {
        // Do stuff with my model
        var model = new DashBoardViewModel {  Id = 23 /* Some more results here*/ };
        return Json(model);
    }
}

// MVC View 
// Include jQuerylibrary
// Include dashboard.js 
<script src="~/Scripts/jquery-2.1.3.js"></script>
<script src="~/Scripts/dashboard.js"></script>
// If you want to capture your URL dynamically 

<div>
    <a class="dashboardUrl" href ="@Url.Action("IndexPartial","Dashboard")"> LinkText </a>
</div>
<div>
    <input class="myDate" type="text"/>
//OR
   @Html.EditorFor(model => model.MyDate) 
</div>

How to send parameters with jquery $.get()

I got this working : -

$.get('api.php', 'client=mikescafe', function(data) {
...
});

It sends via get the string ?client=mikescafe then collect this variable in api.php, and use it in your mysql statement.

How to parse date string to Date?

A parse exception is a checked exception, so you must catch it with a try-catch when working with parsing Strings to Dates, as @miku suggested...

Turn off deprecated errors in PHP 5.3

You can do it in code by calling the following functions.

error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

or

error_reporting(E_ALL ^ E_DEPRECATED);

Changing route doesn't scroll to top in the new page

This Worked for me including autoscroll

<div class="ngView" autoscroll="true" >

RadioGroup: How to check programmatically

Watch out! checking the radiobutton with setChecked() is not changing the state inside the RadioGroup. For example this method from the radioGroup will return a wrong result: getCheckedRadioButtonId().

Check the radioGroup always with

mOption.check(R.id.option1);

you've been warned ;)

Why and how to fix? IIS Express "The specified port is in use"

I had the same problem, but no proccess appeared neither in netstat nor in resmon.

What solved the problem for me was closing all the open browser windows.

Include CSS,javascript file in Yii Framework

Easy in your conf/main.php. This is my example with bootstrap. You can see that here

'components'=>array(
    'clientScript' => array(
        'scriptMap' => array(
            'jquery.js'=>false,  //disable default implementation of jquery
            'jquery.min.js'=>false,  //desable any others default implementation
            'core.css'=>false, //disable
            'styles.css'=>false,  //disable
            'pager.css'=>false,   //disable
            'default.css'=>false,  //disable
        ),
        'packages'=>array(
            'jquery'=>array(                             // set the new jquery
                'baseUrl'=>'bootstrap/',
                'js'=>array('js/jquery-1.7.2.min.js'),
            ),
            'bootstrap'=>array(                       //set others js libraries
                'baseUrl'=>'bootstrap/',
                'js'=>array('js/bootstrap.min.js'),
                'css'=>array(                        // and css
                    'css/bootstrap.min.css',
                    'css/custom.css',
                    'css/bootstrap-responsive.min.css',
                ),
                'depends'=>array('jquery'),         // cause load jquery before load this.
            ),
        ),
    ),
),

How to initialize a list with constructor?

Are you looking for this?

ContactNumbers = new List<ContactNumber>(){ new ContactNumber("555-5555"),
                                            new ContactNumber("555-1234"),
                                            new ContactNumber("555-5678") };

How to get text from each cell of an HTML table?

I have not used Selenium 2. Selenium 1.x has selenium.getTable("tablename".columnNumber.rowNumber) to reach the required cell. May be you can use webdriverbackedselenium and do this.

And you can get the total rows and columns by using

int numOfRows = selenium.getXpathCount("//table[@id='tableid']//tr")

int numOfCols=selenium.getXpathCount("//table[@id='tableid']//tr//td")

How to get the filename without the extension in Java?

While I am a big believer in reusing libraries, the org.apache.commons.io JAR is 174KB, which is noticably large for a mobile app.

If you download the source code and take a look at their FilenameUtils class, you can see there are a lot of extra utilities, and it does cope with Windows and Unix paths, which is all lovely.

However, if you just want a couple of static utility methods for use with Unix style paths (with a "/" separator), you may find the code below useful.

The removeExtension method preserves the rest of the path along with the filename. There is also a similar getExtension.

/**
 * Remove the file extension from a filename, that may include a path.
 * 
 * e.g. /path/to/myfile.jpg -> /path/to/myfile 
 */
public static String removeExtension(String filename) {
    if (filename == null) {
        return null;
    }

    int index = indexOfExtension(filename);

    if (index == -1) {
        return filename;
    } else {
        return filename.substring(0, index);
    }
}

/**
 * Return the file extension from a filename, including the "."
 * 
 * e.g. /path/to/myfile.jpg -> .jpg
 */
public static String getExtension(String filename) {
    if (filename == null) {
        return null;
    }

    int index = indexOfExtension(filename);

    if (index == -1) {
        return filename;
    } else {
        return filename.substring(index);
    }
}

private static final char EXTENSION_SEPARATOR = '.';
private static final char DIRECTORY_SEPARATOR = '/';

public static int indexOfExtension(String filename) {

    if (filename == null) {
        return -1;
    }

    // Check that no directory separator appears after the 
    // EXTENSION_SEPARATOR
    int extensionPos = filename.lastIndexOf(EXTENSION_SEPARATOR);

    int lastDirSeparator = filename.lastIndexOf(DIRECTORY_SEPARATOR);

    if (lastDirSeparator > extensionPos) {
        LogIt.w(FileSystemUtil.class, "A directory separator appears after the file extension, assuming there is no file extension");
        return -1;
    }

    return extensionPos;
}

powershell - extract file name and extension

Check the BaseName and Extension properties of the FileInfo object.

Text Progress Bar in the Console

Try to install this package: pip install progressbar2 :

import time
import progressbar

for i in progressbar.progressbar(range(100)):
    time.sleep(0.02)

progresssbar github: https://github.com/WoLpH/python-progressbar

How to find children of nodes using BeautifulSoup

try this:

li = soup.find("li", { "class" : "test" })
children = li.find_all("a") # returns a list of all <a> children of li

other reminders:

The find method only gets the first occurring child element. The find_all method gets all descendant elements and are stored in a list.

How to delete migration files in Rails 3

You can also run a down migration like so:

rake db:migrate:down VERSION=versionnumber

Refer to the Ruby on Rails guide on migrations for more info.

How to export a MySQL database to JSON?

Another solution, if you are using Ruby, is to write a connection script to the database with ActiveRecord. You will need to install it first

gem install activerecord

# ruby ./export-mysql.rb
require 'rubygems'
require 'active_record'

ActiveRecord::Base.establish_connection(
  :adapter => "mysql",
  :database => "database_name",
  :username => "root",
  :password => "",
  :host => "localhost"
)

class Event < ActiveRecord::Base; end
class Person < ActiveRecord::Base; end

File.open("events.json", "w") { |f| f.write Event.all.to_json }
File.open("people.json", "w") { |f| f.write Person.all.to_json }

You can also add methods to the ActiveRecord classes if you want to manipulate data first or include or exclude certain columns.

Person.all.to_json(:only => [ :id, :name ])

With ActiveRecord you are not limited to JSON. You can just as easily export as XML or YAML

Person.all.to_xml
Person.all.to_yaml

You are not limited to MySQL. Any database supported by ActiveRecord (Postgres, SQLite3, Oracle... etc).

And it's worth mentioning you could open another handle to a database

require 'active_record'

ActiveRecord::Base.configurations["mysql"] = {
  :adapter  => 'mysql',
  :database => 'database_name',
  :username => 'root',
  :password => '',
  :host     => 'localhost'
}


ActiveRecord::Base.configurations["sqlite3"] = {
  :adapter  => 'sqlite3',
  :database => 'db/development.sqlite3'
}

class PersonMySQL < ActiveRecord::Base
  establish_connection "mysql"
end

class PersonSQLite < ActiveRecord::Base
  establish_connection "sqlite3"
end


PersonMySQL.all.each do |person|
    PersonSQLite.create(person.attributes.except("id"))
end

Here is a quick little blog post about it http://www.seanbehan.com/how-to-export-a-mysql-database-to-json-csv-and-xml-with-ruby-and-the-activerecord-gem

How can I get an object's absolute position on the page in Javascript?

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

How do I parse command line arguments in Bash?

If you are making scripts that are interchangeable with other utilities, below flexibility may be useful.

Either:

command -x=myfilename.ext --another_switch 

Or:

command -x myfilename.ext --another_switch

Here is the code:

STD_IN=0

prefix=""
key=""
value=""
for keyValue in "$@"
do
  case "${prefix}${keyValue}" in
    -i=*|--input_filename=*)  key="-i";     value="${keyValue#*=}";; 
    -ss=*|--seek_from=*)      key="-ss";    value="${keyValue#*=}";;
    -t=*|--play_seconds=*)    key="-t";     value="${keyValue#*=}";;
    -|--stdin)                key="-";      value=1;;
    *)                                      value=$keyValue;;
  esac
  case $key in
    -i) MOVIE=$(resolveMovie "${value}");  prefix=""; key="";;
    -ss) SEEK_FROM="${value}";          prefix=""; key="";;
    -t)  PLAY_SECONDS="${value}";           prefix=""; key="";;
    -)   STD_IN=${value};                   prefix=""; key="";; 
    *)   prefix="${keyValue}=";;
  esac
done

jQuery validate Uncaught TypeError: Cannot read property 'nodeName' of null

I had this problem in a Backbone project: my view contains a input and is re-rendered. Here is what happens (example for a checkbox):

  • The first render occurs;
  • jquery.validate is applied, adding an event onClick on the input;
  • View re-renders, the original input disappears but jquery.validate is still bound to it.

The solution is to update the input rather than re-render it completely. Here is an idea of the implementation:

var MyView = Backbone.View.extend({
    render: function(){
        if(this.rendered){
            this.update();
            return;
        }
        this.rendered = true;

        this.$el.html(tpl(this.model.toJSON()));
        return this;
    },
    update: function(){
        this.$el.find('input[type="checkbox"]').prop('checked', this.model.get('checked'));
        return this;
    }
});

This way you don't have to change any existing code calling render(), simply make sure update() keeps your HTML in sync and you're good to go.

Get statistics for each group (such as count, mean, etc) using pandas GroupBy?

On groupby object, the agg function can take a list to apply several aggregation methods at once. This should give you the result you need:

df[['col1', 'col2', 'col3', 'col4']].groupby(['col1', 'col2']).agg(['mean', 'count'])

CSS height 100% percent not working

For code mirror divs refer to the manual, these sections might be useful to you:

http://codemirror.net/demo/fullscreen.html

var editor = CodeMirror.fromTextArea(document.getElementById("code"), {
  lineNumbers: true,
  theme: "night",
  extraKeys: {
    "F11": function(cm) {
      cm.setOption("fullScreen", !cm.getOption("fullScreen"));
    },
    "Esc": function(cm) {
      if (cm.getOption("fullScreen")) cm.setOption("fullScreen", false);
    }
  }
});

And also take a look at:

http://codemirror.net/demo/resize.html

Also a comment:

Inline styling is horrible you should avoid this at all costs, not only will it confuse you, it's poor practice.

setImmediate vs. nextTick

Use setImmediate if you want to queue the function behind whatever I/O event callbacks that are already in the event queue. Use process.nextTick to effectively queue the function at the head of the event queue so that it executes immediately after the current function completes.

So in a case where you're trying to break up a long running, CPU-bound job using recursion, you would now want to use setImmediate rather than process.nextTick to queue the next iteration as otherwise any I/O event callbacks wouldn't get the chance to run between iterations.

cannot open shared object file: No such file or directory

When working on a supercomputer, I received this error when I ran:

module load python/3.4.0
screen
python

To resolve the error, I simply needed to reload the module in the screen terminal:

module load python/3.4.0
python

Ignoring new fields on JSON objects using Jackson

As stated above the annotations only works if this is specified in the parent POJO class and not the class where the conversion from JSON to Java Object is taking place.

The other alternative without touching the parent class and causing disruptions is to implement your own mapper config only for the mapper methods you need for this.

Also the package of the Deserialization feature has been moved. DeserializationConfig.FAIL_ON_UNKNOWN_PROPERTIES to DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES

import org.codehaus.jackson.map.DeserializationConfig;
...
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);