Programs & Examples On #Cruisecontrol.net

CruiseControl.NET is a .NET-based framework for supporting a continuous build process. It includes, but is not limited to, plugins for email notification, Ant, and various source control tools.

Create a new cmd.exe window from within another cmd.exe prompt

simple write in your bat file

@cmd

or

@cmd /k "command1&command2"

HTTP Error 500.30 - ANCM In-Process Start Failure

If you are using Visual Studio, and have any instances of it running, close them all.

You should find a .vs sub folder where your Visual Studio solution (.sln file) resides.
Delete the .vs folder and try again with the in-process hosting model.

Convert List<Object> to String[] in Java

You have to loop through the list and fill your String[].

String[] array = new String[lst.size()];
int index = 0;
for (Object value : lst) {
  array[index] = (String) value;
  index++;
}

If the list would be of String values, List then this would be as simple as calling lst.toArray(new String[0]);

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

Java - Check Not Null/Empty else assign default value

I know the question is really old, but with generics one can add a more generalized method with will work for all types.

public static <T> T getValueOrDefault(T value, T defaultValue) {
    return value == null ? defaultValue : value;
}

How to execute a java .class from the command line

With Java 11 you won't have to go through this rigmarole anymore!

Instead, you can do this:

> java MyApp.java

You don't have to compile beforehand, as it's all done in one step.

You can get the Java 11 JDK here: JDK 11 GA Release

Convert binary to ASCII and vice versa

Built-in only python

Here is a pure python method for simple strings, left here for posterity.

def string2bits(s=''):
    return [bin(ord(x))[2:].zfill(8) for x in s]

def bits2string(b=None):
    return ''.join([chr(int(x, 2)) for x in b])

s = 'Hello, World!'
b = string2bits(s)
s2 = bits2string(b)

print 'String:'
print s

print '\nList of Bits:'
for x in b:
    print x

print '\nString:'
print s2

String:
Hello, World!

List of Bits:
01001000
01100101
01101100
01101100
01101111
00101100
00100000
01010111
01101111
01110010
01101100
01100100
00100001

String:
Hello, World!

Drop multiple tables in one shot in MySQL

Example:

Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.

DROP TABLE IF EXISTS B,C,A;

This can be placed in the beginning of the script instead of individually dropping each table.

Chaining multiple filter() in Django, is this a bug?

From Django docs :

To handle both of these situations, Django has a consistent way of processing filter() calls. Everything inside a single filter() call is applied simultaneously to filter out items matching all those requirements. Successive filter() calls further restrict the set of objects, but for multi-valued relations, they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.

  • It is clearly said that multiple conditions in a single filter() are applied simultaneously. That means that doing :
objs = Mymodel.objects.filter(a=True, b=False)

will return a queryset with raws from model Mymodel where a=True AND b=False.

  • Successive filter(), in some case, will provide the same result. Doing :
objs = Mymodel.objects.filter(a=True).filter(b=False)

will return a queryset with raws from model Mymodel where a=True AND b=False too. Since you obtain "first" a queryset with records which have a=True and then it's restricted to those who have b=False at the same time.

  • The difference in chaining filter() comes when there are multi-valued relations, which means you are going through other models (such as the example given in the docs, between Blog and Entry models). It is said that in that case (...) they apply to any object linked to the primary model, not necessarily those objects that were selected by an earlier filter() call.

Which means that it applies the successives filter() on the target model directly, not on previous filter()

If I take the example from the docs :

Blog.objects.filter(entry__headline__contains='Lennon').filter(entry__pub_date__year=2008)

remember that it's the model Blog that is filtered, not the Entry. So it will treat the 2 filter() independently.

It will, for instance, return a queryset with Blogs, that have entries that contain 'Lennon' (even if they are not from 2008) and entries that are from 2008 (even if their headline does not contain 'Lennon')

THIS ANSWER goes even further in the explanation. And the original question is similar.

how to convert a string to an array in php

There is a function in PHP specifically designed for that purpose, str_word_count(). By default it does not take into account the numbers and multibyte characters, but they can be added as a list of additional characters in the charlist parameter. Charlist parameter also accepts a range of characters as in the example.

One benefit of this function over explode() is that the punctuation marks, spaces and new lines are avoided.

$str = "1st example:
        Alte Füchse gehen schwer in die Falle.    ";

print_r( str_word_count( $str, 1, '1..9ü' ) );

/* output:
Array
(
    [0] => 1st
    [1] => example
    [2] => Alte
    [3] => Füchse
    [4] => gehen
    [5] => schwer
    [6] => in
    [7] => die
    [8] => Falle
)
*/

Combine two data frames by rows (rbind) when they have different sets of columns

You could also just pull out the common column names.

> cols <- intersect(colnames(df1), colnames(df2))
> rbind(df1[,cols], df2[,cols])

open existing java project in eclipse

  1. File -> Import -> Existing Project into Workspace
  2. Browse for that directory.

Alternative: Check out the code in SVN to some folder

  1. Create a new folder in windows
  2. In eclipse File -> switchWorkspace -> newFolderName
  3. close the welcome window in eclipse
  4. In eclipse File -> Import -> Existing project into workspce-> select root dir -> browse and show the svn checkout folder

Conditional WHERE clause in SQL Server

Try this

SELECT 
    DateAppr,
    TimeAppr,
    TAT,
    LaserLTR,
    Permit,
    LtrPrinter,
    JobName,
    JobNumber,
    JobDesc,
    ActQty,
    (ActQty-LtrPrinted) AS L,
    (ActQty-QtyInserted) AS M,
    ((ActQty-LtrPrinted)-(ActQty-QtyInserted)) AS N
FROM 
    [test].[dbo].[MM]
WHERE 
    DateDropped = 0
    AND (
    (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0) 
    OR 
    (ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)
    )

You can read more about conditional WHERE here.

how to display a javascript var in html body

_x000D_
_x000D_
<script type="text/javascript">_x000D_
        function get_param(param) {_x000D_
   var search = window.location.search.substring(1);_x000D_
   var compareKeyValuePair = function(pair) {_x000D_
      var key_value = pair.split('=');_x000D_
      var decodedKey = decodeURIComponent(key_value[0]);_x000D_
      var decodedValue = decodeURIComponent(key_value[1]);_x000D_
      if(decodedKey == param) return decodedValue;_x000D_
      return null;_x000D_
   };_x000D_
_x000D_
   var comparisonResult = null;_x000D_
_x000D_
   if(search.indexOf('&') > -1) {_x000D_
      var params = search.split('&');_x000D_
      for(var i = 0; i < params.length; i++) {_x000D_
         comparisonResult = compareKeyValuePair(params[i]); _x000D_
         if(comparisonResult !== null) {_x000D_
            break;_x000D_
         }_x000D_
      }_x000D_
   } else {_x000D_
      comparisonResult = compareKeyValuePair(search);_x000D_
   }_x000D_
_x000D_
   return comparisonResult;_x000D_
}_x000D_
_x000D_
var parcelNumber = get_param('parcelNumber'); //abc_x000D_
var registryId  = get_param('registryId'); //abc_x000D_
var registrySectionId = get_param('registrySectionId'); //abc_x000D_
var apartmentNumber = get_param('apartmentNumber'); //abc_x000D_
_x000D_
        _x000D_
    </script>
_x000D_
_x000D_
_x000D_

then in the page i call the values like so:

_x000D_
_x000D_
 <td class="tinfodd"> <script  type="text/javascript">_x000D_
                                                    document.write(registrySectionId)_x000D_
                                                    </script></td>
_x000D_
_x000D_
_x000D_

How can I make a program wait for a variable change in javascript?

You can use properties:

Object.defineProperty MDN documentation

Example:

function def(varName, onChange) {
    var _value;

    Object.defineProperty(this, varName, {
        get: function() {
            return _value;
        },
        set: function(value) {
            if (onChange)
                onChange(_value, value);
            _value = value;
        }
    });

    return this[varName];
}

def('myVar', function (oldValue, newValue) {
    alert('Old value: ' + oldValue + '\nNew value: ' + newValue);
});

myVar = 1; // alert: Old value: undefined | New value: 1
myVar = 2; // alert: Old value: 1 | New value: 2

Pandas read_csv low_memory and dtype options

I was facing a similar issue when processing a huge csv file (6 million rows). I had three issues:

  1. the file contained strange characters (fixed using encoding)
  2. the datatype was not specified (fixed using dtype property)
  3. Using the above I still faced an issue which was related with the file_format that could not be defined based on the filename (fixed using try .. except..)
    df = pd.read_csv(csv_file,sep=';', encoding = 'ISO-8859-1',
                     names=['permission','owner_name','group_name','size','ctime','mtime','atime','filename','full_filename'],
                     dtype={'permission':str,'owner_name':str,'group_name':str,'size':str,'ctime':object,'mtime':object,'atime':object,'filename':str,'full_filename':str,'first_date':object,'last_date':object})
    
    try:
        df['file_format'] = [Path(f).suffix[1:] for f in df.filename.tolist()]
    except:
        df['file_format'] = ''

How to check if a database exists in SQL Server?

From a Microsoft's script:

DECLARE @dbname nvarchar(128)
SET @dbname = N'Senna'

IF (EXISTS (SELECT name 
FROM master.dbo.sysdatabases 
WHERE ('[' + name + ']' = @dbname 
OR name = @dbname)))

-- code mine :)
PRINT 'db exists'

How can I get the index from a JSON object with value?

Function base solution for get index from a JSON object with value by VanillaJS.

Exemple: https://codepen.io/gmkhussain/pen/mgmEEW

_x000D_
_x000D_
    var data= [{_x000D_
      "name": "placeHolder",_x000D_
      "section": "right"_x000D_
    }, {_x000D_
      "name": "Overview",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "ByFunction",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "Time",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allFit",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allbMatches",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allOffers",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allInterests",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "allResponses",_x000D_
      "section": "left"_x000D_
    }, {_x000D_
      "name": "divChanged",_x000D_
      "section": "right"_x000D_
    }];_x000D_
    _x000D_
    _x000D_
    // create function_x000D_
    function findIndex(jsonData, findThis){_x000D_
      var indexNum = jsonData.findIndex(obj => obj.name==findThis);  _x000D_
_x000D_
    //Output of result_x000D_
          document.querySelector("#output").innerHTML=indexNum;_x000D_
          console.log(" Array Index number: " + indexNum + " , value of " + findThis );_x000D_
    }_x000D_
    _x000D_
    _x000D_
    /* call function */_x000D_
    findIndex(data, "allOffers");
_x000D_
Output of index number : <h1 id="output"></h1>
_x000D_
_x000D_
_x000D_

Automatically start forever (node) on system restart

Forever was not made to get node applications running as services. The right approach is to either create an /etc/inittab entry (old linux systems) or an upstart (newer linux systems).

Here's some documentation on how to set this up as an upstart: https://github.com/cvee/node-upstart

Options for HTML scraping?

The Ruby world's equivalent to Beautiful Soup is why_the_lucky_stiff's Hpricot.

How to find the last day of the month from date?

You could create a date for the first of the next month, and then use strtotime("-1 day", $firstOfNextMonth)

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

It may help to use a different constructor for Uri.

If you have the server name

string server = "http://www.myserver.com";

and have a relative Uri path to append to it, e.g.

string relativePath = "sites/files/images/picture.png"

When creating a Uri from these two I get the "format could not be determined" exception unless I use the constructor with the UriKind argument, i.e.

// this works, because the protocol is included in the string
Uri serverUri = new Uri(server);

// needs UriKind arg, or UriFormatException is thrown
Uri relativeUri = new Uri(relativePath, UriKind.Relative); 

// Uri(Uri, Uri) is the preferred constructor in this case
Uri fullUri = new Uri(serverUri, relativeUri);

Convert HTML to NSAttributedString in iOS

honoring font family, dynamic font I've concocted this abomination:

