Programs & Examples On #Macrubyc

VB.NET Connection string (Web.Config, App.Config)

If it's a .mdf database and the connection string was saved when it was created, you should be able to access it via:

    Dim cn As SqlConnection = New SqlConnection(My.Settings.DatabaseNameConnectionString)

Hope that helps someone.

Deleting a file in VBA

I'll probably get flamed for this, but what is the point of testing for existence if you are just going to delete it? One of my major pet peeves is an app throwing an error dialog with something like "Could not delete file, it does not exist!"

On Error Resume Next
aFile = "c:\file_to_delete.txt"
Kill aFile
On Error Goto 0
return Len(Dir$(aFile)) > 0 ' Make sure it actually got deleted.

If the file doesn't exist in the first place, mission accomplished!

How to mention C:\Program Files in batchfile

While createting the bat file, you can easly avoid the space. If you want to mentioned "program files "folder in batch file.

Do following steps:

1. Type c: then press enter

2. cd program files

3. cd "choose your own folder name"

then continue as you wish.

This way you can create batch file and you can mention program files folder.

How to parse JSON to receive a Date object in JavaScript?

I ran into an issue with external API providing dates in this format, some times even with UTC difference info like /Date(123232313131+1000)/. I was able to turn it js Date object with following code

var val = '/Date(123232311-1000)/';
var pattern = /^\/Date\([0-9]+((\+|\-)[0-9]+)?\)\/$/;
var date = null;

// Check that the value matches /Date(123232311-1000)/ format
if (pattern.test(val)) {
  var number = val.replace('/Date(', '',).replace(')/', '');
  if (number.indexOf('+') >= 0) {
    var split = number.split('+');
    number = parseInt(split[0]) + parseInt(split[1]);
  } else if (number.indexOf('-') >= 0) {
    var split = number.split('-');
    number = parseInt(split[0]) - parseInt(split[1]);
  } else {
    number = parseInt(number);
    date = new Date(number);
  }
}

Meaning of "referencing" and "dereferencing" in C

find the below explanation:

int main()
{
    int a = 10;// say address of 'a' is 2000;
    int *p = &a; //it means 'p' is pointing[referencing] to 'a'. i.e p->2000
    int c = *p; //*p means dereferncing. it will give the content of the address pointed by 'p'. in this case 'p' is pointing to 2000[address of 'a' variable], content of 2000 is 10. so *p will give 10. 
}

conclusion :

  1. & [address operator] is used for referencing.
  2. * [star operator] is used for de-referencing .

Making div content responsive

Not a lot to go on there, but I think what you're looking for is to flip the width and max-width values:

#container2 {
  width: 90%;
  max-width: 960px;
  /* etc, etc... */
}

That'll give you a container that's 90% of the width of the available space, up to a maximum of 960px, but that's dependent on its container being resizable itself. Responsive design is a whole big ball of wax though, so this doesn't even scratch the surface.

How to sort alphabetically while ignoring case sensitive?

Pass java.text.Collator.getInstance() to Collections.sort method ; it will sort Alphabetically while ignoring case sensitive.

        ArrayList<String> myArray = new ArrayList<String>();
        myArray.add("zzz");
        myArray.add("xxx");
        myArray.add("Aaa");
        myArray.add("bb");
        myArray.add("BB");
        Collections.sort(myArray,Collator.getInstance());

How to check if array is not empty?

I can't comment yet, but it should be mentioned that if you use numpy array with more than one element this will fail:

if l:
    print "list has items"

elif not l:
    print "list is empty"

the error will be:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Using union and order by clause in mysql

You can do this by adding a pseudo-column named rank to each select, that you can sort by first, before sorting by your other criteria, e.g.:

select *
from (
    select 1 as Rank, id, add_date from Table 
    union all
    select 2 as Rank, id, add_date from Table where distance < 5
    union all
    select 3 as Rank, id, add_date from Table where distance between 5 and 15
) a
order by rank, id, add_date desc

Replace only text inside a div using jquery

You need to set the text to something other than an empty string. In addition, the .html() function should do it while preserving the HTML structure of the div.

$('#one').html($('#one').html().replace('text','replace'));

sed fails with "unknown option to `s'" error

The problem is with slashes: your variable contains them and the final command will be something like sed "s/string/path/to/something/g", containing way too many slashes.

Since sed can take any char as delimiter (without having to declare the new delimiter), you can try using another one that doesn't appear in your replacement string:

replacement="/my/path"
sed --expression "s@pattern@$replacement@"

Note that this is not bullet proof: if the replacement string later contains @ it will break for the same reason, and any backslash sequences like \1 will still be interpreted according to sed rules. Using | as a delimiter is also a nice option as it is similar in readability to /.

RESTful API methods; HEAD & OPTIONS

As per: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

9.2 OPTIONS

The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.

Responses to this method are not cacheable.

If the OPTIONS request includes an entity-body (as indicated by the presence of Content-Length or Transfer-Encoding), then the media type MUST be indicated by a Content-Type field. Although this specification does not define any use for such a body, future extensions to HTTP might use the OPTIONS body to make more detailed queries on the server. A server that does not support such an extension MAY discard the request body.

If the Request-URI is an asterisk ("*"), the OPTIONS request is intended to apply to the server in general rather than to a specific resource. Since a server's communication options typically depend on the resource, the "*" request is only useful as a "ping" or "no-op" type of method; it does nothing beyond allowing the client to test the capabilities of the server. For example, this can be used to test a proxy for HTTP/1.1 compliance (or lack thereof).

If the Request-URI is not an asterisk, the OPTIONS request applies only to the options that are available when communicating with that resource.

A 200 response SHOULD include any header fields that indicate optional features implemented by the server and applicable to that resource (e.g., Allow), possibly including extensions not defined by this specification. The response body, if any, SHOULD also include information about the communication options. The format for such a body is not defined by this specification, but might be defined by future extensions to HTTP. Content negotiation MAY be used to select the appropriate response format. If no response body is included, the response MUST include a Content-Length field with a field-value of "0".

The Max-Forwards request-header field MAY be used to target a specific proxy in the request chain. When a proxy receives an OPTIONS request on an absoluteURI for which request forwarding is permitted, the proxy MUST check for a Max-Forwards field. If the Max-Forwards field-value is zero ("0"), the proxy MUST NOT forward the message; instead, the proxy SHOULD respond with its own communication options. If the Max-Forwards field-value is an integer greater than zero, the proxy MUST decrement the field-value when it forwards the request. If no Max-Forwards field is present in the request, then the forwarded request MUST NOT include a Max-Forwards field.

9.4 HEAD

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. The metainformation contained in the HTTP headers in response to a HEAD request SHOULD be identical to the information sent in response to a GET request. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

The response to a HEAD request MAY be cacheable in the sense that the information contained in the response MAY be used to update a previously cached entity from that resource. If the new field values indicate that the cached entity differs from the current entity (as would be indicated by a change in Content-Length, Content-MD5, ETag or Last-Modified), then the cache MUST treat the cache entry as stale.

how to download image from any web page in java

This works for me:

URL url = new URL("http://upload.wikimedia.org/wikipedia/commons/9/9c/Image-Porkeri_001.jpg");
InputStream in = new BufferedInputStream(url.openStream());
OutputStream out = new BufferedOutputStream(new FileOutputStream("Image-Porkeri_001.jpg"));

for ( int i; (i = in.read()) != -1; ) {
    out.write(i);
}
in.close();
out.close();

C++ display stack trace on exception

The following code stops the execution right after an exception is thrown. You need to set a windows_exception_handler along with a termination handler. I tested this in MinGW 32bits.

void beforeCrash(void);

static const bool SET_TERMINATE = std::set_terminate(beforeCrash);

void beforeCrash() {
    __asm("int3");
}

int main(int argc, char *argv[])
{
SetUnhandledExceptionFilter(windows_exception_handler);
...
}

Check the following code for the windows_exception_handler function: http://www.codedisqus.com/0ziVPgVPUk/exception-handling-and-stacktrace-under-windows-mingwgcc.html

Passing HTML input value as a JavaScript Function Parameter

Use this it will work,

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="a"><br>
  <button onclick="add()">Add</button>
</form>
<script>
  function add() {
    var m = document.getElementById("a").value;
    var n = document.getElementById("b").value;
    var sum = m + n;
    alert(sum);
  }
</script>
</body>

Align button at the bottom of div using CSS

Goes to the right and can be used the same way for the left

.yourComponent
{
   float: right;
   bottom: 0;
}

Getting selected value of a combobox

You are getting NullReferenceExeption because of you are using the cmb.SelectedValue which is null. the comboBox doesn't know what is the value of your custom class ComboboxItem, so either do:

ComboboxItem selectedCar = (ComboboxItem)comboBox2.SelectedItem;
int selecteVal = Convert.ToInt32(selectedCar.Value);

Or better of is use data binding like:

ComboboxItem item1 = new ComboboxItem();
item1.Text = "test";
item1.Value = "123";

ComboboxItem item2 = new ComboboxItem();
item2.Text = "test2";
item2.Value = "456";

List<ComboboxItem> items = new List<ComboboxItem> { item1, item2 };

this.comboBox1.DisplayMember = "Text";
this.comboBox1.ValueMember = "Value";
this.comboBox1.DataSource = items;

Vim delete blank lines

This worked for me:

:%s/^[^a-zA-Z0-9]$\n//ig

It basically deletes all the lines that don't have a number or letter. Since all the items in my list had letters, it deleted all the blank lines.

Transparent ARGB hex value

Just came across this and the short code for transparency is simply #00000000.

How to handle ListView click in Android

You have to use setOnItemClickListener someone said.
The code should be like this:

listView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // When clicked, show a toast with the TextView text or do whatever you need.
        Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
    }
});

How can I set the 'backend' in matplotlib in Python?

Your currently selected backend, 'agg' does not support show().

AGG backend is for writing to file, not for rendering in a window. See the backend FAQ at the matplotlib web site.

ImportError: No module named _backend_gdk

For the second error, maybe your matplotlib distribution is not compiled with GTK support, or you miss the PyGTK package. Try to install it.

Do you call the show() method inside a terminal or application that has access to a graphical environment?

Try other GUI backends, in this order:

  • TkAgg
  • WX
  • QTAgg
  • QT4Agg

Jquery get form field value

You can try these lines:

$("#DynamicValueAssignedHere .formdiv form").contents().find("input[name='FirstName']").prevObject[1].value

How can I find the version of php that is running on a distinct domain name?

Sometimes, PHP will emit a X-Powered-By: response header which you can look at e.g. using Firebug.

If this setting (controlled by the ini setting expose_php) is turned off (it often is), there is no way to tell the PHP version used - and rightly so. What PHP version is running is none of the outside world's business, and it's good to obscure this from a security perspective.

Count the number occurrences of a character in a string

str.count(sub[, start[, end]])

Return the number of non-overlapping occurrences of substring sub in the range [start, end]. Optional arguments start and end are interpreted as in slice notation.

>>> sentence = 'Mary had a little lamb'
>>> sentence.count('a')
4

if condition in sql server update query

this worked great:

UPDATE
    table_Name
SET 
  column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
  column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
    ID = @ID

How can I insert values into a table, using a subquery with more than one result?

INSERT INTO prices(group, id, price)
SELECT 7, articleId, 1.50
FROM article where name like 'ABC%';

JavaScript equivalent of PHP's in_array()

No, it doesn't have one. For this reason most popular libraries come with one in their utility packages. Check out jQuery's inArray and Prototype's Array.indexOf for examples.

jQuery's implementation of it is as simple as you might expect:

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(haystack[i] == needle) return true;
    }
    return false;
}