extension NSAttributedString
{
    convenience fileprivate init?(html: String, font: UIFont? = Font.dynamic(style: .subheadline))
    {
        guard let data = html.data(using: String.Encoding.utf8, allowLossyConversion: true) else {
        var totalString = html
        /*
         https://stackoverflow.com/questions/32660748/how-to-use-apples-new-san-francisco-font-on-a-webpage
            .AppleSystemUIFont I get in font.familyName does not work
         while -apple-system does:
         */
        var ffamily = "-apple-system"
        if let font = font {
            let lLDBsucks = font.familyName
            if !lLDBsucks.hasPrefix(".appleSystem") {
                ffamily = font.familyName
            }
            totalString = "<style>\nhtml * {font-family: \(ffamily) !important;}\n            </style>\n" + html
        }
        guard let data = totalString.data(using: String.Encoding.utf8, allowLossyConversion: true) else {
            return nil
        }
        assert(Thread.isMainThread)
        guard let attributedText = try?  NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil) else {
            return nil
        }
        let mutable = NSMutableAttributedString(attributedString: attributedText)
        if let font = font {
        do {
            var found = false
            mutable.beginEditing()
            mutable.enumerateAttribute(NSAttributedString.Key.font, in: NSMakeRange(0, attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (value, range, stop) in
                    if let oldFont = value as? UIFont {
                        let newsize = oldFont.pointSize * 15 * Font.scaleHeruistic / 12
                        let newFont = oldFont.withSize(newsize)
                        mutable.addAttribute(NSAttributedString.Key.font, value: newFont, range: range)
                        found = true
                    }
                }
                if !found {
                    // No font was found - do something else?
                }

            mutable.endEditing()
            
//            mutable.addAttribute(.font, value: font, range: NSRange(location: 0, length: mutable.length))
        }
        self.init(attributedString: mutable)
    }

}

alternatively you can use the versions this was derived from and set font on UILabel after setting attributedString

this will clobber the size and boldness encapsulated in the attributestring though

kudos for reading through all the answers up to here. You are a very patient man woman or child.

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

None of the above worked out for me until I changed the Action as [HttpPost]. and made the ajax type as POST.

    [HttpPost]
    public JsonResult GetSelectedSignalData(string signal1,...)
    {
         JsonResult result = new JsonResult();
         var signalData = GetTheData();
         try
         {
              var serializer = new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = Int32.MaxValue, RecursionLimit = 100 };

            result.Data = serializer.Serialize(signalData);
            return Json(result, JsonRequestBehavior.AllowGet);
            ..
            ..
            ...

    }

And the ajax call as

$.ajax({
    type: "POST",
    url: some_url,
    data: JSON.stringify({  signal1: signal1,.. }),
    contentType: "application/json; charset=utf-8",
    success: function (data) {
        if (data !== null) {
            setValue();
        }

    },
    failure: function (data) {
        $('#errMessage').text("Error...");
    },
    error: function (data) {
        $('#errMessage').text("Error...");
    }
});

Identifier is undefined

From the update 2 and after narrowing down the problem scope, we can easily find that there is a brace missing at the end of the function addWord. The compiler will never explicitly identify such a syntax error. instead, it will assume that the missing function definition located in some other object file. The linker will complain about it and hence directly will be categorized under one of the broad the error phrases which is identifier is undefined. Reasonably, because with the current syntax the next function definition (in this case is ac_search) will be included under the addWord scope. Hence, it is not a global function anymore. And that is why compiler will not see this function outside addWord and will throw this error message stating that there is no such a function. A very good elaboration about the compiler and the linker can be found in this article

What is a mixin, and why are they useful?

It's not a Python example but in the D programing language the term mixin is used to refer to a construct used much the same way; adding a pile of stuff to a class.

In D (which by the way doesn't do MI) this is done by inserting a template (think syntactically aware and safe macros and you will be close) into a scope. This allows for a single line of code in a class, struct, function, module or whatever to expand to any number of declarations.

Jquery function BEFORE form submission

Based on Wakas Bukhary answer, you could make it async by puting the last line in the response scope.

$('#myform').submit(function(event) {

  event.preventDefault(); //this will prevent the default submit
  var _this = $(this); //store form so it can be accessed later

  $.ajax('GET', 'url').then(function(resp) {

    // your code here 

   _this.unbind('submit').submit(); // continue the submit unbind preventDefault
  })  
}

What datatype to use when storing latitude and longitude data in SQL databases?

For longitudes use: Decimal(9,6), and latitudes use: Decimal(8,6)

If you're not used to precision and scale parameters, here's a format string visual:

###.###### and ##.######

Javascript: Extend a Function

Use extendFunction.js

init = extendFunction(init, function(args) {
  doSomethingHereToo();
});

But in your specific case, it's easier to extend the global onload function:

extendFunction('onload', function(args) {
  doSomethingHereToo();
});

I actually really like your question, it's making me think about different use cases.

For javascript events, you really want to add and remove handlers - but for extendFunction, how could you later remove functionality? I could easily add a .revert method to extended functions, so init = init.revert() would return the original function. Obviously this could lead to some pretty bad code, but perhaps it lets you get something done without touching a foreign part of the codebase.

#include errors detected in vscode

1.Install Mingw-w64

2.Then Edit environment variables for your account "C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin"

3.Reload

  • For MAC

    1.Open search ,command + shift +P, and run this code “c/c++ edit configurations (ui)”

    2.open file c_cpp_properties.json and update the includePath from "${workspaceFolder}/**" to "${workspaceFolder}/inc"

How to SELECT WHERE NOT EXIST using LINQ?

from s in context.shift
where !context.employeeshift.Any(es=>(es.shiftid==s.shiftid)&&(es.empid==57))
select s;

Hope this helps

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Most updated solution

If you are using Javascript, the best solution that I came up with is using match instead of exec method. Then, iterate matches and remove the delimiters with the result of the first group using $1

const text = "This is a test string [more or less], [more] and [less]";
const regex = /\[(.*?)\]/gi;
const resultMatchGroup = text.match(regex); // [ '[more or less]', '[more]', '[less]' ]
const desiredRes = resultMatchGroup.map(match => match.replace(regex, "$1"))
console.log("desiredRes", desiredRes); // [ 'more or less', 'more', 'less' ]

As you can see, this is useful for multiple delimiters in the text as well

Converting between datetime, Timestamp and datetime64

If you want to convert an entire pandas series of datetimes to regular python datetimes, you can also use .to_pydatetime().

pd.date_range('20110101','20110102',freq='H').to_pydatetime()

> [datetime.datetime(2011, 1, 1, 0, 0) datetime.datetime(2011, 1, 1, 1, 0)
   datetime.datetime(2011, 1, 1, 2, 0) datetime.datetime(2011, 1, 1, 3, 0)
   ....

It also supports timezones:

pd.date_range('20110101','20110102',freq='H').tz_localize('UTC').tz_convert('Australia/Sydney').to_pydatetime()

[ datetime.datetime(2011, 1, 1, 11, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
 datetime.datetime(2011, 1, 1, 12, 0, tzinfo=<DstTzInfo 'Australia/Sydney' EST+11:00:00 DST>)
....

NOTE: If you are operating on a Pandas Series you cannot call to_pydatetime() on the entire series. You will need to call .to_pydatetime() on each individual datetime64 using a list comprehension or something similar:

datetimes = [val.to_pydatetime() for val in df.problem_datetime_column]

Proper way to initialize C++ structs

In C++ classes/structs are identical (in terms of initialization).

A non POD struct may as well have a constructor so it can initialize members.
If your struct is a POD then you can use an initializer.

struct C
{
    int x; 
    int y;
};

C  c = {0}; // Zero initialize POD

Alternatively you can use the default constructor.

C  c = C();      // Zero initialize using default constructor
C  c{};          // Latest versions accept this syntax.
C* c = new C();  // Zero initialize a dynamically allocated object.

// Note the difference between the above and the initialize version of the constructor.
// Note: All above comments apply to POD structures.
C  c;            // members are random
C* c = new C;    // members are random (more officially undefined).

I believe valgrind is complaining because that is how C++ used to work. (I am not exactly sure when C++ was upgraded with the zero initialization default construction). Your best bet is to add a constructor that initializes the object (structs are allowed constructors).

As a side note:
A lot of beginners try to value init:

C c(); // Unfortunately this is not a variable declaration.
C c{}; // This syntax was added to overcome this confusion.

// The correct way to do this is:
C c = C();

A quick search for the "Most Vexing Parse" will provide a better explanation than I can.

Why doesn't calling a Python string method do anything unless you assign its output?

All string functions as lower, upper, strip are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable, it will fail.

x = 'hello'
x[0] = 'i' #'str' object does not support item assignment

There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them

SQL Query Where Date = Today Minus 7 Days

Use the built in functions:

SELECT URLX, COUNT(URLx) AS Count
FROM ExternalHits
WHERE datex BETWEEN DATE_SUB(NOW(), INTERVAL 7 DAY) AND NOW()
GROUP BY URLx
ORDER BY Count DESC; 

How can I bind to the change event of a textarea in jQuery?

Try this

 $('textarea').trigger('change');
 $("textarea").bind('cut paste', function(e) { });

Python: Pandas Dataframe how to multiply entire column with a scalar

try using apply function.

df['quantity'] = df['quantity'].apply(lambda x: x*-1)

Dump a NumPy array into a csv file

numpy.savetxt saves an array to a text file.

import numpy
a = numpy.asarray([ [1,2,3], [4,5,6], [7,8,9] ])
numpy.savetxt("foo.csv", a, delimiter=",")

Java SecurityException: signer information does not match

A simple way around it is just try changing the order of your imported jar files which can be done from (Eclipse). Right click on your package -> Build Path -> Configure build path -> References and Libraries -> Order and Export. Try changing the order of jars which contain signature files.

User GETDATE() to put current date into SQL variable

You can also use CURRENT_TIMESTAMP for this.

According to BOL CURRENT_TIMESTAMP is the ANSI SQL euivalent to GETDATE()

DECLARE @LastChangeDate AS DATE;
SET @LastChangeDate = CURRENT_TIMESTAMP;

Why can't I see the "Report Data" window when creating reports?

I had the same problem, but in c# 2012 I closed the "report data" and I couldn't find it and I finally found a solution to this issue.

This is my method:

VIEW >> TOOLBARS >> CUSTOMIZE >> COMMANDS ... select from the "Menu bar" .. VIEW.

OK now in the "Controls" find the "REPORT DATA", select it and MOVE it UP, close the menu. After that select a file.rdlc and click on the "View" ... OK Finally will be appeared "REPORT DATA"...

Embed YouTube Video with No Ads

Whether ads are shown on a video is up to the content owner of that video. It's not something that the embedder can control.

If you had permission from the content owners of the videos to upload copies in your own account, and then ensured that your account was set up with monetization turned off, then that would prevent ads from showing during playback. It's up to you to work out that arrangement/permission with the original videos' owners, of course.

(It's also worth pointing out that if your goal is to help non-profits raise money, then allowing them to monetize their video playbacks is in line with that goal...)

Command-line svn for Windows?

You can get SVN command-line tools with TortoiseSVN 1.7 or later or get a 6.5mb standalone package from VisualSVN.

Starting with TortoiseSVN 1.7, its installer provides you with an option to install the command-line tools.

It also makes sense to check the Apache Subversion "Binary Packages" page. xD

List file using ls command in Linux with full path

This prints all files, recursively, from the current directory.

find "$PWD" | awk /.ogg/ # filter .ogg files by regex
find "$PWD" | grep .ogg  # filter .ogg files by term
find "$PWD" | ack .ogg   # filter .ogg files by regex/term using https://github.com/petdance/ack2

Webclient / HttpWebRequest with Basic Authentication returns 404 not found for valid URL

This part of code worked fine for me:

        WebRequest request = WebRequest.Create(url);
        request.Method = WebRequestMethods.Http.Get;
        NetworkCredential networkCredential = new NetworkCredential(logon, password); // logon in format "domain\username"
        CredentialCache myCredentialCache = new CredentialCache {{new Uri(url), "Basic", networkCredential}};
        request.PreAuthenticate = true;
        request.Credentials = myCredentialCache;
        using (WebResponse response = request.GetResponse())
        {
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            using (Stream dataStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(dataStream))
                {
                    string responseFromServer = reader.ReadToEnd();
                    Console.WriteLine(responseFromServer);
                }
            }
        }

How can I create a keystore?

I was crazy looking how to generate a .keystore using in the shell a single line command, so I could run it from another application. This is the way:

echo y | keytool -genkeypair -dname "cn=Mark Jones, ou=JavaSoft, o=Sun, c=US" -alias business -keypass kpi135 -keystore /working/android.keystore -storepass ab987c -validity 20000
  • dname is a unique identifier for the application in the .keystore

    • cn the full name of the person or organization that generates the .keystore
    • ou Organizational Unit that creates the project, its a subdivision of the Organization that creates it. Ex. android.google.com
    • o Organization owner of the whole project. Its a higher scope than ou. Ex.: google.com
    • c The country short code. Ex: For United States is "US"
  • alias Identifier of the app as an single entity inside the .keystore (it can have many)

  • keypass Password for protecting that specific alias.
  • keystore Path where the .keystore file shall be created (the standard extension is actually .ks)
  • storepass Password for protecting the whole .keystore content.
  • validity Amout of days the app will be valid with this .keystore

It worked really well for me, it doesnt ask for anything else in the console, just creates the file. For more information see keytool - Key and Certificate Management Tool.

POST: sending a post request in a url itself

You can post data to a url with JavaScript & Jquery something like that:

$.post("www.abc.com/details", {
    json_string: JSON.stringify({name:"John", phone number:"+410000000"})
});

What is the iOS 6 user agent string?

iPhone:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

iPad:

Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10A5376e Safari/8536.25

For a complete list and more details about the iOS user agent check out these 2 resources:
Safari User Agent Strings (http://useragentstring.com/pages/Safari/)
Complete List of iOS User-Agent Strings (http://enterpriseios.com/wiki/UserAgent)

Null check in VB

Your code is way more cluttered than necessary.

Replace (Not (X Is Nothing)) with X IsNot Nothing and omit the outer parentheses:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For i As Integer = 0 To comp.Container.Components.Count() - 1
        fixUIIn(comp.Container.Components(i), style)
    Next
End If

Much more readable. … Also notice that I’ve removed the redundant Step 1 and the probably redundant .Item.

But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each instead:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For Each component In comp.Container.Components
        fixUIIn(component, style)
    Next
End If

Determining the last row in a single column

personally I had a similar issue and went with something like this:

function getLastRowinColumn (ws, column) {
  var page_lastrow = ws.getDataRange().getNumRows();
  var last_row_col = 0
  for (i=1; i<=page_lastrow;i++) {
    if (!(spread.getRange(column.concat("",i)).isBlank())) {last_row_col = i};
  }
  return last_row_col
}

It looks for the number of rows in the ws and loops through each cell in your column. When it finds a non-empty cell it updates the position of that cell in the last_row_col variable. It has the advantage of allowing you to have non-contiguous columns and still know the last row (assuming you are going through the whole column).

C# DateTime to "YYYYMMDDHHMMSS" format

It is not a big deal. you can simply put like this

WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd-HH:mm:ss")}");

Excuse here for I used $ which is for string Interpolation .

How to transform array to comma separated words string?

Make your array a variable and use implode.

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);

echo $comma_separated; // lastname,email,phone

http://php.net/manual/en/function.implode.php

How to change the value of attribute in appSettings section with Web.config transformation

Replacing all AppSettings

This is the overkill case where you just want to replace an entire section of the web.config. In this case I will replace all AppSettings in the web.config will new settings in web.release.config. This is my baseline web.config appSettings:

<appSettings>
  <add key="KeyA" value="ValA"/>
  <add key="KeyB" value="ValB"/>
</appSettings>

Now in my web.release.config file, I am going to create a appSettings section except I will include the attribute xdt:Transform=”Replace” since I want to just replace the entire element. I did not have to use xdt:Locator because there is nothing to locate – I just want to wipe the slate clean and replace everything.

<appSettings xdt:Transform="Replace">
  <add key="ProdKeyA" value="ProdValA"/>
  <add key="ProdKeyB" value="ProdValB"/>
  <add key="ProdKeyC" value="ProdValC"/>
</appSettings>

Note that in the web.release.config file my appSettings section has three keys instead of two, and the keys aren’t even the same. Now let’s look at the generated web.config file what happens when we publish:

<appSettings>
   <add key="ProdKeyA" value="ProdValA"/>
   <add key="ProdKeyB" value="ProdValB"/>
   <add key="ProdKeyC" value="ProdValC"/>
 </appSettings>

Just as we expected – the web.config appSettings were completely replaced by the values in web.release config. That was easy!

Best method for reading newline delimited files and discarding the newlines?

I'd do it like this:

f = open('test.txt')
l = [l for l in f.readlines() if l.strip()]
f.close()
print l

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

You don't need to downgrade you can:

Either disable undefined symbol diagnostics in the settings -- "intelephense.diagnostics.undefinedSymbols": false .

Or use an ide helper that adds stubs for laravel facades. See https://github.com/barryvdh/laravel-ide-helper

Javascript to export html table to Excel

For UTF 8 Conversion and Currency Symbol Export Use this:

var tableToExcel = (function() {
  var uri = 'data:application/vnd.ms-excel;base64,'
    , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><?xml version="1.0" encoding="UTF-8" standalone="yes"?><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
    , base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
    , format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
  return function(table, name) {
      if (!table.nodeType) table = document.getElementById(table)
      var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
    window.location.href = uri + base64(format(template, ctx))
  }
})()

Dilemma: when to use Fragments vs Activities:

You are free to use one of those.
Basically, you have to evaluate which is the best one to your app. Think about how you will manage the business flow and how to store/manage data preferences.

Think about, how Fragments store garbage data. When you implement the fragment, you have a activity root to fill with fragment(s). So, if your trying to implement a lot of activities with too much fragments, you have to consider performance on your app, coz you're manipulating (coarsely speaks) two context lifecycle, remember the complexity.

Remember: should I use fragments? Why shouldn't I?

regards.

Replace multiple strings at once

For the tags, you should be able to just set the content with .text() instead of .html().

Example: http://jsfiddle.net/Phf4u/1/

var textarea = $('textarea').val().replace(/<br\s?\/?>/, '\n');

$("#output").text(textarea);

...or if you just wanted to remove the <br> elements, you could get rid of the .replace(), and temporarily make them DOM elements.

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

var textarea = $('textarea').val();

textarea = $('<div>').html(textarea).find('br').remove().end().html();

$("#output").text(textarea);

Descending order by date filter in AngularJs

see w3schools samples: https://www.w3schools.com/angular/angular_filters.asp https://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_orderby_click

then add the "reverse" flag:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<p>Click the table headers to change the sorting order:</p>

<div ng-app="myApp" ng-controller="namesCtrl">

<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:reverse">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Carl',country:'Sweden'},
        {name:'Margareth',country:'England'},
        {name:'Hege',country:'Norway'},
        {name:'Joe',country:'Denmark'},
        {name:'Gustav',country:'Sweden'},
        {name:'Birgit',country:'Denmark'},
        {name:'Mary',country:'England'},
        {name:'Kai',country:'Norway'}
        ];

    $scope.reverse=false;
    $scope.orderByMe = function(x) {

        if($scope.myOrderBy == x) {
            $scope.reverse=!$scope.reverse;
        }
        $scope.myOrderBy = x;
    }
});
</script>

</body>
</html>

Subset of rows containing NA (missing) values in a chosen column of a data frame

NA is a special value in R, do not mix up the NA value with the "NA" string. Depending on the way the data was imported, your "NA" and "NULL" cells may be of various type (the default behavior is to convert "NA" strings to NA values, and let "NULL" strings as is).

If using read.table() or read.csv(), you should consider the "na.strings" argument to do clean data import, and always work with real R NA values.

An example, working in both cases "NULL" and "NA" cells :

DF <- read.csv("file.csv", na.strings=c("NA", "NULL"))
new_DF <- subset(DF, is.na(DF$Var2))

How can I escape square brackets in a LIKE clause?

According to documentation:

You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets.

You need to escape these three characters %_[:

'5%'      LIKE '5[%]'      -- true
'5$'      LIKE '5[%]'      -- false
'foo_bar' LIKE 'foo[_]bar' -- true
'foo$bar' LIKE 'foo[_]bar' -- false
'foo[bar' LIKE 'foo[[]bar' -- true
'foo]bar' LIKE 'foo]bar'   -- true

When to favor ng-if vs. ng-show/ng-hide?

From my experience:

1) If your page has a toggle that uses ng-if/ng-show to show/hide something, ng-if causes more of a browser delay (slower). For example: if you have a button used to toggle between two views, ng-show seems to be faster.

2) ng-if will create/destroy scope when it evaluates to true/false. If you have a controller attached to the ng-if, that controller code will get executed every time the ng-if evaluates to true. If you are using ng-show, the controller code only gets executed once. So if you have a button that toggles between multiple views, using ng-if and ng-show would make a huge difference in how you write your controller code.

ROW_NUMBER() in MySQL

From MySQL 8.0.0 and above you could natively use windowed functions.

1.4 What Is New in MySQL 8.0:

Window functions.

MySQL now supports window functions that, for each row from a query, perform a calculation using rows related to that row. These include functions such as RANK(), LAG(), and NTILE(). In addition, several existing aggregate functions now can be used as window functions; for example, SUM() and AVG().

ROW_NUMBER() over_clause :

Returns the number of the current row within its partition. Rows numbers range from 1 to the number of partition rows.

ORDER BY affects the order in which rows are numbered. Without ORDER BY, row numbering is indeterminate.

Demo:

CREATE TABLE Table1(
  id INT AUTO_INCREMENT PRIMARY KEY, col1 INT,col2 INT, col3 TEXT);

INSERT INTO Table1(col1, col2, col3)
VALUES (1,1,'a'),(1,1,'b'),(1,1,'c'),
       (2,1,'x'),(2,1,'y'),(2,2,'z');

SELECT 
    col1, col2,col3,
    ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col3 DESC) AS intRow
FROM Table1;

DBFiddle Demo

How to stop mysqld

On OSX 10.8 and on, the control for MySQL is available from the System Configs. Open System Preferences, click on Mysql (usually on the very bottom) and start/stop the service from that pane. https://dev.mysql.com/doc/refman/5.6/en/osx-installation-launchd.html

The plist file is now under /Library/LaunchDaemons/com.oracle.oss.mysql.mysqld.plist

Why does this AttributeError in python occur?

The default namespace in Python is "__main__". When you use import scipy, Python creates a separate namespace as your module name. The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});