If you are dealing with a sane amount of array elements the above will do the trick nicely.

EDIT: Whoops. I didn't even notice you wanted to see if an array was inside another. According to the PHP documentation this is the expected behavior of PHP's in_array:

$a = array(array('p', 'h'), array('p', 'r'), 'o');

if (in_array(array('p', 'h'), $a)) {
    echo "'ph' was found\n";
}

if (in_array(array('f', 'i'), $a)) {
    echo "'fi' was found\n";
}

if (in_array('o', $a)) {
    echo "'o' was found\n";
}

// Output:
//  'ph' was found
//  'o' was found

The code posted by Chris and Alex does not follow this behavior. Alex's is the official version of Prototype's indexOf, and Chris's is more like PHP's array_intersect. This does what you want:

function arrayCompare(a1, a2) {
    if (a1.length != a2.length) return false;
    var length = a2.length;
    for (var i = 0; i < length; i++) {
        if (a1[i] !== a2[i]) return false;
    }
    return true;
}

function inArray(needle, haystack) {
    var length = haystack.length;
    for(var i = 0; i < length; i++) {
        if(typeof haystack[i] == 'object') {
            if(arrayCompare(haystack[i], needle)) return true;
        } else {
            if(haystack[i] == needle) return true;
        }
    }
    return false;
}

And this my test of the above on it:

var a = [['p','h'],['p','r'],'o'];
if(inArray(['p','h'], a)) {
    alert('ph was found');
}
if(inArray(['f','i'], a)) {
    alert('fi was found');
}
if(inArray('o', a)) {
    alert('o was found');
}  
// Results:
//   alerts 'ph' was found
//   alerts 'o' was found

Note that I intentionally did not extend the Array prototype as it is generally a bad idea to do so.

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

Adding what worked for me in case others have the same issue and end up here. I had an older project that had the CLANG_ENABLE_MODULES setting set to No. After hours of frustration I compared to a working project and found I had Enable Modules Set to no under my LLVM build settings. Setting this to Yes solved my problem and the app builds fine.

Project Settings -> Build Settings -> search for 'Modules' and Update Enable Modules (C and Objective-C) to YES.

How do I access properties of a javascript object if I don't know the names?

Old versions of JavaScript (< ES5) require using a for..in loop:

for (var key in data) {
  if (data.hasOwnProperty(key)) {
    // do something with key
  }
}

ES5 introduces Object.keys and Array#forEach which makes this a little easier:

var data = { foo: 'bar', baz: 'quux' };

Object.keys(data); // ['foo', 'baz']
Object.keys(data).map(function(key){ return data[key] }) // ['bar', 'quux']
Object.keys(data).forEach(function (key) {
  // do something with data[key]
});

ES2017 introduces Object.values and Object.entries.

Object.values(data) // ['bar', 'quux']
Object.entries(data) // [['foo', 'bar'], ['baz', 'quux']]

How to set margin with jquery?

Set it with a px value. Changing the code like below should work

el.css('marginLeft', mrg + 'px');

How do I specify row heights in CSS Grid layout?

One of the Related posts gave me the (simple) answer.

Apparently the auto value on the grid-template-rows property does exactly what I was looking for.

.grid {
    display:grid;
    grid-template-columns: 1fr 1.5fr 1fr;
    grid-template-rows: auto auto 1fr 1fr 1fr auto auto;
    grid-gap:10px;
    height: calc(100vh - 10px);
}

Get the last non-empty cell in a column in Google Sheets

There may be a more eloquent way, but this is the way I came up with:

The function to find the last populated cell in a column is:

=INDEX( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ; ROWS( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ) )

So if you combine it with your current function it would look like this:

=DAYS360(A2,INDEX( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ; ROWS( FILTER( A:A ; NOT( ISBLANK( A:A ) ) ) ) ))

Using Tempdata in ASP.NET MVC - Best practice

Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.

The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

1. See information about the SQL server

tsql -LH SERVER_IP_ADDRESS

locale is "C"
locale charset is "646"
ServerName TITAN
InstanceName MSSQLSERVER
IsClustered No
Version 8.00.194
tcp 1433
np \\TITAN\pipe\sql\query

2. Set your freetds.conf

tsql -C    
freetds.conf directory: /usr/local/etc

[TITAN]
host = SERVER_IP_ADDRESS
port = 1433
tds version = 7.2

3 Try

tsql -S TITAN -U user -P password

OR

 'dsn' => 'dblib:host=TITAN:1433;dbname=YOURDBNAME',

See also http://www.freetds.org/userguide/confirminstall.htm (Example 3-5.)

If you get message 20009, remember you haven't connected to the machine. It's a configuration or network issue, not a protocol failure. Verify the server is up, has the name and IP address FreeTDS is using, and is listening to the configured port.

SQL Query for Logins

Have a look in the syslogins or sysusers tables in the master schema. Not sure if this still still around in more recent MSSQL versions though. In MSSQL 2005 there are views called sys.syslogins and sys.sysusers.

How do I install a NuGet package .nupkg file locally?

On Linux, with NuGet CLI, the commands are similar. To install my.nupkg, run

nuget add -Source some/directory my.nupkg

Then run dotnet restore from that directory

dotnet restore --source some/directory Project.sln

or add that directory as a NuGet source

nuget sources Add -Name MySource -Source some/directory

and then tell msbuild to use that directory with /p:RestoreAdditionalSources=MySource or /p:RestoreSources=MySource. The second switch will disable all other sources, which is good for offline scenarios, for example.

Android – Listen For Incoming SMS Messages

public class SmsListener extends BroadcastReceiver{

    private SharedPreferences preferences;

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            String msg_from;
            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    for(int i=0; i<msgs.length; i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        msg_from = msgs[i].getOriginatingAddress();
                        String msgBody = msgs[i].getMessageBody();
                    }
                }catch(Exception e){
//                            Log.d("Exception caught",e.getMessage());
                }
            }
        }
    }
}

Note: In your manifest file add the BroadcastReceiver-

<receiver android:name=".listener.SmsListener">
    <intent-filter>
        <action android:name="android.provider.Telephony.SMS_RECEIVED" />
    </intent-filter>
</receiver>

Add this permission:

<uses-permission android:name="android.permission.RECEIVE_SMS" />

Why is it bad practice to call System.gc()?

The reason everyone always says to avoid System.gc() is that it is a pretty good indicator of fundamentally broken code. Any code that depends on it for correctness is certainly broken; any that rely on it for performance are most likely broken.

You don't know what sort of garbage collector you are running under. There are certainly some that do not "stop the world" as you assert, but some JVMs aren't that smart or for various reasons (perhaps they are on a phone?) don't do it. You don't know what it's going to do.

Also, it's not guaranteed to do anything. The JVM may just entirely ignore your request.

The combination of "you don't know what it will do," "you don't know if it will even help," and "you shouldn't need to call it anyway" are why people are so forceful in saying that generally you shouldn't call it. I think it's a case of "if you need to ask whether you should be using this, you shouldn't"


EDIT to address a few concerns from the other thread:

After reading the thread you linked, there's a few more things I'd like to point out. First, someone suggested that calling gc() may return memory to the system. That's certainly not necessarily true - the Java heap itself grows independently of Java allocations.

As in, the JVM will hold memory (many tens of megabytes) and grow the heap as necessary. It doesn't necessarily return that memory to the system even when you free Java objects; it is perfectly free to hold on to the allocated memory to use for future Java allocations.

To show that it's possible that System.gc() does nothing, view:

http://bugs.sun.com/view_bug.do?bug_id=6668279

and in particular that there's a -XX:DisableExplicitGC VM option.

Initializing a list to a known number of elements in Python

Not quite sure why everyone is giving you a hard time for wanting to do this - there are several scenarios where you'd want a fixed size initialised list. And you've correctly deduced that arrays are sensible in these cases.

import array
verts=array.array('i',(0,)*1000)

For the non-pythonistas, the (0,)*1000 term is creating a tuple containing 1000 zeros. The comma forces python to recognise (0) as a tuple, otherwise it would be evaluated as 0.

I've used a tuple instead of a list because they are generally have lower overhead.

Test if numpy array contains only zeros

Check out numpy.count_nonzero.

>>> np.count_nonzero(np.eye(4))
4
>>> np.count_nonzero([[0,1,7,0,0],[3,0,0,2,19]])
5

How to choose an AES encryption mode (CBC ECB CTR OCB CFB)?

You might want to chose based on what is widely available. I had the same question and here are the results of my limited research.

Hardware limitations

STM32L (low energy ARM cores) from ST Micro support ECB, CBC,CTR GCM
CC2541 (Bluetooth Low Energy) from TI supports ECB, CBC, CFB, OFB, CTR, and CBC-MAC

Open source limitations

Original rijndael-api source  - ECB, CBC, CFB1
OpenSSL - command line CBC, CFB, CFB1, CFB8, ECB, OFB
OpenSSL - C/C++ API    CBC, CFB, CFB1, CFB8, ECB, OFB and CTR
EFAES lib [1] - ECB, CBC, PCBC, OFB, CFB, CRT ([sic] CTR mispelled)  
OpenAES [2] - ECB, CBC 

[1] http://www.codeproject.com/Articles/57478/A-Fast-and-Easy-to-Use-AES-Library

[2] https://openaes.googlecode.com/files/OpenAES-0.8.0.zip

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

If you are using eclipse and maven for handling dependencies, you may need to take these extra steps to make sure eclipse copies the dependencies properly Maven dependencies not visible in WEB-INF/lib (namely the Deployment Assembly for Dynamic web application)

Using $_POST to get select option value from HTML

You can do it like this, too:

<?php
if(isset($_POST['select1'])){
    $select1 = $_POST['select1'];
    switch ($select1) {
        case 'value1':
            echo 'this is value1<br/>';
            break;
        case 'value2':
            echo 'value2<br/>';
            break;
        default:
            # code...
            break;
    }
}
?>


<form action="" method="post">
    <select name="select1">
        <option value="value1">Value 1</option>
        <option value="value2">Value 2</option>
    </select>
    <input type="submit" name="submit" value="Go"/>
</form>

LocalDate to java.util.Date and vice versa simplest conversion?

Actually there is. There is a static method valueOf in the java.sql.Date object which does exactly that. So we have

java.util.Date date = java.sql.Date.valueOf(localDate);

and that's it. No explicit setting of time zones because the local time zone is taken implicitly.

From docs:

The provided LocalDate is interpreted as the local date in the local time zone.

The java.sql.Date subclasses java.util.Date so the result is a java.util.Date also.

And for the reverse operation there is a toLocalDate method in the java.sql.Date class. So we have:

LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();

The easiest way to replace white spaces with (underscores) _ in bash

This is borderline programming, but look into using tr:

$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'

Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.

preferredStatusBarStyle isn't called

If anyone is using a Navigation Controller and wants all of their navigation controllers to have the black style, you can write an extension to UINavigationController like this in Swift 3 and it will apply to all navigation controllers (instead of assigning it to one controller at a time).

extension UINavigationController {

    override open func viewDidLoad() {
        super.viewDidLoad()

        self.navigationBar.barStyle = UIBarStyle.black
    }

}

Convert nullable bool? to bool

You can use Nullable{T} GetValueOrDefault() method. This will return false if null.

 bool? nullableBool = null;

 bool actualBool = nullableBool.GetValueOrDefault();

Load local images in React.js

In order to load local images to your React.js application, you need to add require parameter in media sections like or Image tags, as below:

image={require('./../uploads/temp.jpg')}

How to use SVG markers in Google Maps API v3

OK! I done this soon in my web,I try two ways to create the custom google map marker, this run code use canvg.js is the best compatibility for browser.the Commented-Out Code is not support IE11 urrently.

_x000D_
_x000D_
var marker;_x000D_
var CustomShapeCoords = [16, 1.14, 21, 2.1, 25, 4.2, 28, 7.4, 30, 11.3, 30.6, 15.74, 25.85, 26.49, 21.02, 31.89, 15.92, 43.86, 10.92, 31.89, 5.9, 26.26, 1.4, 15.74, 2.1, 11.3, 4, 7.4, 7.1, 4.2, 11, 2.1, 16, 1.14];_x000D_
_x000D_
function initMap() {_x000D_
  var map = new google.maps.Map(document.getElementById('map'), {_x000D_
    zoom: 13,_x000D_
    center: {_x000D_
      lat: 59.325,_x000D_
      lng: 18.070_x000D_
    }_x000D_
  });_x000D_
  var markerOption = {_x000D_
    latitude: 59.327,_x000D_
    longitude: 18.067,_x000D_
    color: "#" + "000",_x000D_
    text: "ha"_x000D_
  };_x000D_
  marker = createMarker(markerOption);_x000D_
  marker.setMap(map);_x000D_
  marker.addListener('click', changeColorAndText);_x000D_
};_x000D_
_x000D_
function changeColorAndText() {_x000D_
  var iconTmpObj = createSvgIcon( "#c00", "ok" );_x000D_
  marker.setOptions( {_x000D_
                icon: iconTmpObj_x000D_
            } );_x000D_
};_x000D_
_x000D_
function createMarker(options) {_x000D_
  //IE MarkerShape has problem_x000D_
  var markerObj = new google.maps.Marker({_x000D_
    icon: createSvgIcon(options.color, options.text),_x000D_
    position: {_x000D_
      lat: parseFloat(options.latitude),_x000D_
      lng: parseFloat(options.longitude)_x000D_
    },_x000D_
    draggable: false,_x000D_
    visible: true,_x000D_
    zIndex: 10,_x000D_
    shape: {_x000D_
      coords: CustomShapeCoords,_x000D_
      type: 'poly'_x000D_
    }_x000D_
  });_x000D_
_x000D_
  return markerObj;_x000D_
};_x000D_
_x000D_
function createSvgIcon(color, text) {_x000D_
  var div = $("<div></div>");_x000D_
_x000D_
  var svg = $(_x000D_
    '<svg width="32px" height="43px"  viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">' +_x000D_
    '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>' +_x000D_
    '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>' +_x000D_
    '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>' +_x000D_
    '</svg>'_x000D_
  );_x000D_
  div.append(svg);_x000D_
_x000D_
  var dd = $("<canvas height='50px' width='50px'></cancas>");_x000D_
_x000D_
  var svgHtml = div[0].innerHTML;_x000D_
_x000D_
  canvg(dd[0], svgHtml);_x000D_
_x000D_
  var imgSrc = dd[0].toDataURL("image/png");_x000D_
  //"scaledSize" and "optimized: false" together seems did the tricky ---IE11  &&  viewBox influent IE scaledSize_x000D_
  //var svg = '<svg width="32px" height="43px"  viewBox="0 0 32 43" xmlns="http://www.w3.org/2000/svg">'_x000D_
  //    + '<path style="fill:#FFFFFF;stroke:#020202;stroke-width:1;stroke-miterlimit:10;" d="M30.6,15.737c0-8.075-6.55-14.6-14.6-14.6c-8.075,0-14.601,6.55-14.601,14.6c0,4.149,1.726,7.875,4.5,10.524c1.8,1.801,4.175,4.301,5.025,5.625c1.75,2.726,5,11.976,5,11.976s3.325-9.25,5.1-11.976c0.825-1.274,3.05-3.6,4.825-5.399C28.774,23.813,30.6,20.012,30.6,15.737z"/>'_x000D_
  //    + '<circle style="fill:' + color + ';" cx="16" cy="16" r="11"/>'_x000D_
  //    + '<text x="16" y="20" text-anchor="middle" style="font-size:10px;fill:#FFFFFF;">' + text + '</text>'_x000D_
  //    + '</svg>';_x000D_
  //var imgSrc = 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg);_x000D_
_x000D_
  var iconObj = {_x000D_
    size: new google.maps.Size(32, 43),_x000D_
    url: imgSrc,_x000D_
    scaledSize: new google.maps.Size(32, 43)_x000D_
  };_x000D_
_x000D_
  return iconObj;_x000D_
};
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <title>Your Custom Marker </title>_x000D_
  <style>_x000D_
    /* Always set the map height explicitly to define the size of the div_x000D_
       * element that contains the map. */_x000D_
    #map {_x000D_
      height: 100%;_x000D_
    }_x000D_
    /* Optional: Makes the sample page fill the window. */_x000D_
    html,_x000D_
    body {_x000D_
      height: 100%;_x000D_
      margin: 0;_x000D_
      padding: 0;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="map"></div>_x000D_
    <script src="https://canvg.github.io/canvg/canvg.js"></script>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
    <script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap"></script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Interop type cannot be embedded

Like Jan It took me a while to get it .. =S So for anyone else who's blinded with frustration.

  • Right click the offending assembly that you added in the solution explorer under your project References. (In my case WIA)
  • Click properties.
  • And there should be the option there for Embed Interop Assembly.
  • Set it to False

Vue 2 - Mutating props vue-warn

Props down, events up. That's Vue's Pattern. The point is that if you try to mutate props passing from a parent. It won't work and it just gets overwritten repeatedly by the parent component. Child component can only emit an event to notify parent component to do sth. If you don't like these restrict, you can use VUEX(actually this pattern will suck in complex components structure, you should use VUEX!)

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Some special characters give this type of error, so use

$query="INSERT INTO `tablename` (`name`, `email`)
VALUES
('$_POST[name]','$_POST[email]')";

How do I add a library (android-support-v7-appcompat) in IntelliJ IDEA

Using Gradle

If you are using Gradle, you can add it as a compile dependency.

Instructions

  1. Make sure you have the Android Support Repository SDK package installed. Android Studio automatically recognizes this repository during the build process (not sure about plain IntelliJ).

    Android Support Repository

  2. Add the dependency to {project}/build.gradle

    dependencies {
        compile 'com.android.support:appcompat-v7:+'
    }
    
  3. Click the Sync Project with Gradle Files button.

EDIT: Looks like these same instructions are on the documentation under Adding libraries with resources -> Using Android Studio.

How can I get a resource "Folder" from inside my jar File?

The following code returns the wanted "folder" as Path regardless of if it is inside a jar or not.

  private Path getFolderPath() throws URISyntaxException, IOException {
    URI uri = getClass().getClassLoader().getResource("folder").toURI();
    if ("jar".equals(uri.getScheme())) {
      FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap(), null);
      return fileSystem.getPath("path/to/folder/inside/jar");
    } else {
      return Paths.get(uri);
    }
  }

Requires java 7+.

Check whether an array is empty

function empty() does not work for testing empty arrays! example:

$a=array("","");
if(empty($a)) echo "empty";
else echo "not empty"; //this case is true

a function is necessary:

function is_array_empty($a){
foreach($a as $elm)
if(!empty($elm)) return false;
return true;
}

ok, this is a very old question :) , but i found this thread searching for a solution and i didnt find a good one.

bye (sorry for my english)

Working with dictionaries/lists in R

I'll just comment you can get a lot of mileage out of table when trying to "fake" a dictionary also, e.g.

> x <- c("a","a","b","b","b","c")
> (t <- table(x))
x
a b c 
2 3 1 
> names(t)
[1] "a" "b" "c"
> o <- order(as.numeric(t))
> names(t[o])
[1] "c" "a" "b"

etc.

Including non-Python files with setup.py

I just wanted to follow up on something I found working with Python 2.7 on Centos 6. Adding the package_data or data_files as mentioned above did not work for me. I added a MANIFEST.IN with the files I wanted which put the non-python files into the tarball, but did not install them on the target machine via RPM.

In the end, I was able to get the files into my solution using the "options" in the setup/setuptools. The option files let you modify various sections of the spec file from setup.py. As follows.

from setuptools import setup


setup(
    name='theProjectName',
    version='1',
    packages=['thePackage'],
    url='',
    license='',
    author='me',
    author_email='[email protected]',
    description='',
    options={'bdist_rpm': {'install_script': 'filewithinstallcommands'}},
)

file - MANIFEST.in:

include license.txt

file - filewithinstallcommands:

mkdir -p $RPM_BUILD_ROOT/pathtoinstall/
#this line installs your python files
python setup.py install -O1 --root=$RPM_BUILD_ROOT --record=INSTALLED_FILES
#install license.txt into /pathtoinstall folder
install -m 700 license.txt $RPM_BUILD_ROOT/pathtoinstall/
echo /pathtoinstall/license.txt >> INSTALLED_FILES

How do I start my app on startup?

Additionally you can use an app like AutoStart if you dont want to modify the code, to launch an android application at startup: AutoStart - No root

Detach (move) subdirectory into separate Git repository

I'm sure git subtree is all fine and wonderful, but my subdirectories of git managed code that I wanted to move was all in eclipse. So if you're using egit, it's painfully easy. Take the project you want to move and team->disconnect it, and then team->share it to the new location. It will default to trying to use the old repo location, but you can uncheck the use-existing selection and pick the new place to move it. All hail egit.

How to merge two files line by line in Bash

You can use paste:

paste file1.txt file2.txt > fileresults.txt

Error type 3 Error: Activity class {} does not exist

For me, I tried most of the answers, and didn't work. My Android Studio version is 4.0.1. I changed my git branch to the master branch, and then returned to my own branch, and it worked. This time I could run my branch. So weird I know

show loading icon until the page is load?

HTML

<body>
    <div id="load"></div>
    <div id="contents">
          jlkjjlkjlkjlkjlklk
    </div>
</body>

JS

document.onreadystatechange = function () {
  var state = document.readyState
  if (state == 'interactive') {
       document.getElementById('contents').style.visibility="hidden";
  } else if (state == 'complete') {
      setTimeout(function(){
         document.getElementById('interactive');
         document.getElementById('load').style.visibility="hidden";
         document.getElementById('contents').style.visibility="visible";
      },1000);
  }
}

CSS

#load{
    width:100%;
    height:100%;
    position:fixed;
    z-index:9999;
    background:url("https://www.creditmutuel.fr/cmne/fr/banques/webservices/nswr/images/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}

Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.

DEMO

http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)

update

http://jsfiddle.net/d9ngT/

How to find all occurrences of a substring?

Come, let us recurse together.

def locations_of_substring(string, substring):
    """Return a list of locations of a substring."""

    substring_length = len(substring)    
    def recurse(locations_found, start):
        location = string.find(substring, start)
        if location != -1:
            return recurse(locations_found + [location], location+substring_length)
        else:
            return locations_found

    return recurse([], 0)

print(locations_of_substring('this is a test for finding this and this', 'this'))
# prints [0, 27, 36]

No need for regular expressions this way.

How do I force a vertical scrollbar to appear?

html { overflow-y: scroll; }

This css rule causes a vertical scrollbar to always appear.

Source: http://css-tricks.com/snippets/css/force-vertical-scrollbar/

how to clear JTable

This is the fastest and easiest way that I have found;

while (tableModel.getRowCount()>0)
          {
             tableModel.removeRow(0);
          }

This clears the table lickety split and leaves it ready for new data.

Uncaught SyntaxError: Unexpected token with JSON.parse