laravel select where and where condition

Here is shortest way of doing it.

$userRecord = Model::where(['email'=>$email, 'password'=>$password])->first();

How to get the Android Emulator's IP address?

If you do truly want the IP assigned to your emulator:

adb shell
ifconfig eth0

Which will give you something like:

eth0: ip 10.0.2.15 mask 255.255.255.0 flags [up broadcast running multicast]

Select method of Range class failed via VBA

I believe you are having the same problem here.
The sheet must be active before you can select a range on it.

Also, don't omit the sheet name qualifier:

Sheets("BxWsn Simulation").Select
Sheets("BxWsn Simulation").Range("Result").Select

Or,

With Sheets("BxWsn Simulation")
  .Select
  .Range("Result").Select
End WIth

which is the same.

How do I change UIView Size?

Here you go. this should work.

questionFrame.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.7) 

answerFrame.frame =  CGRectMake(0 , self.view.frame.height * 0.7, self.view.frame.width, self.view.frame.height * 0.3)

How to initialize a vector of vectors on a struct?

Like this:

#include <vector>

// ...

std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));

(Pre-C++11 you need to leave whitespace between the angled brackets.)

moment.js - UTC gives wrong date

Both Date and moment will parse the input string in the local time zone of the browser by default. However Date is sometimes inconsistent with this regard. If the string is specifically YYYY-MM-DD, using hyphens, or if it is YYYY-MM-DD HH:mm:ss, it will interpret it as local time. Unlike Date, moment will always be consistent about how it parses.

The correct way to parse an input moment as UTC in the format you provided would be like this:

moment.utc('07-18-2013', 'MM-DD-YYYY')

Refer to this documentation.

If you want to then format it differently for output, you would do this:

moment.utc('07-18-2013', 'MM-DD-YYYY').format('YYYY-MM-DD')

You do not need to call toString explicitly.

Note that it is very important to provide the input format. Without it, a date like 01-04-2013 might get processed as either Jan 4th or Apr 1st, depending on the culture settings of the browser.

How to fix docker: Got permission denied issue

Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/images/json: dial unix /var/run/docker.sock: connect: permission denied

sudo chmod 666 /var/run/docker.sock

This fix my problem.

What does Java option -Xmx stand for?

see here: Java Tool Doc, it says,

-Xmxn
Specify the maximum size, in bytes, of the memory allocation pool. This value must a multiple of 1024 greater than 2MB. Append the letter k or K to indicate kilobytes, or m or M to indicate megabytes. The default value is 64MB. The upper limit for this value will be approximately 4000m on Solaris 7 and Solaris 8 SPARC platforms and 2000m on Solaris 2.6 and x86 platforms, minus overhead amounts. Examples:

           -Xmx83886080
           -Xmx81920k
           -Xmx80m

So, in simple words, you are setting Java heap memory to a maximum of 1024 MB from the available memory, not more.

Notice there is NO SPACE between -Xmx and 1024m

It does not matter if you use uppercase or lowercase. For example: "-Xmx10G" and "-Xmx10g" do the exact same thing.

HTML-5 date field shows as "mm/dd/yyyy" in Chrome, even when valid date is set

I have same problem and i found solution which is given below with full datepicker using simple HTML,Javascript and CSS. In this code i prepare formate like dd/mm/yyyy but you can work any.

HTML Code:

    <body>
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt"  onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
</body>

CSS Code:

#dt{text-indent: -500px;height:25px; width:200px;}

Javascript Code :

function mydate()
{
  //alert("");
document.getElementById("dt").hidden=false;
document.getElementById("ndt").hidden=true;
}
function mydate1()
{
 d=new Date(document.getElementById("dt").value);
dt=d.getDate();
mn=d.getMonth();
mn++;
yy=d.getFullYear();
document.getElementById("ndt").value=dt+"/"+mn+"/"+yy
document.getElementById("ndt").hidden=false;
document.getElementById("dt").hidden=true;
}

Output:

enter image description here

View array in Visual Studio debugger?