Hopefully this helps someone else.

My issue was that I had commented HTML in a PHP callback function via AJAX that was parsing the comments and return invalid JSON.

Once I removed the commented HTML, all was good and the JSON was parsed with no issues.

Updating state on props change in React Form

componentWillReceiveProps is depcricated since react 16: use getDerivedStateFromProps instead

If I understand correctly, you have a parent component that is passing start_time down to the ModalBody component which assigns it to its own state? And you want to update that time from the parent, not a child component.

React has some tips on dealing with this scenario. (Note, this is an old article that has since been removed from the web. Here's a link to the current doc on component props).

Using props to generate state in getInitialState often leads to duplication of "source of truth", i.e. where the real data is. This is because getInitialState is only invoked when the component is first created.

Whenever possible, compute values on-the-fly to ensure that they don't get out of sync later on and cause maintenance trouble.

Basically, whenever you assign parent's props to a child's state the render method isn't always called on prop update. You have to invoke it manually, using the componentWillReceiveProps method.

componentWillReceiveProps(nextProps) {
  // You don't have to do this check first, but it can help prevent an unneeded render
  if (nextProps.startTime !== this.state.startTime) {
    this.setState({ startTime: nextProps.startTime });
  }
}

Get Maven artifact version at runtime

I know it's a very late answer but I'd like to share what I did as per this link:

I added the below code to the pom.xml:

        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <executions>
                <execution>
                    <id>build-info</id>
                    <goals>
                        <goal>build-info</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

And this Advice Controller in order to get the version as model attribute:

import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.info.BuildProperties;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;

@ControllerAdvice
public class CommonControllerAdvice
{
       @Autowired
       BuildProperties buildProperties;
    
       @ModelAttribute("version")
       public String getVersion() throws IOException
       {
          String version = buildProperties.getVersion();
          return version;
       }
    }

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

See String.replaceAll.

Use the regex "\s" and replace with " ".

Then use String.trim.

<Django object > is not JSON serializable

From version 1.9 Easier and official way of getting json

from django.http import JsonResponse
from django.forms.models import model_to_dict


return JsonResponse(  model_to_dict(modelinstance) )

Returning value that was passed into a method

You can use a lambda with an input parameter, like so:

.Returns((string myval) => { return myval; });

Or slightly more readable:

.Returns<string>(x => x);

SVN undo delete before commit

What worked for me is

svn revert --depth infinity deletedDir

How to add style from code behind?

You can't.

So just don't apply styles directly like that, and apply a class "foo", and then define that in your CSS specification:

a.foo { color : orange; }
a.foo:hover { font-weight : bold; }

Graphviz: How to go from .dot to a graph?

You can also output your file in xdot format, then render it in a browser using canviz, a JavaScript library.

Canviz on code.google.com:

To see an example, there is a "Canviz Demo" link on the page above as of November 2, 2014.

Interface vs Base class

Use your own judgement and be smart. Don't always do what others (like me) are saying. You will hear "prefer interfaces to abstract classes" but it really depends. It depends what the class is.

In the above mentioned case where we have a hierarchy of objects, interface is a good idea. Interface helps to work with collections of these objects and it also helps when implementing a service working with any object of the hierarchy. You just define a contract for working with objects from the hierarchy.

On the other hand when you implement a bunch of services that share a common functionality you can either separate the common functionality into a complete separate class or you can move it up into a common base class and make it abstract so that nobody can instantiate the base class.

Also consider this how to support your abstractions over time. Interfaces are fixed: You release an interface as a contract for a set of functionality that any type can implement. Base classes can be extended over time. Those extensions become part of every derived class.

How to check if a map contains a key in Go?

better way here

if _, ok := dict["foo"]; ok {
    //do something here
}

Use a list of values to select rows from a pandas dataframe

You can use isin method:

In [1]: df = pd.DataFrame({'A': [5,6,3,4], 'B': [1,2,3,5]})

In [2]: df
Out[2]:
   A  B
0  5  1
1  6  2
2  3  3
3  4  5

In [3]: df[df['A'].isin([3, 6])]
Out[3]:
   A  B
1  6  2
2  3  3

And to get the opposite use ~:

In [4]: df[~df['A'].isin([3, 6])]
Out[4]:
   A  B
0  5  1
3  4  5

Rails Active Record find(:all, :order => ) issue

I am using rails 6 and Model.all(:order 'columnName DESC') is not working. I have found the correct answer in OrderInRails

This is very simple.

@variable=Model.order('columnName DESC')

Rotate label text in seaborn factorplot

I had a problem with the answer by @mwaskorn, namely that

g.set_xticklabels(rotation=30)

fails, because this also requires the labels. A bit easier than the answer by @Aman is to just add

plt.xticks(rotation=45)

How to know if a DateTime is between a DateRange in C#

I’ve found the following library to be the most helpful when doing any kind of date math. I’m still amazed nothing like this is part of the .Net framework.

http://www.codeproject.com/Articles/168662/Time-Period-Library-for-NET

How to use a parameter in ExecStart command line?

To attempt command line arguments directly is not possible.

One alternative might be environment variables (https://superuser.com/questions/728951/systemd-giving-my-service-multiple-arguments).

This is where I found the answer: http://www.freedesktop.org/software/systemd/man/systemctl.html

so sudo systemctl restart myprog -v -- systemctl will think you're trying to set one of its flags, not myprog's flag.

sudo systemctl restart myprog someotheroption -- systemctl will restart myprog and the someotheroption service, if it exists.

Setting environment variable in react-native?

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

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

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

        import * as base from "./pagebase";

        base.BASE_URL
        base.API_KEY

What is the difference between GitHub and gist?

GISTS The Gist is an outstanding service provided by GitHub. Using this service, you can share your work publically or privately. You can share a single file, articles, full applications or source code etc.

The GitHub is much more than just Gists. It provides immense services to group together a project or programs digital resources in a centralized location called repository and share among stakeholder. The GitHub repository will hold or maintain the multiple version of the files or history of changes and you can retrieve a specific version of a file when you want. Whereas gist will create each post as a new repository and will maintain the history of the file.

adb command not found

Is adb installed? To check, run the following command in Terminal:

~/Library/Android/sdk/platform-tools/adb

If that prints output, skip these following install steps and go straight to the final Terminal command I list:

  1. Launch Android Studio
  2. Launch SDK Manager via Tools -> Android -> SDK Manager
  3. Check Android SDK Platform-Tools

Run the following command on your Mac and restart your Terminal session:

echo export "PATH=~/Library/Android/sdk/platform-tools:$PATH" >> ~/.bash_profile

Note: If you've switched to zsh, the above command should use .zshenv rather than .bash_profile

Nginx serves .php files as downloads, instead of executing them

My solution was to add

    location ~ \.php$ {
    try_files $uri =404;
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;

to my custom configuration file, for example etc/nginx/sites-available/example.com.conf

Adding to /etc/nginx/sites-available/default didn't work for me.

What causes signal 'SIGILL'?

Make sure that all functions with non-void return type have a return statement.

While some compilers automatically provide a default return value, others will send a SIGILL or SIGTRAP at runtime when trying to leave a function without a return value.

How can I switch my git repository to a particular commit

If you want to throw the latest four commits away, use:

git reset --hard HEAD^^^^

Alternatively, you can specify the hash of a commit you want to reset to:

git reset --hard 6e559cb

How do you convert a time.struct_time object into a datetime object?

Like this:

>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)

How can I call a function using a function pointer?

The best way to read that is the clockwise/spiral rule by David Anderson.

Difference between "enqueue" and "dequeue"

These are terms usually used when describing a "FIFO" queue, that is "first in, first out". This works like a line. You decide to go to the movies. There is a long line to buy tickets, you decide to get into the queue to buy tickets, that is "Enqueue". at some point you are at the front of the line, and you get to buy a ticket, at which point you leave the line, that is "Dequeue".

Correct owner/group/permissions for Apache 2 site files/folders under Mac OS X?

Open up terminal first and then go to directory of web server

cd /Library/WebServer/Documents

and then type this and what you will do is you will give read and write permission

sudo chmod -R o+w /Library/WebServer/Documents

This will surely work!

How to filter by IP address in Wireshark?

Actually for some reason wireshark uses two different kind of filter syntax one on display filter and other on capture filter. Display filter is only useful to find certain traffic just for display purpose only. its like you are interested in all trafic but for now you just want to see specific.

but if you are interested only in certian traffic and does not care about other at all then you use the capture filter.

The Syntax for display filter is (as mentioned earlier)

ip.addr = x.x.x.x or ip.src = x.x.x.x or ip.dst = x.x.x.x

but above syntax won't work in capture filters, following are the filters

host x.x.x.x

see more example on wireshark wiki page

Converting a String array into an int Array in java

private void processLine(String[] strings) {
    Integer[] intarray=new Integer[strings.length];
    for(int i=0;i<strings.length;i++) {
        intarray[i]=Integer.parseInt(strings[i]);
    }
    for(Integer temp:intarray) {
        System.out.println("convert int array from String"+temp);
    }
}

"unmappable character for encoding" warning in Java

If you use eclipse (Eclipse can put utf8 code for you even you write utf8 character. You will see normal utf8 character when you programming but background will be utf8 code) ;

  1. Select Project
  2. Right click and select Properties
  3. Select Resource on Resource Panel(Top of right menu which opened after 2.)
  4. You can see in Resource Panel, Text File Encoding, select other which you want

P.S : this will ok if you static value in code. For Example String test = "IIIIIiiiiiiççççç";

No provider for TemplateRef! (NgIf ->TemplateRef)

You missed the * in front of NgIf (like we all have, dozens of times):

<div *ngIf="answer.accepted">&#10004;</div>

Without the *, Angular sees that the ngIf directive is being applied to the div element, but since there is no * or <template> tag, it is unable to locate a template, hence the error.


If you get this error with Angular v5:

Error: StaticInjectorError[TemplateRef]:
  StaticInjectorError[TemplateRef]:
    NullInjectorError: No provider for TemplateRef!

You may have <template>...</template> in one or more of your component templates. Change/update the tag to <ng-template>...</ng-template>.

Run react-native on android emulator

Try

  • brew cask install android-platform-tools
  • adb reverse tcp:9090 tcp:9090
  • run the app

Automapper missing type map configuration or unsupported mapping - Error

Where have you specified the mapping code (CreateMap)? Reference: Where do I configure AutoMapper?

If you're using the static Mapper method, configuration should only happen once per AppDomain. That means the best place to put the configuration code is in application startup, such as the Global.asax file for ASP.NET applications.

If the configuration isn't registered before calling the Map method, you will receive Missing type map configuration or unsupported mapping.

"Active Directory Users and Computers" MMC snap-in for Windows 7?

As @CraigHyatt mentioned in one of the comments:

"Control Panel -> Programs and Features -> Turn Windows features on or off -> Remote Server Administration Tools -> AD DS and AD LDS Tools"

This worked like a charm in Windows Server 2008. A reboot was necessary, but the Active Directory Users and Computers snap in was available after that.

PHP Multidimensional Array Searching (Find key by specific value)

Use this function:

function searchThroughArray($search,array $lists){
        try{
            foreach ($lists as $key => $value) {
                if(is_array($value)){
                    array_walk_recursive($value, function($v, $k) use($search ,$key,$value,&$val){
                        if(strpos($v, $search) !== false )  $val[$key]=$value;
                    });
            }else{
                    if(strpos($value, $search) !== false )  $val[$key]=$value;
                }

            }
            return $val;

        }catch (Exception $e) {
            return false;
        }
    }

and call function.

print_r(searchThroughArray('breville-one-touch-tea-maker-BTM800XL',$products));

How to test which port MySQL is running on and whether it can be connected to?

To find a listener on a port, do this:

netstat -tln

You should see a line that looks like this if mysql is indeed listening on that port.

tcp        0      0 127.0.0.1:3306              0.0.0.0:*                   LISTEN      

Port 3306 is MySql's default port.

To connect, you just have to use whatever client you require, such as the basic mysql client.

mysql -h localhost -u user database

Or a url that is interpreted by your library code.

PHP Regex to get youtube video ID?

fixed based on How to validate youtube video ids?

<?php

$links = [
    "youtube.com/v/tFad5gHoBjY",
    "youtube.com/vi/tFad5gHoBjY",
    "youtube.com/?v=tFad5gHoBjY",
    "youtube.com/?vi=tFad5gHoBjY",
    "youtube.com/watch?v=tFad5gHoBjY",
    "youtube.com/watch?vi=tFad5gHoBjY",
    "youtu.be/tFad5gHoBjY",
    "http://youtu.be/qokEYBNWA_0?t=30m26s",
    "youtube.com/v/vidid",
    "youtube.com/vi/vidid",
    "youtube.com/?v=vidid",
    "youtube.com/?vi=vidid",
    "youtube.com/watch?v=vidid",
    "youtube.com/watch?vi=vidid",
    "youtu.be/vidid",
    "youtube.com/embed/vidid",
    "http://youtube.com/v/vidid",
    "http://www.youtube.com/v/vidid",
    "https://www.youtube.com/v/vidid",
    "youtube.com/watch?v=vidid&wtv=wtv",
    "http://www.youtube.com/watch?dev=inprogress&v=vidid&feature=related",
    "youtube.com/watch?v=7HCZvhRAk-M"
];

foreach($links as $link){
    preg_match("#([\/|\?|&]vi?[\/|=]|youtu\.be\/|embed\/)([a-zA-Z0-9_-]+)#", $link, $matches);
    var_dump(end($matches));
}

Deactivate or remove the scrollbar on HTML

put this code in your html header:

<style type="text/css">
html {
        overflow: auto;
}
</style>

Horizontal list items

A much better way is to use inline-block, because you don't need to use clear:both at the end of your list anymore.

Try this:

<ul>
    <li>
        <a href="#">some item</a>
    </li>
    <li>
        <a href="#">another item</a>
    </li>
</ul>

CSS:

ul > li{
    display:inline-block;
}

Have a look at it here : http://jsfiddle.net/shahverdy/4N6Ap/

Propagate all arguments in a bash shell script

Works fine, except if you have spaces or escaped characters. I don't find the way to capture arguments in this case and send to a ssh inside of script.

This could be useful but is so ugly

_command_opts=$( echo "$@" | awk -F\- 'BEGIN { OFS=" -" } { for (i=2;i<=NF;i++) { gsub(/^[a-z] /,"&@",$i) ; gsub(/ $/,"",$i );gsub (/$/,"@",$i) }; print $0 }' | tr '@' \' )

C++ Array of pointers: delete or delete []?

Your second example is correct; you don't need to delete the monsters array itself, just the individual objects you created.

Counting number of occurrences in column?

=arrayformula(if(isblank(B2:B),iferror(1/0),mmult(sign(B2:B=TRANSPOSE(A2:A)),A2:A)))

I got this from a good tutorial - can't remember the title - probably about using MMult

Pass props in Link react-router

To work off the answer above (https://stackoverflow.com/a/44860918/2011818), you can also send the objects inline the "To" inside the Link object.

<Route path="/foo/:fooId" component={foo} / >

<Link to={{pathname:/foo/newb, sampleParam: "Hello", sampleParam2: "World!" }}> CLICK HERE </Link>

this.props.match.params.fooId //newb
this.props.location.sampleParam //"Hello"
this.props.location.sampleParam2 //"World!"

YouTube iframe embed - full screen

React.JS People, remember allowFullScreen and frameBorder="0"

Without camel-case, react strips these tags out!

How do I put text on ProgressBar?

Just want to point out something on @codingbadger answer. When using "ProgressBarRenderer" you should always check for "ProgressBarRenderer.IsSupported" before using the class. For me, this has been a nightmare with Visual Styles errors in Win7 that I couldn't fix. So, a better approach and workaround for the solution would be:

Rectangle clip = new Rectangle(rect.X, rect.Y, (int)Math.Round(((float)Value / Maximum) * rect.Width), rect.Height);
if (ProgressBarRenderer.IsSupported)
  ProgressBarRenderer.DrawHorizontalChunks(g, clip);
else
  g.FillRectangle(new SolidBrush(this.ForeColor), clip);

Notice that the fill will be a simple rectangle and not chunks. Chunks will be used only if ProgressBarRenderer is supported

ERROR 2003 (HY000): Can't connect to MySQL server on '127.0.0.1' (111)

I was also facing the same issue. The following helped me fix the problem go to control panel-> Administrative tools-->services inside this you will most certainly see the MySQL servce: right click and say start(force start).

ORA-01830: date format picture ends before converting entire input string / Select sum where date query

You can try as follows it works for me

select * from nm_admission where trunc(entry_timestamp) = to_date('09-SEP-2018','DD-MM-YY');

OR

select * from nm_admission where trunc(entry_timestamp) = '09-SEP-2018';

You can also try using to_char but remember to_char is too expensive

select * from nm_admission where to_char(entry_timestamp) = to_date('09-SEP-2018','DD-MM-YY');

The TRUNC(17-SEP-2018 08:30:11) will give 17-SEP-2018 00:00:00 as a result, you can compare the only date portion independently and time portion will skip.

Handling Dialogs in WPF with MVVM

I was pondering a similar problem when asking how the view model for a task or dialog should look like.

My current solution looks like this:

public class SelectionTaskModel<TChoosable> : ViewModel
    where TChoosable : ViewModel
{
    public SelectionTaskModel(ICollection<TChoosable> choices);
    public ReadOnlyCollection<TChoosable> Choices { get; }
    public void Choose(TChoosable choosen);
    public void Abort();
}

When the view model decides that user input is required, it pulls up a instance of SelectionTaskModel with the possible choices for the user. The infrastructure takes care of bringing up the corresponding view, which in proper time will call the Choose() function with the user's choice.

Why am I getting tree conflicts in Subversion?

This can be caused by not using the same version clients all over.

Using a version 1.5 client and a version 1.6 client towards the same repository can create this kind of problem. (I was just bitten myself.)

Markdown to create pages and table of contents?

You can use the [TOC] at the first line and then on the bottom, the only thing you need to do is making sure that the titles are in the same bigger font. The table of content would come out automatically. ( But this only appear in some markdown editors, I didn't try all)

How do you clear the console screen in C?

Using macros you can check if you're on Windows, Linux, Mac or Unix, and call the respective function depending on the current platform. Something as follows:

void clear(){
    #if defined(__linux__) || defined(__unix__) || defined(__APPLE__)
        system("clear");
    #endif

    #if defined(_WIN32) || defined(_WIN64)
        system("cls");
    #endif
}

How to get a view table query (code) in SQL Server 2008 Management Studio

right-click the view in the object-explorer, select "script view as...", then "create to" and then "new query editor window"

Comparing chars in Java

One way to do it using a List<Character> constructed using overloaded convenience factory methods in is as :

if(List.of('A','B','C','D','E').contains(symbol) {
    // do something
}

How to autosize and right-align GridViewColumn data in WPF?

I have created the following class and used across the application wherever required in place of GridView:

/// <summary>
/// Represents a view mode that displays data items in columns for a System.Windows.Controls.ListView control with auto sized columns based on the column content     
/// </summary>
public class AutoSizedGridView : GridView
{        
    protected override void PrepareItem(ListViewItem item)
    {
        foreach (GridViewColumn column in Columns)
        {
            // Setting NaN for the column width automatically determines the required
            // width enough to hold the content completely.

            // If the width is NaN, first set it to ActualWidth temporarily.
            if (double.IsNaN(column.Width))
              column.Width = column.ActualWidth;

            // Finally, set the column with to NaN. This raises the property change
            // event and re computes the width.
            column.Width = double.NaN;              
        }            
        base.PrepareItem(item);
    }
}

Most efficient method to groupby on an array of objects

Without mutations:

const groupBy = (xs, key) => xs.reduce((acc, x) => Object.assign({}, acc, {
  [x[key]]: (acc[x[key]] || []).concat(x)
}), {})

console.log(groupBy(['one', 'two', 'three'], 'length'));
// => {3: ["one", "two"], 5: ["three"]}

How do I return a char array from a function?

A char array is returned by char*, but the function you wrote does not work because you are returning an automatic variable that disappears when the function exits.

Use something like this:

char *testfunc() {
    char* arr = malloc(100);
    strcpy(arr,"xxxx");
    return arr;
}

This is of course if you are returning an array in the C sense, not an std:: or boost:: or something else.

As noted in the comment section: remember to free the memory from the caller.

How to get calendar Quarter from a date in TSQL

declare @TempTable table([Date] datetime)

insert into @TempTable([Date])
values('2008-01-02'),('2007-08-21')
                      
select datepart(year, [Date]) as [year]
,convert(varchar(10),datepart(year, [Date])) + '-Q' + convert(varchar(3),datename(quarter, [Date])) as quarter_with_year
,datefromparts(datepart(year, [Date]),(convert(varchar(3),datename(quarter, [Date])) * 3)-2,1) as quarter_startdate
,eomonth(datefromparts(datepart(year, [Date]),convert(varchar(3),datename(quarter, [Date])) * 3,1)) as quarter_enddate
FROM @TempTable

This returns the year,quarter, and start end date of quarter.

How to get first and last day of week in Oracle?

First day of week (Monday):

SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)-1 first_day_week FROM dual;

Last day of week (Sunday):

SELECT TO_DATE(to_char(sysdate,'YYYY')||'0101','YYYYMMDD') + 7 * to_number(to_char(sysdate,'WW')-1)+5 last_day_week FROM dual;

Substituting your date or date field in these formulas will work for you!

Drop data frame columns by name

list(NULL) also works:

dat <- mtcars
colnames(dat)
# [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"
# [11] "carb"
dat[,c("mpg","cyl","wt")] <- list(NULL)
colnames(dat)
# [1] "disp" "hp"   "drat" "qsec" "vs"   "am"   "gear" "carb"

How to mute an html5 video player using jQuery

$("video").prop('muted', true); //mute

AND

$("video").prop('muted', false); //unmute

See all events here

(side note: use attr if in jQuery < 1.6)

How do I cancel form submission in submit button onclick event?

You are better off doing...

<form onsubmit="return isValidForm()" />

If isValidForm() returns false, then your form doesn't submit.

You should also probably move your event handler from inline.

document.getElementById('my-form').onsubmit = function() {
    return isValidForm();
};

Which Java library provides base64 encoding/decoding?

Within Apache Commons, commons-codec-1.7.jar contains a Base64 class which can be used to encode.

Via Maven:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>20041127.091804</version>
</dependency>

Direct Download

How to print pandas DataFrame without index

Similar to many of the answers above that use df.to_string(index=False), I often find it necessary to extract a single column of values in which case you can specify an individual column with .to_string using the following:

data = pd.DataFrame({'col1': np.random.randint(0, 100, 10), 
    'col2': np.random.randint(50, 100, 10), 
    'col3': np.random.randint(10, 10000, 10)})

print(data.to_string(columns=['col1'], index=False)

print(data.to_string(columns=['col1', 'col2'], index=False))

Which provides an easy to copy (and index free) output for use pasting elsewhere (Excel). Sample output:

col1  col2    
49    62    
97    97    
87    94    
85    61    
18    55

Switch in Laravel 5 - Blade

Updated 2020 Answer

Since Laravel 5.5 the @switch is built into the Blade. Use it as shown below.

@switch($login_error)
    @case(1)
        <span> `E-mail` input is empty!</span>
        @break

    @case(2)
        <span>`Password` input is empty!</span>
        @break

    @default
        <span>Something went wrong, please try again</span>
@endswitch

Older Answer

Unfortunately Laravel Blade does not have switch statement. You can use Laravel if else approach or use use plain PHP switch. You can use plain PHP in blade templates like in any other PHP application. Starting from Laravel 5.2 and up use @php statement.

Option 1:

@if ($login_error == 1)
    `E-mail` input is empty!
@elseif ($login_error == 2)
    `Password` input is empty!
@endif

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Of course:

curl http://example.com:11740
curl https://example.com:11740

Port 80 and 443 are just default port numbers.

The import javax.persistence cannot be resolved

hibernate-distribution-3.6.10.Final\lib\jpa : Add this jar to solve the issue. It is present in lib folder inside that you have a folder called jpa ---> inside that you have hibernate-jpa-2.0-1.0.1.Final jar

How to check if any flags of a flag combination are set?

You can use this extension method on enum, for any type of enums:

public static bool IsSingle(this Enum value)
{
    var items = Enum.GetValues(value.GetType());
    var counter = 0;
    foreach (var item in items)
    {
        if (value.HasFlag((Enum)item))
        {
            counter++;
        }
        if (counter > 1)
        {
            return false;
        }
    }
    return true;
}

sql insert into table with select case values

You have the alias inside of the case, it needs to be outside of the END:

Insert into TblStuff (FullName,Address,City,Zip)
Select
  Case
    When Middle is Null 
    Then Fname + LName
    Else Fname +' ' + Middle + ' '+ Lname
  End as FullName,
  Case
    When Address2 is Null Then Address1
    else Address1 +', ' + Address2 
  End as  Address,
  City as City,
  Zip as Zip
from tblImport

How do I authenticate a WebClient request?

What kind of authentication are you using? If it's Forms authentication, then at best, you'll have to find the .ASPXAUTH cookie and pass it in the WebClient request.

At worst, it won't work.

How to check if a Constraint exists in Sql server?

INFORMATION_SCHEMA is your friend. It has all kinds of views that show all kinds of schema information. Check your system views. You will find you have three views dealing with constraints, one being CHECK_CONSTRAINTS.

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

Not best answer but you can reuse an already created ca bundle using --cert option of pip, for instance:

pip install SQLAlchemy==1.1.15 --cert="C:\Users\myUser\certificates\my_ca-bundle.crt"

How do I get the object if it exists, or None if it does not exist?

Handling exceptions at different points in your views could really be cumbersome..What about defining a custom Model Manager, in the models.py file, like

class ContentManager(model.Manager):
    def get_nicely(self, **kwargs):
        try:
            return self.get(kwargs)
        except(KeyError, Content.DoesNotExist):
            return None

and then including it in the content Model class

class Content(model.Model):
    ...
    objects = ContentManager()

In this way it can be easily dealt in the views i.e.

post = Content.objects.get_nicely(pk = 1)
if post:
    # Do something
else:
    # This post doesn't exist

How to add chmod permissions to file in Git?

Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644 or 755 (spelled (100644 and 100755; the 100 part means "regular file"):

diff --git a/path b/path
new file mode 100644

The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask setting, which would normally be 022 to remove write permission from "group" and "other", or 002 to remove write permission only from "other". It might also be 077 if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".


1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664 in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.

The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.

Force table column widths to always be fixed regardless of contents

Try looking into the following CSS:

word-wrap:break-word;

Web browsers should not break-up "words" by default so what you are experiencing is normal behaviour of a browser. However you can override this with the word-wrap CSS directive.

You would need to set a width on the overall table then a width on the columns. "width:100%;" should also be OK depending on your requirements.

Using word-wrap may not be what you want however it is useful for showing all of the data without deforming the layout.

Can't connect to Postgresql on port 5432

Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf and postgres.conf files I finally found out that my firewall was overriding everything and therefore blocking connections

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

List last updated on December 1, 2020:

As of November 30, 2020, AWS now has EC2 Mac instances:

We previously used and had good experiences with:

Here are some other sites that I am aware of:

When we were with MacStadium, we loved them. We had great connectivity/uptime. When I've needed hands-on support to plug in a Time Machine backup, they've been great. They performed a seamless upgrade to better hardware for us over one weekend (when we could afford a bit of downtime), and that went off without a hitch. Highly recommended. (Not affiliated - just happy).

In April of 2020, we stopped using MacStadium, simply because we no longer needed a Mac server. If I need another Mac host, I would be happy to go back to them.

How to create a DataFrame of random integers with Pandas?

numpy.random.randint accepts a third argument (size) , in which you can specify the size of the output array. You can use this to create your DataFrame -

df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

Here - np.random.randint(0,100,size=(100, 4)) - creates an output array of size (100,4) with random integer elements between [0,100) .


Demo -

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

which produces:

     A   B   C   D
0   45  88  44  92
1   62  34   2  86
2   85  65  11  31
3   74  43  42  56
4   90  38  34  93
5    0  94  45  10
6   58  23  23  60
..  ..  ..  ..  ..

How to pass credentials to the Send-MailMessage command for sending emails

in addition to UseSsl, you have to include smtp port 587 to make it work.

Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

ActiveX component can't create object

I had this problem too. I was trying to run an old 32-bit dll in a 64 bit system. I got it working by copying the .dll to the C:\Windows\SysWoW64\ directory and running this:

%systemroot%\SysWoW64\regsvr32 "C:\Windows\SysWoW64\thenameofyourdll.dll"

And also enabling IIS to run 32 bit apps

How to get a list of programs running with nohup

When I started with $ nohup storm dev-zookeper ,

METHOD1 : using jobs,

prayagupd@prayagupd:/home/vmfest# jobs -l
[1]+ 11129 Running                 nohup ~/bin/storm/bin/storm dev-zookeeper &

METHOD2 : using ps command.

$ ps xw
PID  TTY      STAT   TIME COMMAND
1031 tty1     Ss+    0:00 /sbin/getty -8 38400 tty1
10582 ?        S      0:01 [kworker/0:0]
10826 ?        Sl     0:18 java -server -Dstorm.options= -Dstorm.home=/root/bin/storm -Djava.library.path=/usr/local/lib:/opt/local/lib:/usr/lib -Dsto
10853 ?        Ss     0:00 sshd: vmfest [priv] 

TTY column with ? => nohup running programs.

Description

  • TTY column = the terminal associated with the process
  • STAT column = state of a process
    • S = interruptible sleep (waiting for an event to complete)
    • l = is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)

Reference

$ man ps # then search /PROCESS STATE CODES

Equivalent of LIMIT for DB2

Theres these available options:-

DB2 has several strategies to cope with this problem.
You can use the "scrollable cursor" in feature.
In this case you can open a cursor and, instead of re-issuing a query you can FETCH forward and backward.
This works great if your application can hold state since it doesn't require DB2 to rerun the query every time.
You can use the ROW_NUMBER() OLAP function to number rows and then return the subset you want.
This is ANSI SQL 
You can use the ROWNUM pseudo columns which does the same as ROW_NUMBER() but is suitable if you have Oracle skills.
You can use LIMIT and OFFSET if you are more leaning to a mySQL or PostgreSQL dialect.  

How to read line by line or a whole text file at once?

Well, to do this one can also use the freopen function provided in C++ - http://www.cplusplus.com/reference/cstdio/freopen/ and read the file line by line as follows -:

#include<cstdio>
#include<iostream>

using namespace std;

int main(){
   freopen("path to file", "rb", stdin);
   string line;
   while(getline(cin, line))
       cout << line << endl;
   return 0;
}

Set the table column width constant regardless of the amount of text in its cells?

If you need one ore more fixed-width columns while other columns should resize, try setting both min-width and max-width to the same value.

What does "export default" do in JSX?

Simplest Understanding for default export is

Export is ES6's feature which is used to Export a module(file) and use it in some other module(file).

Default Export:

  1. default export is the convention if you want to export only one object(variable, function, class) from the file(module).
  2. There could be only one default export per file, but not restricted to only one export.
  3. When importing default exported object we can rename it as well.

Export or Named Export:

  1. It is used to export the object(variable, function, calss) with the same name.

  2. It is used to export multiple objects from one file.

  3. It cannot be renamed when importing in another file, it must have the same name that was used to export it, but we can create its alias by using as operator.

In React, Vue and many other frameworks the Export is mostly used to export reusable components to make modular based applications.

Remove xticks in a matplotlib plot?

Here is an alternative solution that I found on the matplotlib mailing list:

import matplotlib.pylab as plt

x = range(1000)
ax = plt.axes()
ax.semilogx(x, x)
ax.xaxis.set_ticks_position('none') 

graph

How to adjust gutter in Bootstrap 3 grid system?

(Posted on behalf of the OP).

I believe I figured it out.

In my case, I added [class*="col-"] {padding: 0 7.5px;};.

Then added .row {margin: 0 -7.5px;}.

This works pretty well, except there is 1px margin on both sides. So I just make .row {margin: 0 -7.5px;} to .row {margin: 0 -8.5px;}, then it works perfectly.

I have no idea why there is a 1px margin. Maybe someone can explain it?

See the sample I created:

Demo
Code

Can I create a One-Time-Use Function in a Script or Stored Procedure?

You can create temp stored procedures like:

create procedure #mytemp as
begin
   select getdate() into #mytemptable;
end

in an SQL script, but not functions. You could have the proc store it's result in a temp table though, then use that information later in the script ..

malloc for struct and pointer in C

Few points

struct Vector y = (struct Vector*)malloc(sizeof(struct Vector)); is wrong

it should be struct Vector *y = (struct Vector*)malloc(sizeof(struct Vector)); since y holds pointer to struct Vector.

1st malloc() only allocates memory enough to hold Vector structure (which is pointer to double + int)

2nd malloc() actually allocate memory to hold 10 double.

Formula to check if string is empty in Crystal Reports

if {le_gur_bond.gur1}="" or IsNull({le_gur_bond.gur1})   Then
    ""
else 
 "and " + {le_gur_bond.gur2} + " of "+ {le_gur_bond.grr_2_address2}

How do you make a div follow as you scroll?

The post is old but I found a perfect CSS for the purpose and I want to share it.

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

    div.sticky {
        position: -webkit-sticky; /* Safari */
        position: sticky;
        top: 0;
        background-color: green;
        border: 2px solid #4CAF50;
    }

Source: https://www.w3schools.com/css/css_positioning.asp

From io.Reader to string in Go

The most efficient way would be to always use []byte instead of string.

In case you need to print data received from the io.ReadCloser, the fmt package can handle []byte, but it isn't efficient because the fmt implementation will internally convert []byte to string. In order to avoid this conversion, you can implement the fmt.Formatter interface for a type like type ByteSlice []byte.

read file in classpath

Try getting Spring to inject it, assuming you're using Spring as a dependency-injection framework.

In your class, do something like this:

public void setSqlResource(Resource sqlResource) {
    this.sqlResource = sqlResource;
}

And then in your application context file, in the bean definition, just set a property:

<bean id="someBean" class="...">
    <property name="sqlResource" value="classpath:com/somecompany/sql/sql.txt" />
</bean>

And Spring should be clever enough to load up the file from the classpath and give it to your bean as a resource.

You could also look into PropertyPlaceholderConfigurer, and store all your SQL in property files and just inject each one separately where needed. There are lots of options.

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

useTimezone is an older workaround. MySQL team rewrote the setTimestamp/getTimestamp code fairly recently, but it will only be enabled if you set the connection parameter useLegacyDatetimeCode=false and you're using the latest version of mysql JDBC connector. So for example:

String url =
 "jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false

If you download the mysql-connector source code and look at setTimestamp, it's very easy to see what's happening:

If use legacy date time code = false, newSetTimestampInternal(...) is called. Then, if the Calendar passed to newSetTimestampInternal is NULL, your date object is formatted in the database's time zone:

this.tsdf = new SimpleDateFormat("''yyyy-MM-dd HH:mm:ss", Locale.US);
this.tsdf.setTimeZone(this.connection.getServerTimezoneTZ());
timestampString = this.tsdf.format(x);

It's very important that Calendar is null - so make sure you're using:

setTimestamp(int,Timestamp).

... NOT setTimestamp(int,Timestamp,Calendar).

It should be obvious now how this works. If you construct a date: January 5, 2011 3:00 AM in America/Los_Angeles (or whatever time zone you want) using java.util.Calendar and call setTimestamp(1, myDate), then it will take your date, use SimpleDateFormat to format it in the database time zone. So if your DB is in America/New_York, it will construct the String '2011-01-05 6:00:00' to be inserted (since NY is ahead of LA by 3 hours).

To retrieve the date, use getTimestamp(int) (without the Calendar). Once again it will use the database time zone to build a date.

Note: The webserver time zone is completely irrelevant now! If you don't set useLegacyDatetimecode to false, the webserver time zone is used for formatting - adding lots of confusion.


Note:

It's possible MySQL my complain that the server time zone is ambiguous. For example, if your database is set to use EST, there might be several possible EST time zones in Java, so you can clarify this for mysql-connector by telling it exactly what the database time zone is:

String url =
 "jdbc:mysql://localhost/mydb?useLegacyDatetimeCode=false&serverTimezone=America/New_York";

You only need to do this if it complains.

How to avoid a System.Runtime.InteropServices.COMException?

Your code (or some code called by you) is making a call to a COM method which is returning an unknown value. If you can find that then you're half way there.

You could try breaking when the exception is thrown. Go to Debug > Exceptions... and use the Find... option to locate System.Runtime.InteropServices.COMException. Tick the option to break when it's thrown and then debug your application.

Hopefully it will break somewhere meaningful and you'll be able to trace back and find the source of the error.

In Python, how do I convert all of the items in a list to floats?

I have solve this problem in my program using:

number_input = float("{:.1f}".format(float(input())))
list.append(number_input)

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I've run into the very same issue, when mistakenly named variable with the very same name, as function.

So this:

isLive = isLive(data);

failed, generating OP's mentioned error message.

Fix to this was as simple as changing above line to:

isItALive = isLive(data);

I don't know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.

How exactly to use Notification.Builder

Notification.Builder API 11 or NotificationCompat.Builder API 1

This is a usage example.

Intent notificationIntent = new Intent(ctx, YourClass.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx,
        YOUR_PI_REQ_CODE, notificationIntent,
        PendingIntent.FLAG_CANCEL_CURRENT);

NotificationManager nm = (NotificationManager) ctx
        .getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = ctx.getResources();
Notification.Builder builder = new Notification.Builder(ctx);

builder.setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.some_img)
            .setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.some_big_img))
            .setTicker(res.getString(R.string.your_ticker))
            .setWhen(System.currentTimeMillis())
            .setAutoCancel(true)
            .setContentTitle(res.getString(R.string.your_notif_title))
            .setContentText(res.getString(R.string.your_notif_text));
Notification n = builder.build();

nm.notify(YOUR_NOTIF_ID, n);

How to show particular image as thumbnail while implementing share on Facebook?

My tags were correct but Facebook only scrapes every 24 hours, according to their documentation. Using the Facebook Lint page got the image into Facebook.

Enter your URL here and FB will update the metadata from your page:

https://developers.facebook.com/tools/debug (updated link)

Prevent typing non-numeric in input type number

I just had the same problem and discovered an alternative solution using the validation API - works without black magic in all major browsers (Chrome, Firefox, Safari) except IE. This solution simply prevents users from entering invalid values. I also included a fallback for IE, which is not nice but works at least.

Context: onInput function is called on input events, setInputValue is used to set the value of the input element, previousInputValue contains the last valid input value (updated in setInputValue calls).

    function onInput (event) {
        const inputValue = event.target.value;

        // badInput supported on validation api (except IE)
        // in IE it will be undefined, so we need strict value check
        const badInput = event.target.validity.badInput;

        // simply prevent modifying the value
        if (badInput === true) {
        // it's still possible to enter invalid values in an empty input, so we'll need this trick to prevent that
            if (previousInputValue === '') {
                setInputValue(' ');
                setTimeout(() => {
                    setInputValue('');
                }, 1);
            }
            return;
        }

        if (badInput === false) {
            setInputValue(inputValue);
            return;
        }

        // fallback case for IE and other abominations

        // remove everything from the string expect numbers, point and comma
        // replace comma with points (parseFloat works only with points)
        let stringVal = String(inputValue)
            .replace(/([^0-9.,])/g, '')
            .replace(/,/g, '.');

        // remove all but first point
        const pointIndex = stringVal.indexOf('.');
        if (pointIndex !== -1) {
            const pointAndBefore = stringVal.substring(0, pointIndex + 1);
            const afterPoint = stringVal.substring(pointIndex + 1);

            // removing all points after the first
            stringVal = `${pointAndBefore}${afterPoint.replace(/\./g, '')}`;
        }

        const float = parseFloat(stringVal);
        if (isNaN(float)) {
            // fallback to emptying the input if anything goes south
            setInputValue('');
            return;
        }
        setInputValue(stringVal);
}

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

Filter Linq EXCEPT on properties

Construct a List<AppMeta> from the excluded List and use the Except Linq operator.

var ex = excludedAppIds.Select(x => new AppMeta{Id = x}).ToList();                           
var result = ex.Except(unfilteredApps).ToList();

How can I present a file for download from an MVC controller?

You should look at the File method of the Controller. This is exactly what it's for. It returns a FilePathResult instead of an ActionResult.

Finding longest string in array

A new answer to an old question: in ES6 you can do shorter:

Math.max(...(x.map(el => el.length)));

adb server version doesn't match this client

I experienced a similar problem where my attempts to use adb such as adb logcat provided this error output:

adb server version (40) doesn't match this client (36); killing...

This solution worked for me in 2018 on Ubuntu 18.04 from Android Studio 3.2.1 using terminal.

The commands are as follows:

adb kill-server sudo cp ~/Android/Sdk/platform-tools/adb /usr/bin/adb sudo chmod +x /usr/bin/adb adb start-server

You may need to adjust the cp command arguments based on the path to Android/ on your system.

2nd generation kudos to my source: https://stackoverflow.com/a/40991118/7015599

Can I bind an array to an IN() condition?

You'll have to construct the query-string.

<?php
$ids     = array(1, 2, 3, 7, 8, 9);
$inQuery = implode(',', array_fill(0, count($ids), '?'));

$db = new PDO(...);
$stmt = $db->prepare(
    'SELECT *
     FROM table
     WHERE id IN(' . $inQuery . ')'
);

// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
    $stmt->bindValue(($k+1), $id);

$stmt->execute();
?>

Both chris (comments) and somebodyisintrouble suggested that the foreach-loop ...

(...)
// bindvalue is 1-indexed, so $k+1
foreach ($ids as $k => $id)
    $stmt->bindValue(($k+1), $id);

$stmt->execute();

... might be redundant, so the foreach loop and the $stmt->execute could be replaced by just ...

<?php 
  (...)
  $stmt->execute($ids);

Android ACTION_IMAGE_CAPTURE Intent

It is very simple to solve this problem with Activity Result Code Simple try this method

if (reqCode == RECORD_VIDEO) {
   if(resCode == RESULT_OK) {
       if (uri != null) {
           compress();
       }
    } else if(resCode == RESULT_CANCELED && data!=null){
       Toast.makeText(MainActivity.this,"No Video Recorded",Toast.LENGTH_SHORT).show();
   }
}

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

Combining INSERT INTO and WITH/CTE

The WITH clause for Common Table Expressions go at the top.

Wrapping every insert in a CTE has the benefit of visually segregating the query logic from the column mapping.

Spot the mistake:

WITH _INSERT_ AS (
  SELECT
    [BatchID]      = blah
   ,[APartyNo]     = blahblah
   ,[SourceRowID]  = blahblahblah
  FROM Table1 AS t1
)
INSERT Table2
      ([BatchID], [SourceRowID], [APartyNo])
SELECT [BatchID], [APartyNo], [SourceRowID]   
FROM _INSERT_

Same mistake:

INSERT Table2 (
  [BatchID]
 ,[SourceRowID]
 ,[APartyNo]
)
SELECT
  [BatchID]      = blah
 ,[APartyNo]     = blahblah
 ,[SourceRowID]  = blahblahblah
FROM Table1 AS t1

A few lines of boilerplate make it extremely easy to verify the code inserts the right number of columns in the right order, even with a very large number of columns. Your future self will thank you later.

Find object in list that has attribute equal to some value (that meets any condition)

Since it has not been mentioned just for completion. The good ol' filter to filter your to be filtered elements.

Functional programming ftw.

####### Set Up #######
class X:

    def __init__(self, val):
        self.val = val

elem = 5

my_unfiltered_list = [X(1), X(2), X(3), X(4), X(5), X(5), X(6)]

####### Set Up #######

### Filter one liner ### filter(lambda x: condition(x), some_list)
my_filter_iter = filter(lambda x: x.val == elem, my_unfiltered_list)
### Returns a flippin' iterator at least in Python 3.5 and that's what I'm on

print(next(my_filter_iter).val)
print(next(my_filter_iter).val)
print(next(my_filter_iter).val)

### [1, 2, 3, 4, 5, 5, 6] Will Return: ###
# 5
# 5
# Traceback (most recent call last):
#   File "C:\Users\mousavin\workspace\Scripts\test.py", line 22, in <module>
#     print(next(my_filter_iter).value)
# StopIteration


# You can do that None stuff or whatever at this point, if you don't like exceptions.

I know that generally in python list comprehensions are preferred or at least that is what I read, but I don't see the issue to be honest. Of course Python is not an FP language, but Map / Reduce / Filter are perfectly readable and are the most standard of standard use cases in functional programming.

So there you go. Know thy functional programming.

filter condition list

It won't get any easier than this:

next(filter(lambda x: x.val == value,  my_unfiltered_list)) # Optionally: next(..., None) or some other default value to prevent Exceptions

How to continue a Docker container which has exited

Follow these steps:

  1. Run below command to see that all the container services both running and stopped on. Option -a is given to see that the container stops as well

    docker ps -a
    
  2. Then start the docker container either by container_id or container tag names

    docker start <CONTAINER_ID> or <NAMES>
    

    enter image description here

    Say from the above picture, container id 4b161b302337
    So command to be run is

    docker start 4b161b302337
    
  3. One can verify whether the container is running with

    docker ps
    

How to debug in Django, the good way?

I use PyCharm and stand by it all the way. It cost me a little but I have to say the advantage that I get out of it is priceless. I tried debugging from console and I do give people a lot of credit who can do that, but for me being able to visually debug my application(s) is great.

I have to say though, PyCharm does take a lot of memory. But then again, nothing good is free in life. They just came with their latest version 3. It also plays very well with Django, Flask and Google AppEngine. So, all in all, I'd say it's a great handy tool to have for any developer.

If you are not using it yet, I'd recommend to get the trial version for 30 days to take a look at the power of PyCharm. I'm sure there are other tools also available, such as Aptana. But I guess I just also like the way PyCharm looks. I feel very comfortable debugging my apps there.

Switch statement fallthrough in C#?

You can achieve fall through like c++ by the goto keyword.

EX:

switch(num)
{
   case 1:
      goto case 3;
   case 2:
      goto case 3;
   case 3:
      //do something
      break;
   case 4:
      //do something else
      break;
   case default:
      break;
}

Is there any difference between GROUP BY and DISTINCT

In terms of usage, GROUP BY is used for grouping those rows you want to calculate. DISTINCT will not do any calculation. It will show no duplicate rows.

I always used DISTINCT if I want to present data without duplicates.

If I want to do calculations like summing up the total quantity of mangoes, I will use GROUP BY

Import a file from a subdirectory?

  • Create a subdirectory named lib.
  • Create an empty file named lib\__init__.py.
  • In lib\BoxTime.py, write a function foo() like this:

    def foo():
        print "foo!"
    
  • In your client code in the directory above lib, write:

    from lib import BoxTime
    BoxTime.foo()
    
  • Run your client code. You will get:

    foo!
    

Much later -- in linux, it would look like this:

% cd ~/tmp
% mkdir lib
% touch lib/__init__.py
% cat > lib/BoxTime.py << EOF
heredoc> def foo():
heredoc>     print "foo!"
heredoc> EOF
% tree lib
lib
+-- BoxTime.py
+-- __init__.py

0 directories, 2 files
% python 
Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from lib import BoxTime
>>> BoxTime.foo()
foo!

How to insert a large block of HTML in JavaScript?

If you are using on the same domain then you can create a seperate HTML file and then import this using the code from this answer by @Stano :

https://stackoverflow.com/a/34579496/2468603

How to insert an item into a key/value pair object?

Do you need to look up objects by the key? If not, consider using List<Tuple<string, string>> or List<KeyValuePair<string, string>> if you're not using .NET 4.

C++ String Declaring

C++ supplies a string class that can be used like this:

#include <string>
#include <iostream>

int main() {
    std::string Something = "Some text";
    std::cout << Something << std::endl;
}

What is the list of valid @SuppressWarnings warning names in Java?

JSL 1.7

The Oracle documentation mentions:

  • unchecked: Unchecked warnings are identified by the string "unchecked".
  • deprecation: A Java compiler must produce a deprecation warning when a type, method, field, or constructor whose declaration is annotated with the annotation @Deprecated is used (i.e. overridden, invoked, or referenced by name), unless: [...] The use is within an entity that is annotated to suppress the warning with the annotation @SuppressWarnings("deprecation"); or

It then explains that implementations can add and document their own:

Compiler vendors should document the warning names they support in conjunction with this annotation type. Vendors are encouraged to cooperate to ensure that the same names work across multiple compilers.

Iterator Loop vs index loop

With a vector iterators do no offer any real advantage. The syntax is uglier, longer to type and harder to read.

Iterating over a vector using iterators is not faster and is not safer (actually if the vector is possibly resized during the iteration using iterators will put you in big troubles).

The idea of having a generic loop that works when you will change later the container type is also mostly nonsense in real cases. Unfortunately the dark side of a strictly typed language without serious typing inference (a bit better now with C++11, however) is that you need to say what is the type of everything at each step. If you change your mind later you will still need to go around and change everything. Moreover different containers have very different trade-offs and changing container type is not something that happens that often.

The only case in which iteration should be kept if possible generic is when writing template code, but that (I hope for you) is not the most frequent case.

The only problem present in your explicit index loop is that size returns an unsigned value (a design bug of C++) and comparison between signed and unsigned is dangerous and surprising, so better avoided. If you use a decent compiler with warnings enabled there should be a diagnostic on that.

Note that the solution is not to use an unsiged as the index, because arithmetic between unsigned values is also apparently illogical (it's modulo arithmetic, and x-1 may be bigger than x). You instead should cast the size to an integer before using it. It may make some sense to use unsigned sizes and indexes (paying a LOT of attention to every expression you write) only if you're working on a 16 bit C++ implementation (16 bit was the reason for having unsigned values in sizes).

As a typical mistake that unsigned size may introduce consider:

void drawPolyline(const std::vector<P2d>& points)
{
    for (int i=0; i<points.size()-1; i++)
        drawLine(points[i], points[i+1]);
}

Here the bug is present because if you pass an empty points vector the value points.size()-1 will be a huge positive number, making you looping into a segfault. A working solution could be

for (int i=1; i<points.size(); i++)
    drawLine(points[i - 1], points[i]);

but I personally prefer to always remove unsinged-ness with int(v.size()).

PS: If you really don't want to think by to yourself to the implications and simply want an expert to tell you then consider that a quite a few world recognized C++ experts agree and expressed opinions on that unsigned values are a bad idea except for bit manipulations.

Discovering the ugliness of using iterators in the case of iterating up to second-last is left as an exercise for the reader.

How can I link a photo in a Facebook album to a URL

Unfortunately, no. This feature is not available for facebook albums.

Detecting a mobile browser

I usually find that the simpler approach of checking the visibility of a particular element (say burger icon) that is only visible on mobile views works well and is far safer than relying on a very complicated regex. That would be difficult to test works 100%.

function isHidden(el) {
   return (el.offsetParent === null);
}

Reading a binary file with python

You could use numpy.fromfile, which can read data from both text and binary files. You would first construct a data type, which represents your file format, using numpy.dtype, and then read this type from file using numpy.fromfile.

Difference between FetchType LAZY and EAGER in Java Persistence API?

Basically,

LAZY = fetch when needed
EAGER = fetch immediately

Error renaming a column in MySQL

There is a syntax problem, because the right syntax to alter command is ALTER TABLE tablename CHANGE OldColumnName NewColunmName DATATYPE;

Can I replace groups in Java regex?

Here is a different solution, that also allows the replacement of a single group in multiple matches. It uses stacks to reverse the execution order, so the string operation can be safely executed.

private static void demo () {

    final String sourceString = "hello world!";

    final String regex = "(hello) (world)(!)";
    final Pattern pattern = Pattern.compile(regex);

    String result = replaceTextOfMatchGroup(sourceString, pattern, 2, world -> world.toUpperCase());
    System.out.println(result);  // output: hello WORLD!
}

public static String replaceTextOfMatchGroup(String sourceString, Pattern pattern, int groupToReplace, Function<String,String> replaceStrategy) {
    Stack<Integer> startPositions = new Stack<>();
    Stack<Integer> endPositions = new Stack<>();
    Matcher matcher = pattern.matcher(sourceString);

    while (matcher.find()) {
        startPositions.push(matcher.start(groupToReplace));
        endPositions.push(matcher.end(groupToReplace));
    }
    StringBuilder sb = new StringBuilder(sourceString);
    while (! startPositions.isEmpty()) {
        int start = startPositions.pop();
        int end = endPositions.pop();
        if (start >= 0 && end >= 0) {
            sb.replace(start, end, replaceStrategy.apply(sourceString.substring(start, end)));
        }
    }
    return sb.toString();       
}

Maintain model of scope when changing between views in AngularJS

You can use $locationChangeStart event to store the previous value in $rootScope or in a service. When you come back, just initialize all previously stored values. Here is a quick demo using $rootScope.

enter image description here

_x000D_
_x000D_
var app = angular.module("myApp", ["ngRoute"]);_x000D_
app.controller("tab1Ctrl", function($scope, $rootScope) {_x000D_
    if ($rootScope.savedScopes) {_x000D_
        for (key in $rootScope.savedScopes) {_x000D_
            $scope[key] = $rootScope.savedScopes[key];_x000D_
        }_x000D_
    }_x000D_
    $scope.$on('$locationChangeStart', function(event, next, current) {_x000D_
        $rootScope.savedScopes = {_x000D_
            name: $scope.name,_x000D_
            age: $scope.age_x000D_
        };_x000D_
    });_x000D_
});_x000D_
app.controller("tab2Ctrl", function($scope) {_x000D_
    $scope.language = "English";_x000D_
});_x000D_
app.config(function($routeProvider) {_x000D_
    $routeProvider_x000D_
        .when("/", {_x000D_
            template: "<h2>Tab1 content</h2>Name: <input ng-model='name'/><br/><br/>Age: <input type='number' ng-model='age' /><h4 style='color: red'>Fill the details and click on Tab2</h4>",_x000D_
            controller: "tab1Ctrl"_x000D_
        })_x000D_
        .when("/tab2", {_x000D_
            template: "<h2>Tab2 content</h2> My language: {{language}}<h4 style='color: red'>Now go back to Tab1</h4>",_x000D_
            controller: "tab2Ctrl"_x000D_
        });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"></script>_x000D_
<body ng-app="myApp">_x000D_
    <a href="#/!">Tab1</a>_x000D_
    <a href="#!tab2">Tab2</a>_x000D_
    <div ng-view></div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Emulate Samsung Galaxy Tab

What resolution and density should I set?

  • 1024x600

How can I indicate that this is large screen device?

  • you can't really (not that i know of)

What hardware does this tablet support?

What is max heap size?

  • not sure

Which Android version?

  • 2.2

Hope that helps - check the spec page for all unanswered questions.

Is it possible to return empty in react render function?

Returning falsy value in the render() function will render nothing. So you can just do

 render() {
    let finalClasses = "" + (this.state.classes || "");
    return !isTimeout && <div>{this.props.children}</div>;
  }

shell-script headers (#!/bin/sh vs #!/bin/csh)

This defines what shell (command interpreter) you are using for interpreting/running your script. Each shell is slightly different in the way it interacts with the user and executes scripts (programs).

When you type in a command at the Unix prompt, you are interacting with the shell.

E.g., #!/bin/csh refers to the C-shell, /bin/tcsh the t-shell, /bin/bash the bash shell, etc.

You can tell which interactive shell you are using the

 echo $SHELL

command, or alternatively

 env | grep -i shell

You can change your command shell with the chsh command.

Each has a slightly different command set and way of assigning variables and its own set of programming constructs. For instance the if-else statement with bash looks different that the one in the C-shell.

This page might be of interest as it "translates" between bash and tcsh commands/syntax.

Using the directive in the shell script allows you to run programs using a different shell. For instance I use the tcsh shell interactively, but often run bash scripts using /bin/bash in the script file.

Aside:

This concept extends to other scripts too. For instance if you program in Python you'd put

 #!/usr/bin/python

at the top of your Python program

Get the current user, within an ApiController action, without passing the userID as a parameter

string userName;
string userId;
if (HttpContext.Current != null && HttpContext.Current.User != null 
        && HttpContext.Current.User.Identity.Name != null)
{
    userName = HttpContext.Current.User.Identity.Name;
    userId = HttpContext.Current.User.Identity.GetUserId();
}

Or based on Darrel Miller's comment, maybe use this to retrieve the HttpContext first.

// get httpContext
object httpContext;
actionContext.Request.Properties.TryGetValue("MS_HttpContext", out httpContext);    

See also:

How to access HTTPContext from within your Web API action

Is there a method that tells my program to quit?

In Python 3 there is an exit() function:

elif choice == "q":
    exit()

How to close TCP and UDP ports via windows command line

Yes there is possible to close TCP or UDP port there is a command in DOS

TASKKILL /f /pid 1234 

I hope this will work for You