I use the ArrayDebugView add-in for Visual Studio (http://arraydebugview.sourceforge.net/).

It seems to be a long dead project (but one I'm looking at continuing myself) but the add-in still works beautifully for me in VS2010 for both C++ and C#.

It has a few quirks (tab order, modal dialog, no close button) but the ability to plot the contents of an array in a graph more than make up for it.

Edit July 2014: I have finally built a new Visual Studio extension to replace ArrayebugView's functionality. It is available on the VIsual Studio Gallery, search for ArrayPlotter or go to http://visualstudiogallery.msdn.microsoft.com/2fde2c3c-5b83-4d2a-a71e-5fdd83ce6b96?SRC=Home

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

You module and class AthleteList have the same name. Change:

import AthleteList

to:

from AthleteList import AthleteList

This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList

Various ways to remove local Git changes

Option 1: Discard tracked and untracked file changes

Discard changes made to both staged and unstaged files.

$ git reset --hard [HEAD]

Then discard (or remove) untracked files altogether.

$ git clean [-f]

Option 2: Stash

You can first stash your changes

$ git stash

And then either drop or pop it depending on what you want to do. See https://git-scm.com/docs/git-stash#_synopsis.

Option 3: Manually restore files to original state

First we switch to the target branch

$ git checkout <branch-name>

List all files that have changes

$ git status

Restore each file to its original state manually

$ git restore <file-path>

Is there any difference between "!=" and "<>" in Oracle Sql?

Actually, there are four forms of this operator:

<>
!=
^=

and even

¬= -- worked on some obscure platforms in the dark ages

which are the same, but treated differently when a verbatim match is required (stored outlines or cached queries).

Recommendations of Python REST (web services) framework?

We are working on a framework for strict REST services, check out http://prestans.googlecode.com

Its in early Alpha at the moment, we are testing against mod_wsgi and Google's AppEngine.

Looking for testers and feedback. Thanks.

Fragment transaction animation: slide in and slide out

I have same issue, i used simple solution

1)create sliding_out_right.xml in anim folder

  <?xml version="1.0" encoding="utf-8"?>
    <set xmlns:android="http://schemas.android.com/apk/res/android">
        <translate android:fromXDelta="0" android:toXDelta="-50%p"
            android:duration="@android:integer/config_mediumAnimTime"/>
        <alpha android:fromAlpha="1.0" android:toAlpha="0.0"
            android:duration="@android:integer/config_mediumAnimTime" />
    </set>

2) create sliding_in_left.xml in anim folder

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate android:fromXDelta="50%p" android:toXDelta="0"
        android:duration="@android:integer/config_mediumAnimTime"/>
    <alpha android:fromAlpha="0.0" android:toAlpha="1.0"
        android:duration="@android:integer/config_mediumAnimTime" />
</set>

3) simply using fragment transaction setCustomeAnimations() with two custom xml and two default xml for animation as follows :-

 fragmentTransaction.setCustomAnimations(R.anim.sliding_in_left, R.anim.sliding_out_right, android.R.anim.slide_in_left, android.R.anim.slide_out_right );

Create html documentation for C# code

Doxygen or Sandcastle help file builder are the primary tools that will extract XML documentation into HTML (and other forms) of external documentation.

Note that you can combine these documentation exporters with documentation generators - as you've discovered, Resharper has some rudimentary helpers, but there are also much more advanced tools to do this specific task, such as GhostDoc (for C#/VB code with XML documentation) or my addin Atomineer Pro Documentation (for C#, C++/CLI, C++, C, VB, Java, JavaScript, TypeScript, JScript, PHP, Unrealscript code containing XML, Doxygen, JavaDoc or Qt documentation).

Finding the path of the program that will execute from the command line in Windows

Here's a little cmd script you can copy-n-paste into a file named something like where.cmd:

@echo off
rem - search for the given file in the directories specified by the path, and display the first match
rem
rem    The main ideas for this script were taken from Raymond Chen's blog:
rem
rem         http://blogs.msdn.com/b/oldnewthing/archive/2005/01/20/357225.asp
rem
rem
rem - it'll be nice to at some point extend this so it won't stop on the first match. That'll
rem     help diagnose situations with a conflict of some sort.
rem

setlocal

rem - search the current directory as well as those in the path
set PATHLIST=.;%PATH%
set EXTLIST=%PATHEXT%

if not "%EXTLIST%" == "" goto :extlist_ok
set EXTLIST=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
:extlist_ok

rem - first look for the file as given (not adding extensions)
for %%i in (%1) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i

rem - now look for the file adding extensions from the EXTLIST
for %%e in (%EXTLIST%) do @for %%i in (%1%%e) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i

Creating Unicode character from its number

The code below will write the 4 unicode chars (represented by decimals) for the word "be" in Japanese. Yes, the verb "be" in Japanese has 4 chars! The value of characters is in decimal and it has been read into an array of String[] -- using split for instance. If you have Octal or Hex, parseInt take a radix as well.

// pseudo code
// 1. init the String[] containing the 4 unicodes in decima :: intsInStrs 
// 2. allocate the proper number of character pairs :: c2s
// 3. Using Integer.parseInt (... with radix or not) get the right int value
// 4. place it in the correct location of in the array of character pairs
// 5. convert c2s[] to String
// 6. print 

String[] intsInStrs = {"12354", "12426", "12414", "12377"}; // 1.
char [] c2s = new char [intsInStrs.length * 2];  // 2.  two chars per unicode

int ii = 0;
for (String intString : intsInStrs) {
    // 3. NB ii*2 because the 16 bit value of Unicode is written in 2 chars
    Character.toChars(Integer.parseInt(intsInStrs[ii]), c2s, ii * 2 ); // 3 + 4
    ++ii; // advance to the next char
}

String symbols = new String(c2s);  // 5.
System.out.println("\nLooooonger code point: " + symbols); // 6.
// I tested it in Eclipse and Java 7 and it works.  Enjoy

How to make a new line or tab in <string> XML (eclipse/android)?

\n didn't work for me. So I used <br></br> HTML tag

    <string name="message_register_success">
Sign up is complete. <br></br>
 Enjoy a new shopping life at MageMobile!!
</string>

AutoComplete TextBox in WPF

or you can add the AutoCompleteBox into the toolbox by clicking on it and then Choose Items, go to WPF Components, type in the filter AutoCompleteBox, which is on the System.Windows.Controls namespace and the just drag into your xaml file. This is way much easier than doing these other stuff, since the AutoCompleteBox is a native control.

select2 changing items dynamically

In my project I use following code:

$('#attribute').select2();
$('#attribute').bind('change', function(){
    var $options = $();
    for (var i in data) {
        $options = $options.add(
            $('<option>').attr('value', data[i].id).html(data[i].text)
        );
    }
    $('#value').html($options).trigger('change');
});

Try to comment out the select2 part. The rest of the code will still work.

Run a Command Prompt command from Desktop Shortcut

Create A Shortcut That Opens The Command Prompt & Runs A Command:

Yes! You can create a shortcut to cmd.exe with a command specified after it. Alternatively you could create a batch script, if your goal is just to have a clickable way to run commands.

Steps:

  1. Right click on some empty space in Explorer, and in the context menu go to "New/Shortcut".

  2. When prompted to enter a location put either:

"C:\Windows\System32\cmd.exe /k your-command" This will run the command and keep (/k) the command prompt open after.

or

"C:\Windows\System32\cmd.exe /c your-command" This will run the command and the close (/c) the command prompt.

Notes:

  • Tested, and working on Windows 8 - Core X86-64 September 12 2014

  • If you want to have more than one command, place an "&" symbol in between them. For example: "C:\Windows\System32\cmd.exe /k command1 & command2".

How to play CSS3 transitions in a loop?

CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.

You need to define the animation keyframes and apply it to the element:

@keyframes changewidth {
  from {
    width: 100px;
  }

  to {
    width: 300px;
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.

What is the difference between __str__ and __repr__?

>>> print(decimal.Decimal(23) / decimal.Decimal("1.05"))
21.90476190476190476190476190
>>> decimal.Decimal(23) / decimal.Decimal("1.05")
Decimal('21.90476190476190476190476190')

When print() is called on the result of decimal.Decimal(23) / decimal.Decimal("1.05") the raw number is printed; this output is in string form which can be achieved with __str__(). If we simply enter the expression we get a decimal.Decimal output — this output is in representational form which can be achieved with __repr__(). All Python objects have two output forms. String form is designed to be human-readable. The representational form is designed to produce output that if fed to a Python interpreter would (when possible) reproduce the represented object.

extract date only from given timestamp in oracle sql

If you want the value from your timestamp column to come back as a date datatype, use something like this:

select trunc(my_timestamp_column,'dd') as my_date_column from my_table;

Apache won't start in wamp

My solution on Windows 10 was just to stop IIS (Internet Information Services).

How to check if a file contains a specific string using Bash

Shortest (correct) version:

grep -q "something" file; [ $? -eq 0 ] && echo "yes" || echo "no"

can be also written as

grep -q "something" file; test $? -eq 0 && echo "yes" || echo "no"

but you dont need to explicitly test it in this case, so the same with:

grep -q "something" file && echo "yes" || echo "no"

R cannot be resolved - Android error

Another way this can occur is if you start a new project from one of the samples. When you later decide to change the package name from com.example.android.foo to your own domain, you will need to modify several values in the manifest and in individual .java files.

If you're in Eclipse, find the package statement for the .java file and choose QuickFix. There may be several choices there, but the one you want is the one that indicates to "Move 'foo.java' to package 'com.youdomain.android.yourapp'. Save the file and it may autobuild or do as others have suggested and try "Project->Clean".

What is the best comment in source code you have ever encountered?

Sometime in the early 1980's we were writing financial modeling code for utilities in PL/I. Got a call from a client with code blowing up right after a comment

/* Honest this works */

The guy had taken our standard set of financial equations and done about 15 pages of algebra to combine a bunch of code into one equation. After Three Mile Island when utilities had to write off their nuclear plants at huge costs the equation failed because of a FIXED BIN 15 (integer) overflow that would not have happened if the algebra hadn't happened.

How can I get input radio elements to horizontally align?

Here is updated Fiddle

Simply remove </br> between input radio's

<div class="clearBoth"></div>
<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change
<div class="clearBoth"></div>

How to change TextField's height and width?

You can simply wrap Text field widget in padding widget..... Like this,

Padding(
         padding: EdgeInsets.only(left: 5.0, right: 5.0),
          child: TextField(
            cursorColor: Colors.blue,

            decoration: InputDecoration(
                labelText: 'Email',
                hintText: '[email protected]',
                //labelStyle: textStyle,
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(5),
                  borderSide: BorderSide(width: 2, color: Colors.blue,)),
              focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                  borderSide: BorderSide(width: 2, color: Colors.green)),
                )

            ),
          ),

Groovy String to Date

The first argument to parse() is the expected format. You have to change that to Date.parse("E MMM dd H:m:s z yyyy", testDate) for it to work. (Note you don't need to create a new Date object, it's a static method)

If you don't know in advance what format, you'll have to find a special parsing library for that. In Ruby there's a library called Chronic, but I'm not aware of a Groovy equivalent. Edit: There is a Java port of the library called jChronic, you might want to check it out.

How can I reverse a list in Python?

>>> L = [0,10,20,40]
>>> L.reverse()
>>> L
[40, 20, 10, 0]

Or

>>> L[::-1]
[40, 20, 10, 0]

Get protocol + host name from URL

The standard library function urllib.parse.urlsplit() is all you need. Here is an example for Python3:

>>> import urllib.parse
>>> o = urllib.parse.urlsplit('https://user:[email protected]:8080/dir/page.html?q1=test&q2=a2#anchor1')
>>> o.scheme
'https'
>>> o.netloc
'user:[email protected]:8080'
>>> o.hostname
'www.example.com'
>>> o.port
8080
>>> o.path
'/dir/page.html'
>>> o.query
'q1=test&q2=a2'
>>> o.fragment
'anchor1'
>>> o.username
'user'
>>> o.password
'pass'

SQLite with encryption/password protection

You can password protect SQLite3 DB. For the first time before doing any operations, set password as follows.

SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.open();

then next time you can access it like

conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();

This wont allow any GUI editor to view Your data. Later if you wish to change the password, use conn.ChangePassword("new_password"); To reset or remove password, use conn.ChangePassword(String.Empty);

Installing Pandas on Mac OSX

pip install pandas works fine with pip 18.0 on macOS 10.13.6. In addition, to work with Xlsx files, you will need xlrd installed.

'negative' pattern matching in python

 if not (line.startswith("OK ") or line.strip() == "."):
     print line

Creating columns in listView and add items

You need to set property for the control:

listView1.View = View.Details;

Datatable select method ORDER BY clause

Use

datatable.select("col1='test'","col1 ASC")

Then before binding your data to the grid or repeater etc, use this

datatable.defaultview.sort()

That will solve your problem.

jquery.ajax Access-Control-Allow-Origin

http://encosia.com/using-cors-to-access-asp-net-services-across-domains/

refer the above link for more details on Cross domain resource sharing.

you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.

sample below:

ajax call:

$(document).ready(function () {
        $.ajax({
            crossDomain: true,
            type:"GET",
            contentType: "application/json; charset=utf-8",
            async:false,
            url: "<your middle man service url here>/GetQuote?callback=?",
            data: { symbol: 'ctsh' },
            dataType: "jsonp",                
            jsonpCallback: 'fnsuccesscallback'
        });
    });

service (asmx) which will return jsonp:

[WebMethod]
    [ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
    public void GetQuote(String symbol,string callback)
    {          

        WebProxy myProxy = new WebProxy("<proxy url here>", true);

        myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
        StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
        SQ.Proxy = myProxy;
        String result = SQ.GetQuote(symbol);
        StringBuilder sb = new StringBuilder();
        JavaScriptSerializer js = new JavaScriptSerializer();
        sb.Append(callback + "(");
        sb.Append(js.Serialize(result));
        sb.Append(");");
        Context.Response.Clear();
        Context.Response.ContentType = "application/json";
        Context.Response.Write(sb.ToString());
        Context.Response.End();         
    }

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

check to make the field you are referencing to is an exact match with foreign key, in my case one was unsigned and the other was signed so i just changed them to match and this worked

ALTER TABLE customer_information ADD CONSTRAINT fk_customer_information1 FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE

How do I prevent Conda from activating the base environment by default?

So in the end I found that if I commented out the Conda initialisation block like so:

# >>> conda initialize >>>
# !! Contents within this block are managed by 'conda init' !!
# __conda_setup="$('/Users/geoff/anaconda2/bin/conda' 'shell.bash' 'hook' 2> /dev/null)"
# if [ $? -eq 0 ]; then
    # eval "$__conda_setup"
# else
if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
    . "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
else
    export PATH="/Users/geoff/anaconda2/bin:$PATH"
fi
# fi
# unset __conda_setup
# <<< conda initialize <<<

It works exactly how I want. That is, Conda is available to activate an environment if I want, but doesn't activate by default.

Rename a dictionary key

For a regular dict, you can use:

mydict[k_new] = mydict.pop(k_old)

This will move the item to the end of the dict, unless k_new was already existing in which case it will overwrite the value in-place.

For a Python 3.7+ dict where you additionally want to preserve the ordering, the simplest is to rebuild an entirely new instance. For example, renaming key 2 to 'two':

>>> d = {0:0, 1:1, 2:2, 3:3}
>>> {"two" if k == 2 else k:v for k,v in d.items()}
{0: 0, 1: 1, 'two': 2, 3: 3}

The same is true for an OrderedDict, where you can't use dict comprehension syntax, but you can use a generator expression:

OrderedDict((k_new if k == k_old else k, v) for k, v in od.items())

Modifying the key itself, as the question asks for, is impractical because keys are hashable which usually implies they're immutable and can't be modified.

How do I output coloured text to a Linux terminal?

Before you going to output any color you need make sure you are in a terminal:

[ -t 1 ] && echo 'Yes I am in a terminal'  # isatty(3) call in C

Then you need to check terminal capability if it support color

on systems with terminfo (Linux based) you can obtain quantity of supported colors as

Number_Of_colors_Supported=$(tput colors)

on systems with termcap (BSD based) you can obtain quantity of supported colors as

Number_Of_colors_Supported=$(tput Co)

Then make you decision:

[ ${Number_Of_colors_Supported} -ge 8 ] && {
    echo 'You are fine and can print colors'
} || {
    echo 'Terminal does not support color'
}

BTW, do not use coloring as it was suggested before with ESC characters. Use standard call to terminal capability that will assign you CORRECT colors that particular terminal support.

BSD Based
fg_black="$(tput AF 0)"
fg_red="$(tput AF 1)"
fg_green="$(tput AF 2)"
fg_yellow="$(tput AF 3)"
fg_blue="$(tput AF 4)"
fg_magenta="$(tput AF 5)"
fg_cyan="$(tput AF 6)"
fg_white="$(tput AF 7)"
reset="$(tput me)"
Linux Based
fg_black="$(tput setaf 0)"
fg_red="$(tput setaf 1)"
fg_green="$(tput setaf 2)"
fg_yellow="$(tput setaf 3)"
fg_blue="$(tput setaf 4)"
fg_magenta="$(tput setaf 5)"
fg_cyan="$(tput setaf 6)"
fg_white="$(tput setaf 7)"
reset="$(tput sgr0)"
Use As
echo -e "${fg_red}  Red  ${fg_green} Bull ${reset}"

XPath: How to select elements based on their value?

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]

Up, Down, Left and Right arrow keys do not trigger KeyDown event

In order to capture keystrokes in a Forms control, you must derive a new class that is based on the class of the control that you want, and you override the ProcessCmdKey().

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    //handle your keys here
}

Example :

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    //capture up arrow key
    if (keyData == Keys.Up )
    {
        MessageBox.Show("You pressed Up arrow key");
        return true;
    }

    return base.ProcessCmdKey(ref msg, keyData);
}

Full source...Arrow keys in C#

Vayne

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

First off, your code is a bit off. aes() is an argument in ggplot(), you don't use ggplot(...) + aes(...) + layers

Second, from the help file ?geom_bar:

By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.

You want the second case, where the height of the bar is equal to the conversion_rate So what you want is...

data_country <- data.frame(country = c("China", "Germany", "UK", "US"), 
            conversion_rate = c(0.001331558,0.062428188, 0.052612025, 0.037800687))
ggplot(data_country, aes(x=country,y = conversion_rate)) +geom_bar(stat = "identity")

Result:

enter image description here

Required attribute on multiple checkboxes with the same name?

i had the same problem, my solution was apply the required attribute to all elements

<input type="checkbox" name="checkin_days[]" required="required" value="0" /><span class="w">S</span>
<input type="checkbox" name="checkin_days[]" required="required" value="1" /><span class="w">M</span>
<input type="checkbox" name="checkin_days[]" required="required" value="2" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="3" /><span class="w">W</span>
<input type="checkbox" name="checkin_days[]" required="required" value="4" /><span class="w">T</span>
<input type="checkbox" name="checkin_days[]" required="required" value="5" /><span class="w">F</span>
<input type="checkbox" name="checkin_days[]" required="required" value="6" /><span class="w">S</span>

when the user check one of the elements i remove the required attribute from all elements:

var $checkedCheckboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]:checked'),
    $checkboxes = $('#recurrent_checkin :checkbox[name="checkin_days[]"]');

$checkboxes.click(function() {

if($checkedCheckboxes.length) {
        $checkboxes.removeAttr('required');
    } else {
        $checkboxes.attr('required', 'required');
    }

 });

Inserting a tab character into text using C#

Hazar is right with his \t. Here's the full list of escape characters for C#:

\' for a single quote.

\" for a double quote.

\\ for a backslash.

\0 for a null character.

\a for an alert character.

\b for a backspace.

\f for a form feed.

\n for a new line.

\r for a carriage return.

\t for a horizontal tab.

\v for a vertical tab.

\uxxxx for a unicode character hex value (e.g. \u0020).

\x is the same as \u, but you don't need leading zeroes (e.g. \x20).

\Uxxxxxxxx for a unicode character hex value (longer form needed for generating surrogates).

How to find a hash key containing a matching value

Ruby 1.9 and greater:

hash.key(value) => key

Ruby 1.8:

You could use hash.index

hsh.index(value) => key

Returns the key for a given value. If not found, returns nil.

h = { "a" => 100, "b" => 200 }
h.index(200) #=> "b"
h.index(999) #=> nil

So to get "orange", you could just use:

clients.key({"client_id" => "2180"})

How to count the number of set bits in a 32-bit integer?

The Hacker's Delight bit-twiddling becomes so much clearer when you write out the bit patterns.

unsigned int bitCount(unsigned int x)
{
  x = ((x >> 1) & 0b01010101010101010101010101010101)
     + (x       & 0b01010101010101010101010101010101);
  x = ((x >> 2) & 0b00110011001100110011001100110011)
     + (x       & 0b00110011001100110011001100110011); 
  x = ((x >> 4) & 0b00001111000011110000111100001111)
     + (x       & 0b00001111000011110000111100001111); 
  x = ((x >> 8) & 0b00000000111111110000000011111111)
     + (x       & 0b00000000111111110000000011111111); 
  x = ((x >> 16)& 0b00000000000000001111111111111111)
     + (x       & 0b00000000000000001111111111111111); 
  return x;
}

The first step adds the even bits to the odd bits, producing a sum of bits in each two. The other steps add high-order chunks to low-order chunks, doubling the chunk size all the way up, until we have the final count taking up the entire int.

LINQ extension methods - Any() vs. Where() vs. Exists()

Any() returns true if any of the elements in a collection meet your predicate's criteria.

Where() returns an enumerable of all elements in a collection that meet your predicate's criteria.

Exists() does the same thing as any except it's just an older implementation that was there on the IList back before Linq.

Adding an img element to a div with javascript

document.getElementById("placehere").appendChild(elem);

not

document.getElementById("placehere").appendChild("elem");

and use the below to set the source

elem.src = 'images/hydrangeas.jpg';

How do I remove the title bar from my app?

This works for me

getSupportActionBar().hide();

Convert generic list to dataset in C#

Have you tried binding the list to the datagridview directly? If not, try that first because it will save you lots of pain. If you have tried it already, please tell us what went wrong so we can better advise you. Data binding gives you different behaviour depending on what interfaces your data object implements. For example, if your data object only implements IEnumerable (e.g. List), you will get very basic one-way binding, but if it implements IBindingList as well (e.g. BindingList, DataView), then you get two-way binding.

Multi-line bash commands in makefile

You can use backslash for line continuation. However note that the shell receives the whole command concatenated into a single line, so you also need to terminate some of the lines with a semicolon:

foo:
    for i in `find`;     \
    do                   \
        all="$$all $$i"; \
    done;                \
    gcc $$all

But if you just want to take the whole list returned by the find invocation and pass it to gcc, you actually don't necessarily need a multiline command:

foo:
    gcc `find`

Or, using a more shell-conventional $(command) approach (notice the $ escaping though):

foo:
    gcc $$(find)

How do I search within an array of hashes by hash values in ruby?

if your array looks like

array = [
 {:name => "Hitesh" , :age => 27 , :place => "xyz"} ,
 {:name => "John" , :age => 26 , :place => "xtz"} ,
 {:name => "Anil" , :age => 26 , :place => "xsz"} 
]

And you Want To know if some value is already present in your array. Use Find Method

array.find {|x| x[:name] == "Hitesh"}

This will return object if Hitesh is present in name otherwise return nil

How to get the excel file name / path in VBA

this is a simple alternative that gives all responses, Fullname, Path, filename.

Dim FilePath, FileOnly, PathOnly As String

FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))

How to use mysql JOIN without ON condition?

There are several ways to do a cross join or cartesian product:

SELECT column_names FROM table1 CROSS JOIN table2;

SELECT column_names FROM table1, table2;

SELECT column_names FROM table1 JOIN table2;

Neglecting the on condition in the third case is what results in a cross join.

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I found the same error, and it took two days to identify what the error was.

The error was simply because I was trying to use: android:background

Rather than: app:srcCompat

in an SVG file.

In your case, I believe this is it

<ImageView 
    android:scaleType="fitXY" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:src="@drawable/tour_11"      <-- the error is here !
 />

I recommend using it this way

add this to your build.gradle app

android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
    }  
 }

and

<androidx.appcompat.widget.AppCompatImageView  <-- use **AppCompatImageView** not **ImageView**
        android:scaleType="fitXY" 
        android:layout_width="match_parent" 
        android:layout_height="match_parent" 
        app:srcCompat="@drawable/tour_11"
     />

I hope this helps.

Get height of div with no height set in css

jQuery .height will return you the height of the element. It doesn't need CSS definition as it determines the computed height.

DEMO

You can use .height(), .innerHeight() or outerHeight() based on what you need.

enter image description here

.height() - returns the height of element excludes padding, border and margin.

.innerHeight() - returns the height of element includes padding but excludes border and margin.

.outerHeight() - returns the height of the div including border but excludes margin.

.outerHeight(true) - returns the height of the div including margin.

Check below code snippet for live demo. :)

_x000D_
_x000D_
$(function() {_x000D_
  var $heightTest = $('#heightTest');_x000D_
  $heightTest.html('Div style set as "height: 180px; padding: 10px; margin: 10px; border: 2px solid blue;"')_x000D_
    .append('<p>Height (.height() returns) : ' + $heightTest.height() + ' [Just Height]</p>')_x000D_
    .append('<p>Inner Height (.innerHeight() returns): ' + $heightTest.innerHeight() + ' [Height + Padding (without border)]</p>')_x000D_
    .append('<p>Outer Height (.outerHeight() returns): ' + $heightTest.outerHeight() + ' [Height + Padding + Border]</p>')_x000D_
    .append('<p>Outer Height (.outerHeight(true) returns): ' + $heightTest.outerHeight(true) + ' [Height + Padding + Border + Margin]</p>')_x000D_
});
_x000D_
div { font-size: 0.9em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="heightTest" style="height: 150px; padding: 10px; margin: 10px; border: 2px solid blue; overflow: hidden; ">_x000D_
</div>
_x000D_
_x000D_
_x000D_

AngularJS: How to run additional code after AngularJS has rendered a template?

First, the right place to mess with rendering are directives. My advice would be to wrap DOM manipulating jQuery plugins by directives like this one.

I had the same problem and came up with this snippet. It uses $watch and $evalAsync to ensure your code runs after directives like ng-repeat have been resolved and templates like {{ value }} got rendered.

app.directive('name', function() {
    return {
        link: function($scope, element, attrs) {
            // Trigger when number of children changes,
            // including by directives like ng-repeat
            var watch = $scope.$watch(function() {
                return element.children().length;
            }, function() {
                // Wait for templates to render
                $scope.$evalAsync(function() {
                    // Finally, directives are evaluated
                    // and templates are renderer here
                    var children = element.children();
                    console.log(children);
                });
            });
        },
    };
});

Hope this can help you prevent some struggle.

Passing a method as a parameter in Ruby

The normal Ruby way to do this is to use a block.

So it would be something like:

def weightedknn( data, vec1, k = 5 )
  foo
  weight = yield( dist )
  foo
end

And used like:

weightenknn( data, vec1 ) { |dist| gaussian( dist ) }

This pattern is used extensively in Ruby.

jQuery convert line breaks to br (nl2br equivalent)

Put this in your code (preferably in a general js functions library):

String.prototype.nl2br = function()
{
    return this.replace(/\n/g, "<br />");
}

Usage:

var myString = "test\ntest2";

myString.nl2br();

creating a string prototype function allows you to use this on any string.

C# - Winforms - Global Variables

Or you could put your globals in the app.config

what is the difference between uint16_t and unsigned short int incase of 64 bit processor?

uint16_t is unsigned 16-bit integer.

unsigned short int is unsigned short integer, but the size is implementation dependent. The standard only says it's at least 16-bit (i.e, minimum value of UINT_MAX is 65535). In practice, it usually is 16-bit, but you can't take that as guaranteed.

Note:

  1. If you want a portable unsigned 16-bit integer, use uint16_t.
  2. inttypes.h and stdint.h are both introduced in C99. If you are using C89, define your own type.
  3. uint16_t may not be provided in certain implementation(See reference below), but unsigned short int is always available.

Reference: C11(ISO/IEC 9899:201x) §7.20 Integer types

For each type described herein that the implementation provides) shall declare that typedef name and define the associated macros. Conversely, for each type described herein that the implementation does not provide, shall not declare that typedef name nor shall it define the associated macros. An implementation shall provide those types described as ‘‘required’’, but need not provide any of the others (described as ‘optional’’).

Could not resolve Spring property placeholder

I still believe its to do with the props file not being located by spring. Do a quick test by passing the params as jvm params. i.e -Didm.url=....

What is the "-->" operator in C/C++?

One book I read (I don't remember correctly which book) stated: Compilers try to parse expressions to the biggest token by using the left right rule.

In this case, the expression:

x-->0

Parses to biggest tokens:

token 1: x
token 2: --
token 3: >
token 4: 0
conclude: x-- > 0

The same rule applies to this expression:

a-----b

After parse:

token 1: a
token 2: --
token 3: --
token 4: -
token 5: b
conclude: (a--)-- - b

I hope this helps to understand the complicated expression ^^

What do 3 dots next to a parameter type mean in Java?

String... is the same as String[]

import java.lang.*;

public class MyClassTest {

    //public static void main(String... args) { 

    public static void main(String[] args) {
        for(String str: args) {
            System.out.println(str);
        }
    }
}

How to read all rows from huge table?

So it turns out that the crux of the problem is that by default, Postgres starts in "autoCommit" mode, and also it needs/uses cursors to be able to "page" through data (ex: read the first 10K results, then the next, then the next), however cursors can only exist within a transaction. So the default is to read all rows, always, into RAM, and then allow your program to start processing "the first result row, then the second" after it has all arrived, for two reasons, it's not in a transaction (so cursors don't work), and also a fetch size hasn't been set.

So how the psql command line tool achieves batched response (its FETCH_COUNT setting) for queries, is to "wrap" its select queries within a short-term transaction (if a transaction isn't yet open), so that cursors can work. You can do something like that also with JDBC:

  static void readLargeQueryInChunksJdbcWay(Connection conn, String originalQuery, int fetchCount, ConsumerWithException<ResultSet, SQLException> consumer) throws SQLException {
    boolean originalAutoCommit = conn.getAutoCommit();
    if (originalAutoCommit) {
      conn.setAutoCommit(false); // start temp transaction
    }
    try (Statement statement = conn.createStatement()) {
      statement.setFetchSize(fetchCount);
      ResultSet rs = statement.executeQuery(originalQuery);
      while (rs.next()) {
        consumer.accept(rs); // or just do you work here
      }
    } finally {
      if (originalAutoCommit) {
        conn.setAutoCommit(true); // reset it, also ends (commits) temp transaction
      }
    }
  }
  @FunctionalInterface
  public interface ConsumerWithException<T, E extends Exception> {
    void accept(T t) throws E;
  }

This gives the benefit of requiring less RAM, and, in my results, seemed to run overall faster, even if you don't need to save the RAM. Weird. It also gives the benefit that your processing of the first row "starts faster" (since it process it a page at a time).

And here's how to do it the "raw postgres cursor" way, along with full demo code, though in my experiments it seemed the JDBC way, above, was slightly faster for whatever reason.

Another option would be to have autoCommit mode off, everywhere, though you still have to always manually specify a fetchSize for each new Statement (or you can set a default fetch size in the URL string).

Difference between res.send and res.json in Express.js

res.json forces the argument to JSON. res.send will take an non-json object or non-json array and send another type. For example:

This will return a JSON number.

res.json(100)

This will return a status code and issue a warning to use sendStatus.

res.send(100)

If your argument is not a JSON object or array (null,undefined,boolean,string), and you want to ensure it is sent as JSON, use res.json.

How do I install Python OpenCV through Conda?

I think the easiest option that should work cross-platform and across various versions of Anaconda is

#Run Anaconda Prompt as an Administrator (on Windows) & execute the command below
#(you may need to use   sudo   on a Unix-Based or Mac system 
#to have the needed permissions)

conda install -c conda-forge opencv

how to check if a datareader is null or empty

I also use OleDbDataReader.IsDBNull()

if ( myReader.IsDBNull(colNum) ) { retrievedValue = ""; }
else { retrievedValue = myReader.GetString(colNum); }

Eclipse CDT: no rule to make target all

Project -> Clean -> Clean all Projects and then Project -> Build Project worked for me (I did the un-checking generate make-file automatically and then rechecking it before doing this). This was for an AVR (micro-processor programming) project through the AVR CDT plugin in eclipse Juno though.

HAX kernel module is not installed

Actual error

enter image description here

follow bellow two simple steps to fix.

Step 1:- update "Intel x86 Emulator Accelerator (HAXM installer)" Ref. bellow img enter image description here

Step2:-

After installing the installer, you have to run it to install it on your system. Open the directory where your Android SDK is located. Go inside the extras\Intel\Hardware_Accelerated_Execution_Manager directory and you should see the intelhaxm-android.exe file.

enter image description here

If you got the error "This computer meets requirements for HAXM, but VT-x is not turned on..." during installation try to turn it on in your BIOS and check your antivirus software settings also. (Check this stackoverflow post). Thats it! its working for me.

Rotate an image in image source in html

This CSS seems to work in Safari and Chrome:

div#div2
{
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}

and in the body:

<div id="div2"><img src="image.jpg"  ></div>

But this (and the .rotate90 example above) pushes the rotated image higher up on the page than if it were un-rotated. Not sure how to control placement of the image relative to text or other rotated images.

How can I conditionally import an ES6 module?

You can't import conditionally, but you can do the opposite: export something conditionally. It depends on your use case, so this work around might not be for you.

You can do:

api.js

import mockAPI from './mockAPI'
import realAPI from './realAPI'

const exportedAPI = shouldUseMock ? mockAPI : realAPI
export default exportedAPI

apiConsumer.js

import API from './api'
...

I use that to mock analytics libs like mixpanel, etc... because I can't have multiple builds or our frontend currently. Not the most elegant, but works. I just have a few 'if' here and there depending on the environment because in the case of mixpanel, it needs initialization.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

This is a briefer variation of the accepted answer: the function below extracts the bits from-to inclusive by creating a bitmask. After applying an AND logic over the original number the result is shifted so the function returns just the extracted bits. Skipped index/integrity checks for clarity.

uint16_t extractInt(uint16_t orig16BitWord, unsigned from, unsigned to) 
{
  unsigned mask = ( (1<<(to-from+1))-1) << from;
  return (orig16BitWord & mask) >> from;
}

HTTP Error 403.14 - Forbidden The Web server is configured to not list the contents

I came across this error because I had the wrong .NET version (v2.0 instead of v4.0) configured on the web site application pool. I fixed it this way on Windows Server 2008 R2 and IIS 7. I'm pretty sure the instructions apply to Windows Server 2012 and IIS 8 as well:

  • Press keys Windows+R to open the Run dialog, type inetmgr and then click OK. This opens the IIS Manager.
  • In the left treeview, locate the Sites node and find the Default Web Site node under it (or the name of the site where the error message appears).
  • Right-click the node and select Manage web site -> Advanced settings.... Note the name of the value Application pool. Close this dialog.
  • In the treeview to the left, locate and select the node Application pools.
  • In the list to the right, locate the Application pool with the same name as the one you noted in the web site settings. Right-click it and select Advanced settings...
  • Make sure that the .NET Framework version value is v4.0. Click OK.

This doesn't apply if you're running an older site that actually should have .NET v2.0, of course :)

Flash CS4 refuses to let go

Also, to use your new namespaced class you can also do

var jenine:com.newnamespace.subspace.Jenine = com.newnamespace.subspace.Jenine()

Access properties file programmatically with Spring?

Create a class like below

    package com.tmghealth.common.util;

    import java.util.Properties;

    import org.springframework.beans.BeansException;

    import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

    import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

    import org.springframework.context.annotation.Configuration;

    import org.springframework.context.annotation.PropertySource;

    import org.springframework.stereotype.Component;


    @Component
    @Configuration
    @PropertySource(value = { "classpath:/spring/server-urls.properties" })
    public class PropertiesReader extends PropertyPlaceholderConfigurer {

        @Override
        protected void processProperties(
                ConfigurableListableBeanFactory beanFactory, Properties props)
                throws BeansException {
            super.processProperties(beanFactory, props);

        }

    }

Then wherever you want to access a property use

    @Autowired
        private Environment environment;
    and getters and setters then access using 

    environment.getProperty(envName
                    + ".letter.fdi.letterdetails.restServiceUrl");

-- write getters and setters in the accessor class

    public Environment getEnvironment() {
            return environment;
        }`enter code here`

        public void setEnvironment(Environment environment) {
            this.environment = environment;
        }

Parse HTML table to Python list?

Hands down the easiest way to parse a HTML table is to use pandas.read_html() - it accepts both URLs and HTML.

import pandas as pd
url = r'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
tables = pd.read_html(url) # Returns list of all tables on page
sp500_table = tables[0] # Select table of interest

Only downside is that read_html() doesn't preserve hyperlinks.

How to make spring inject value into a static field

As these answers are old, I found this alternative. It is very clean and works with just java annotations:

To fix it, create a “none static setter” to assign the injected value for the static variable. For example :

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class GlobalValue {

public static String DATABASE;

@Value("${mongodb.db}")
public void setDatabase(String db) {
    DATABASE = db;
}
}

https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

How to increase Java heap space for a tomcat app

  • Open the server tab in eclipse
  • right click open
  • click on open lauch configuration
  • Go to arguments
  • Here you can add in VM arguments after endorsed

    -Xms64m -Xmx256m
    

Images can't contain alpha channels or transparencies

Exporting from Sketch

To avoid transparency, ensure no layer extends beyond the artboard bounds.

GCC dump preprocessor defines

A portable approach that works equally well on Linux or Windows (where there is no /dev/null):

echo | gcc -dM -E -

For c++ you may use (replace c++11 with whatever version you use):

echo | gcc -x c++ -std=c++11 -dM -E -

It works by telling gcc to preprocess stdin (which is produced by echo) and print all preprocessor defines (search for -dletters). If you want to know what defines are added when you include a header file you can use -dD option which is similar to -dM but does not include predefined macros:

echo "#include <stdlib.h>" | gcc -x c++ -std=c++11 -dD -E -

Note, however, that empty input still produces lots of defines with -dD option.

How to do a join in linq to sql with method syntax?

var result = from sc in enumerableOfSomeClass
             join soc in enumerableOfSomeOtherClass
             on sc.Property1 equals soc.Property2
             select new { SomeClass = sc, SomeOtherClass = soc };

Would be equivalent to:

var result = enumerableOfSomeClass
    .Join(enumerableOfSomeOtherClass,
          sc => sc.Property1,
          soc => soc.Property2,
          (sc, soc) => new
                       {
                           SomeClass = sc,
                           SomeOtherClass = soc
                       });

As you can see, when it comes to joins, query syntax is usually much more readable than lambda syntax.

Remove Elements from a HashSet while Iterating

The reason you get a ConcurrentModificationException is because an entry is removed via Set.remove() as opposed to Iterator.remove(). If an entry is removed via Set.remove() while an iteration is being done, you will get a ConcurrentModificationException. On the other hand, removal of entries via Iterator.remove() while iteration is supported in this case.

The new for loop is nice, but unfortunately it does not work in this case, because you can't use the Iterator reference.

If you need to remove an entry while iteration, you need to use the long form that uses the Iterator directly.

for (Iterator<Integer> it = set.iterator(); it.hasNext();) {
    Integer element = it.next();
    if (element % 2 == 0) {
        it.remove();
    }
}

How can I clear the content of a file?

Use FileMode.Truncate everytime you create the file. Also place the File.Create inside a try catch.

How do I increase the RAM and set up host-only networking in Vagrant?

I could not get any of these answers to work. Here's what I ended up putting at the very top of my Vagrantfile, before the Vagrant::Config.run do block:

Vagrant.configure("2") do |config|
  config.vm.provider "virtualbox" do |vb|
    vb.customize ["modifyvm", :id, "--memory", "1024"]
  end
end

I noticed that the shortcut accessor style, "vb.memory = 1024", didn't seem to work.

The import javax.persistence cannot be resolved

Yes, you will likely need to add another jar or dependency

javax.persistence.* is part of the Java Persistence API (JPA). It is only an API, you can think of it as similar to an interface. There are many implementations of JPA and this answer gives a very good elaboration of each, as well as which to use.

If your javax.persistence.* import cannot be resolved, you will need to provide the jar that implements JPA. You can do that either by manually downloading it (and adding it to your project) or by adding a declaration to a dependency management tool (for eg, Ivy/Maven/Gradle). See here for the EclipseLink implementation (the reference implementation) on Maven repo.

After doing that, your imports should be resolved.

Also see here for what is JPA about. The xml you are referring to could be persistence.xml, which is explained on page 3 of the link.

That being said, you might just be pointing to the wrong target runtime

If i recall correctly, you don't need to provide a JPA implementation if you are deploying it into a JavaEE app server like JBoss. See here "Note that you typically don't need it when you deploy your application in a Java EE 6 application server (like JBoss AS 6 for example).". Try changing your project's target runtime.

If your local project was setup to point to Tomcat while your remote repo assumes a JavaEE server, this could be the case. See here for the difference between Tomcat and JBoss.

Edit: I changed my project to point to GlassFish instead of Tomcat and javax.persistence.* resolved fine without any explicit JPA dependency.

Expand a div to fill the remaining width

A slightly different implementation,

Two div panels(content+extra), side by side, content panel expands if extra panel is not present.

jsfiddle: http://jsfiddle.net/qLTMf/1722/

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

I've always thought that DLLs and shared objects are just different terms for the same thing - Windows calls them DLLs, while on UNIX systems they're shared objects, with the general term - dynamically linked library - covering both (even the function to open a .so on UNIX is called dlopen() after 'dynamic library').

They are indeed only linked at application startup, however your notion of verification against the header file is incorrect. The header file defines prototypes which are required in order to compile the code which uses the library, but at link time the linker looks inside the library itself to make sure the functions it needs are actually there. The linker has to find the function bodies somewhere at link time or it'll raise an error. It ALSO does that at runtime, because as you rightly point out the library itself might have changed since the program was compiled. This is why ABI stability is so important in platform libraries, as the ABI changing is what breaks existing programs compiled against older versions.

Static libraries are just bundles of object files straight out of the compiler, just like the ones that you are building yourself as part of your project's compilation, so they get pulled in and fed to the linker in exactly the same way, and unused bits are dropped in exactly the same way.

Access a JavaScript variable from PHP

JS ist browser-based, PHP is server-based. You have to generate some browser-based request/signal to get the data from the JS into the PHP. Take a look into Ajax.

An Iframe I need to refresh every 30 seconds (but not the whole page)

add "id='myiframe'" to the iframe, then use this script :

<script>

function f1()
{
 var x=document.getElementById("myiframe");
   x.src=x.src+Math.floor(random()%100000);
}

setInterval(f1,30*1000);

</script>

Android Studio-No Module

For some reason, I was missing the settings.gradle file.

  1. Create settings.gradle under your root directory, and inside it:
include ':app'

(assuming your app is indeed inside /app directory).

  1. Hit File -> Sync Project with Gradle Files.


After that everything worked out for me.

Import JSON file in React

Something that worked for me was to simply place the JSON file in the public folder. You can simply import in any js using

brain.loadData("exampleFile.json");

It is as simple as that I guess. Definitely worth a try :D

How can I output a UTF-8 CSV in PHP that Excel will read properly?

How about just outputting for Excel itself? This is an excellent class that allows you to generate XLS files server-side. I use it frequently for clients who can't "figure out" csv's and so far have never had a complaint. It also allows some extra formatting (shading, rowheights, calculations, etc) that csv won't ever do.

How to check encoding of a CSV file

In Linux systems, you can use file command. It will give the correct encoding

Sample:

file blah.csv

Output:

blah.csv: ISO-8859 text, with very long lines

See :hover state in Chrome Developer Tools

Now you can see both the pseudo-class rules and force them on elements.

To see the rules like :hover in the Styles pane click the small :hov text in the top right.

Toggle element state

To force an element into :hover state, right click it and select :hover.

Force element state

Additional tips on the elements panel in Chrome Developer Tools Shortcuts.

Creating a procedure in mySql with parameters

(IN @brugernavn varchar(64)**)**,IN @password varchar(64))

The problem is the )

What is the difference between call and apply?

Even though call and apply achive the same thing, I think there is atleast one place where you cannot use call but can only use apply. That is when you want to support inheritance and want to call the constructor.

Here is a function allows you to create classes which also supports creating classes by extending other classes.

function makeClass( properties ) {
    var ctor = properties['constructor'] || function(){}
    var Super = properties['extends'];
    var Class = function () {
                 // Here 'call' cannot work, only 'apply' can!!!
                 if(Super)
                    Super.apply(this,arguments);  
                 ctor.apply(this,arguments);
                }
     if(Super){
        Class.prototype = Object.create( Super.prototype );
        Class.prototype.constructor = Class;
     }
     Object.keys(properties).forEach( function(prop) {
           if(prop!=='constructor' && prop!=='extends')
            Class.prototype[prop] = properties[prop];
     });
   return Class; 
}

//Usage
var Car = makeClass({
             constructor: function(name){
                         this.name=name;
                        },
             yourName: function() {
                     return this.name;
                   }
          });
//We have a Car class now
 var carInstance=new Car('Fiat');
carInstance.youName();// ReturnsFiat

var SuperCar = makeClass({
               constructor: function(ignore,power){
                     this.power=power;
                  },
               extends:Car,
               yourPower: function() {
                    return this.power;
                  }
              });
//We have a SuperCar class now, which is subclass of Car
var superCar=new SuperCar('BMW xy',2.6);
superCar.yourName();//Returns BMW xy
superCar.yourPower();// Returns 2.6

Insert node at a certain position in a linked list C++

For inserting at a particular position k, you need to traverse the list till the position k-1 and then do the insert.

[You need not create a new node to traverse to that position as you did in your code] You should traverse from the head node.

C++ - struct vs. class

You could prove to yourself that there is no other difference by trying to define a function in a struct. I remember even my college professor who was teaching about structs and classes in C++ was surprised to learn this (after being corrected by a student). I believe it, though. It was kind of amusing. The professor kept saying what the differences were and the student kept saying "actually you can do that in a struct too". Finally the prof. asked "OK, what is the difference" and the student informed him that the only difference was the default accessibility of members.

A quick Google search suggests that POD stands for "Plain Old Data".

Python list / sublist selection -1 weirdness

when slicing an array;

ls[y:x]  

takes the slice from element y upto and but not including x. when you use the negative indexing it is equivalent to using

ls[y:-1] == ls[y:len(ls)-1]

so it so the slice would be upto the last element, but it wouldn't include it (as per the slice)

Target elements with multiple classes, within one rule

.border-blue.background { ... } is for one item with multiple classes.
.border-blue, .background { ... } is for multiple items each with their own class.
.border-blue .background { ... } is for one item where '.background' is the child of '.border-blue'.

See Chris' answer for a more thorough explanation.

How to extract closed caption transcript from YouTube video?

I just got this easily done manually by opening the transcript at the beginning of the video and left-clicking and dragging at the time 00:00 marker with the shift key pressed over a few lines at the beginning.

I then advanced the video to near the end. When the video stopped, I clicked the end of the last sentence whilst holding down the shift key once more. With CTRL-C I copied the text to the clipboard and pasted it into an editor.

Done!

Caveat: Be sure to have no RDP-Windows sharing the clipboard or Software such as Teamviewer is running at the same time as this procedure will overflow their buffers where a large amount of text is copied.

Can I pass a JavaScript variable to another browser window?

Alternatively, you can add it to the URL and let the scripting language (PHP, Perl, ASP, Python, Ruby, whatever) handle it on the other side. Something like:

var x = 10;
window.open('mypage.php?x='+x);

Is there a java setting for disabling certificate validation?

Use cli utility keytool from java software distribution for import (and trust!) needed certificates

Sample:

  1. From cli change dir to jre\bin

  2. Check keystore (file found in jre\bin directory)
    keytool -list -keystore ..\lib\security\cacerts
    Enter keystore password: changeit

  3. Download and save all certificates chain from needed server.

  4. Add certificates (before need to remove "read-only" attribute on file "..\lib\security\cacerts") keytool -alias REPLACE_TO_ANY_UNIQ_NAME -import -keystore ..\lib\security\cacerts -file "r:\root.crt"

accidentally I found such a simple tip. Other solutions require the use of InstallCert.Java and JDK

source: http://www.java-samples.com/showtutorial.php?tutorialid=210

sum two columns in R

tablename$column3=rowSums(cbind(tablename$column1,tablename$column2),na.rm=TRUE)

This can be used to ignore blank values in the excel sheet.
I have used for Euro stat dataset.

This example works in R:

crime_stat_data$All_theft <-rowSums(cbind(crime_stat_data$Theft,crime_stat_data$Theft_of_a_motorised_land_vehicle, crime_stat_data$Burglary, crime_stat_data$Burglary_of_private_residential_premises), na.rm=TRUE)  

Best practice multi language website

Topic's premise

There are three distinct aspects in a multilingual site:

  • interface translation
  • content
  • url routing

While they all interconnected in different ways, from CMS point of view they are managed using different UI elements and stored differently. You seem to be confident in your implementation and understanding of the first two. The question was about the latter aspect - "URL Translation? Should we do this or not? and in what way?"

What the URL can be made of?

A very important thing is, don't get fancy with IDN. Instead favor transliteration (also: transcription and romanization). While at first glance IDN seems viable option for international URLs, it actually does not work as advertised for two reasons:

  • some browsers will turn the non-ASCII chars like '?' or 'ž' into '%D1%87' and '%C5%BE'
  • if user has custom themes, the theme's font is very likely to not have symbols for those letters

I actually tried to IDN approach few years ago in a Yii based project (horrible framework, IMHO). I encountered both of the above mentioned problems before scraping that solution. Also, I suspect that it might be an attack vector.

Available options ... as I see them.

Basically you have two choices, that could be abstracted as:

  • http://site.tld/[:query]: where [:query] determines both language and content choice

  • http://site.tld/[:language]/[:query]: where [:language] part of URL defines the choice of language and [:query] is used only to identify the content

Query is ? and O ..

Lets say you pick http://site.tld/[:query].

In that case you have one primary source of language: the content of [:query] segment; and two additional sources:

  • value $_COOKIE['lang'] for that particular browser
  • list of languages in HTTP Accept-Language (1), (2) header

First, you need to match the query to one of defined routing patterns (if your pick is Laravel, then read here). On successful match of pattern you then need to find the language.

You would have to go through all the segments of the pattern. Find the potential translations for all of those segments and determine which language was used. The two additional sources (cookie and header) would be used to resolve routing conflicts, when (not "if") they arise.

Take for example: http://site.tld/blog/novinka.

That's transliteration of "????, ???????", that in English means approximately "blog", "latest".

As you can already notice, in Russian "????" will be transliterated as "blog". Which means that for the first part of [:query] you (in the best case scenario) will end up with ['en', 'ru'] list of possible languages. Then you take next segment - "novinka". That might have only one language on the list of possibilities: ['ru'].

When the list has one item, you have successfully found the language.

But if you end up with 2 (example: Russian and Ukrainian) or more possibilities .. or 0 possibilities, as a case might be. You will have to use cookie and/or header to find the correct option.

And if all else fails, you pick the site's default language.

Language as parameter

The alternative is to use URL, that can be defined as http://site.tld/[:language]/[:query]. In this case, when translating query, you do not need to guess the language, because at that point you already know which to use.

There is also a secondary source of language: the cookie value. But here there is no point in messing with Accept-Language header, because you are not dealing with unknown amount of possible languages in case of "cold start" (when user first time opens site with custom query).

Instead you have 3 simple, prioritized options:

  1. if [:language] segment is set, use it
  2. if $_COOKIE['lang'] is set, use it
  3. use default language

When you have the language, you simply attempt to translate the query, and if translation fails, use the "default value" for that particular segment (based on routing results).

Isn't here a third option?

Yes, technically you can combine both approaches, but that would complicate the process and only accommodate people who want to manually change URL of http://site.tld/en/news to http://site.tld/de/news and expect the news page to change to German.

But even this case could probable be mitigated using cookie value (which would contain information about previous choice of language), to implement with less magic and hope.

Which approach to use?

As you might already guessed, I would recommend http://site.tld/[:language]/[:query] as the more sensible option.

Also in real word situation you would have 3rd major part in URL: "title". As in name of the product in online shop or headline of article in news site.

Example: http://site.tld/en/news/article/121415/EU-as-global-reserve-currency

In this case '/news/article/121415' would be the query, and the 'EU-as-global-reserve-currency' is title. Purely for SEO purposes.

Can it be done in Laravel?

Kinda, but not by default.

I am not too familiar with it, but from what I have seen, Laravel uses simple pattern-based routing mechanism. To implement multilingual URLs you will probably have to extend core class(es), because multilingual routing need access to different forms of storage (database, cache and/or configuration files).

It's routed. What now?

As a result of all you would end up with two valuable pieces of information: current language and translated segments of query. These values then can be used to dispatch to the class(es) which will produce the result.

Basically, the following URL: http://site.tld/ru/blog/novinka (or the version without '/ru') gets turned into something like

$parameters = [
   'language' => 'ru',
   'classname' => 'blog',
   'method' => 'latest',
];

Which you just use for dispatching:

$instance = new {$parameter['classname']};
$instance->{'get'.$parameters['method']}( $parameters );

.. or some variation of it, depending on the particular implementation.

How to convert from []byte to int in Go Programming

now := []byte{0xFF,0xFF,0xFF,0xFF}
nowBuffer := bytes.NewReader(now)
var  nowVar uint32
binary.Read(nowBuffer,binary.BigEndian,&nowVar)
fmt.Println(nowVar)
4294967295

removing bold styling from part of a header

If you don't want a separate CSS file, you can use inline CSS:

<h1>This text should be bold, <span style="font-weight:normal">but this text should not</span></h1>

However, as Madara's comment suggests, you might want to consider putting the unbolded part in a different header, depending on the use case involved.

What is this: [Ljava.lang.Object;?

[Ljava.lang.Object; is the name for Object[].class, the java.lang.Class representing the class of array of Object.

The naming scheme is documented in Class.getName():

If this class object represents a reference type that is not an array type then the binary name of the class is returned, as specified by the Java Language Specification (§13.1).

If this class object represents a primitive type or void, then the name returned is the Java language keyword corresponding to the primitive type or void.

If this class object represents a class of arrays, then the internal form of the name consists of the name of the element type preceded by one or more '[' characters representing the depth of the array nesting. The encoding of element type names is as follows:

Element Type        Encoding
boolean             Z
byte                B
char                C
double              D
float               F
int                 I
long                J
short               S 
class or interface  Lclassname;

Yours is the last on that list. Here are some examples:

// xxxxx varies
System.out.println(new int[0][0][7]); // [[[I@xxxxx
System.out.println(new String[4][2]); // [[Ljava.lang.String;@xxxxx
System.out.println(new boolean[256]); // [Z@xxxxx

The reason why the toString() method on arrays returns String in this format is because arrays do not @Override the method inherited from Object, which is specified as follows:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Note: you can not rely on the toString() of any arbitrary object to follow the above specification, since they can (and usually do) @Override it to return something else. The more reliable way of inspecting the type of an arbitrary object is to invoke getClass() on it (a final method inherited from Object) and then reflecting on the returned Class object. Ideally, though, the API should've been designed such that reflection is not necessary (see Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection).


On a more "useful" toString for arrays

java.util.Arrays provides toString overloads for primitive arrays and Object[]. There is also deepToString that you may want to use for nested arrays.

Here are some examples:

int[] nums = { 1, 2, 3 };

System.out.println(nums);
// [I@xxxxx

System.out.println(Arrays.toString(nums));
// [1, 2, 3]

int[][] table = {
        { 1, },
        { 2, 3, },
        { 4, 5, 6, },
};

System.out.println(Arrays.toString(table));
// [[I@xxxxx, [I@yyyyy, [I@zzzzz]

System.out.println(Arrays.deepToString(table));
// [[1], [2, 3], [4, 5, 6]]

There are also Arrays.equals and Arrays.deepEquals that perform array equality comparison by their elements, among many other array-related utility methods.

Related questions

jQuery: enabling/disabling datepicker

try

$("#from").datepicker().datepicker('disable');

Find all elements on a page whose element ID contains a certain text using jQuery

Thanks to both of you. This worked perfectly for me.

$("input[type='text'][id*=" + strID + "]:visible").each(function() {
    this.value=strVal;
});

How to work with string fields in a C struct?

On strings and memory allocation:

A string in C is just a sequence of chars, so you can use char * or a char array wherever you want to use a string data type:

typedef struct     {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} patient;

Then you need to allocate memory for the structure itself, and for each of the strings:

patient *createPatient(int number, char *name, 
  char *addr, char *bd, char sex) {

  // Allocate memory for the pointers themselves and other elements
  // in the struct.
  patient *p = malloc(sizeof(struct patient));

  p->number = number; // Scalars (int, char, etc) can simply be copied

  // Must allocate memory for contents of pointers.  Here, strdup()
  // creates a new copy of name.  Another option:
  // p->name = malloc(strlen(name)+1);
  // strcpy(p->name, name);
  p->name = strdup(name);
  p->address = strdup(addr);
  p->birthdate = strdup(bd);
  p->gender = sex;
  return p;
}

If you'll only need a few patients, you can avoid the memory management at the expense of allocating more memory than you really need:

typedef struct     {
  int number;
  char name[50];       // Declaring an array will allocate the specified
  char address[200];   // amount of memory when the struct is created,
  char birthdate[50];  // but pre-determines the max length and may
  char gender;         // allocate more than you need.
} patient;

On linked lists:

In general, the purpose of a linked list is to prove quick access to an ordered collection of elements. If your llist contains an element called num (which presumably contains the patient number), you need an additional data structure to hold the actual patients themselves, and you'll need to look up the patient number every time.

Instead, if you declare

typedef struct llist
{
  patient *p;
  struct llist *next;
} list;

then each element contains a direct pointer to a patient structure, and you can access the data like this:

patient *getPatient(list *patients, int num) {
  list *l = patients;
  while (l != NULL) {
    if (l->p->num == num) {
      return l->p;
    }
    l = l->next;
  }
  return NULL;
}

Is it possible to hide the cursor in a webpage using CSS or Javascript?

I did it with transparent *.cur 1px to 1px, but it looks like small dot. :( I think it's the best cross-browser thing that I can do. CSS2.1 has no value 'none' for 'cursor' property - it was added in CSS3. Thats why it's workable not everywhere.

How to add external JS scripts to VueJS Components

If you are trying to embed external js scripts to the vue.js component template, follow below:

I wanted to add a external javascript embed code to my component like this:

<template>
  <div>
    This is my component
    <script src="https://badge.dimensions.ai/badge.js"></script>
  </div>
<template>

And Vue showed me this error:

Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as , as they will not be parsed.


The way I solved it was by adding type="application/javascript" (See this question to learn more about MIME type for js):

<script type="application/javascript" defer src="..."></script>


You may notice the defer attribute. If you want to learn more watch this video by Kyle

How can I write a regex which matches non greedy?

The ? operand makes match non-greedy. E.g. .* is greedy while .*? isn't. So you can use something like <img.*?> to match the whole tag. Or <img[^>]*>.

But remember that the whole set of HTML can't be actually parsed with regular expressions.

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

Alternative to commandline Solution:

Recently I was playing with Services in Mac OS X. I added a service to a folder or file so that I can open that folder or file in Visual Studio Code. I think this could be an alternative to using 'code .' command if you are using the Finder app. Here are the steps:

  • Open Automator App from Application. (Or you can use Spotlight).
  • Click on 'New Document' button to create a new script.
  • Choose 'Service' as a new type of document.
  • Select 'files and folders' in 'Service receives selected' dropdown.
  • Search for 'Open Finder Items' action item.
  • Drag that action item to the workflow area.
  • Select 'Visual Studio Code.app' application in the action 'Open with' dropdown.
  • Press 'command + s' to save the service. It will ask a name of service. Give it a name. I gave 'Open with VSCode'. Close the Automator app. Check the image below for more information.

enter image description here

Verify:

  • Open the Finder app.
  • Right-click on any folder.
  • In the context menu, look for 'Open with VSCode' menu option.
  • Click on the 'Open with VSCode' menu option.
  • The folder should get open in the Visual Studio Code application. Check image below for more info.

enter image description here

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

You can always do this:

jQuery.fn.extend({
   myfunction: function(param){
       // code here
   },
});
OR
jQuery.extend({
   myfunction: function(param){
       // code here
   },
});
$(element).myfunction(param);

PHP fopen() Error: failed to open stream: Permission denied

You may need to change the permissions as an administrator. Open up terminal on your Mac and then open the directory that markers.xml is located in. Then type:

sudo chmod 777 markers.xml

You may be prompted for a password. Also, it could be the directories that don't allow full access. I'm not familiar with WordPress, so you may have to change the permission of each directory moving upward to the mysite directory.

How to call a parent method from child class in javascript?

While you can call the parent method by the prototype of the parent, you will need to pass the current child instance for using call, apply, or bind method. The bind method will create a new function so I doesn't recommend that if you care for performance except it only called once.

As an alternative you can replace the child method and put the parent method on the instance while calling the original child method.

_x000D_
_x000D_
function proxy(context, parent){
  var proto = parent.prototype;
  var list = Object.getOwnPropertyNames(proto);
  
  for(var i=0; i < list.length; i++){
    var key = list[i];

    // Create only when child have similar method name
    if(context[key] !== proto[key]){
      let currentMethod = context[key];
      let parentMethod = proto[key];
      
      context[key] = function(){
        context.super = parentMethod;
        return currentMethod.apply(context, arguments);
      }
    }
  }
}

// ========= The usage would be like this ==========

class Parent {
  first = "Home";

  constructor(){
    console.log('Parent created');
  }

  add(arg){
    return this.first + ", Parent "+arg;
  }
}

class Child extends Parent{
  constructor(b){
    super();
    proxy(this, Parent);
    console.log('Child created');
  }

  // Comment this to call method from parent only
  add(arg){
    return super.add(arg) + ", Child "+arg;
  }
}

var family = new Child();
console.log(family.add('B'));
_x000D_
_x000D_
_x000D_

Javascript add leading zeroes to date

I wrapped the correct answer of this question in a function that can add multiple leading zero's but defaults to adding 1 zero.

function zeroFill(nr, depth){
  depth = (depth === undefined)? 1 : depth;

  var zero = "0";
  for (var i = 0; i < depth; ++i) {
    zero += "0";
  }

  return (zero + nr).slice(-(depth + 1));
}

for working with numbers only and not more than 2 digits, this is also an approach:

function zeroFill(i) {
    return (i < 10 ? '0' : '') + i
  }

Pandas group-by and sum

A variation on the .agg() function; provides the ability to (1) persist type DataFrame, (2) apply averages, counts, summations, etc. and (3) enables groupby on multiple columns while maintaining legibility.

df.groupby(['att1', 'att2']).agg({'att1': "count", 'att3': "sum",'att4': 'mean'})

using your values...

df.groupby(['Name', 'Fruit']).agg({'Number': "sum"})

Programmatically change the height and width of a UIImageView Xcode Swift

Hey i figured it out shortly after. For some reason I was just having a brain fart.

image.frame = CGRectMake(0 , 0, self.view.frame.width, self.view.frame.height * 0.2)

Changing minDate and maxDate on the fly using jQuery DatePicker

I have changed min date property of date time picker by using this

$('#date').data("DateTimePicker").minDate(startDate);

I hope this one help to someone !