Programs & Examples On #Updatemodel

Validation failed for one or more entities while saving changes to SQL Server Database using Entity Framework

I have faced same issue a couple of days ago while updating the database. In my case, there was few new non nullable columns added for maintenance which was not supplied in the code which is causing the exception. I figure out those fields and supplied values for them and its resolved.

Get error message if ModelState.IsValid fails?

It is sample extension

public class GetModelErrors
{
    //Usage return Json to View :
    //return Json(new { state = false, message = new GetModelErrors(ModelState).MessagesWithKeys() });
    public class KeyMessages
    {
        public string Key { get; set; }
        public string Message { get; set; }
    }
    private readonly ModelStateDictionary _entry;
    public GetModelErrors(ModelStateDictionary entry)
    {
        _entry = entry;
    }

    public int Count()
    {
        return _entry.ErrorCount;
    }
    public string Exceptions(string sp = "\n")
    {
        return string.Join(sp, _entry.Values
            .SelectMany(v => v.Errors)
            .Select(e => e.Exception));
    }
    public string Messages(string sp = "\n")
    {
        string msg = string.Empty;
        foreach (var item in _entry)
        {
            if (item.Value.ValidationState == ModelValidationState.Invalid)
            {
                msg += string.Join(sp, string.Join(",", item.Value.Errors.Select(i => i.ErrorMessage)));
            }
        }
        return msg;
    }

    public List<KeyMessages> MessagesWithKeys(string sp = "<p> ? ")
    {
        List<KeyMessages> list = new List<KeyMessages>();
        foreach (var item in _entry)
        {
            if (item.Value.ValidationState == ModelValidationState.Invalid)
            {
                list.Add(new KeyMessages
                {
                    Key = item.Key,
                    Message = string.Join(null, item.Value.Errors.Select(i => sp + i.ErrorMessage))
                });
            }
        }
        return list;
    }
}

How to handle checkboxes in ASP.NET MVC forms?

HtmlHelper adds an hidden input to notify the controller about Unchecked status. So to have the correct checked status:

bool bChecked = form[key].Contains("true");

How can I detect whether an iframe is loaded?

You may try this (using jQuery)

_x000D_
_x000D_
$(function(){_x000D_
    $('#MainPopupIframe').load(function(){_x000D_
        $(this).show();_x000D_
        console.log('iframe loaded successfully')_x000D_
    });_x000D_
        _x000D_
    $('#click').on('click', function(){_x000D_
        $('#MainPopupIframe').attr('src', 'https://heera.it');    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Using plain javascript

_x000D_
_x000D_
window.onload=function(){_x000D_
    var ifr=document.getElementById('MainPopupIframe');_x000D_
    ifr.onload=function(){_x000D_
        this.style.display='block';_x000D_
        console.log('laod the iframe')_x000D_
    };_x000D_
    var btn=document.getElementById('click');    _x000D_
    btn.onclick=function(){_x000D_
        ifr.src='https://heera.it';    _x000D_
    };_x000D_
};
_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Also you can try this (dynamic iframe)

_x000D_
_x000D_
$(function(){_x000D_
    $('#click').on('click', function(){_x000D_
        var ifr=$('<iframe/>', {_x000D_
            id:'MainPopupIframe',_x000D_
            src:'https://heera.it',_x000D_
            style:'display:none;width:320px;height:400px',_x000D_
            load:function(){_x000D_
                $(this).show();_x000D_
                alert('iframe loaded !');_x000D_
            }_x000D_
        });_x000D_
        $('body').append(ifr);    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button><br />
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Tick symbol in HTML/XHTML

.className {
   content: '\&#x2713';
}

Using CSS content Property you can show tick with an image or other codesign.

ctypes - Beginner

Here's a quick and dirty ctypes tutorial.

First, write your C library. Here's a simple Hello world example:

testlib.c

#include <stdio.h>

void myprint(void);

void myprint()
{
    printf("hello world\n");
}

Now compile it as a shared library (mac fix found here):

$ gcc -shared -Wl,-soname,testlib -o testlib.so -fPIC testlib.c

# or... for Mac OS X 
$ gcc -shared -Wl,-install_name,testlib.so -o testlib.so -fPIC testlib.c

Then, write a wrapper using ctypes:

testlibwrapper.py

import ctypes

testlib = ctypes.CDLL('/full/path/to/testlib.so')
testlib.myprint()

Now execute it:

$ python testlibwrapper.py

And you should see the output

Hello world
$

If you already have a library in mind, you can skip the non-python part of the tutorial. Make sure ctypes can find the library by putting it in /usr/lib or another standard directory. If you do this, you don't need to specify the full path when writing the wrapper. If you choose not to do this, you must provide the full path of the library when calling ctypes.CDLL().

This isn't the place for a more comprehensive tutorial, but if you ask for help with specific problems on this site, I'm sure the community would help you out.

PS: I'm assuming you're on Linux because you've used ctypes.CDLL('libc.so.6'). If you're on another OS, things might change a little bit (or quite a lot).

Authentication issue when debugging in VS2013 - iis express

VS 2015 changes this. It added a .vs folder to my web project and the applicationhost.config was in there. I made the changes suggested (window authentication = true, anon=false) and it started delivering a username instead of a blank.

Autonumber value of last inserted row - MS Access / VBA

If DAO use

RS.Move 0, RS.LastModified
lngID = RS!AutoNumberFieldName

If ADO use

cn.Execute "INSERT INTO TheTable.....", , adCmdText + adExecuteNoRecords
Set rs = cn.Execute("SELECT @@Identity", , adCmdText)
Debug.Print rs.Fields(0).Value

cn being a valid ADO connection, @@Identity will return the last Identity (Autonumber) inserted on this connection.

Note that @@Identity might be troublesome because the last generated value may not be the one you are interested in. For the Access database engine, consider a VIEW that joins two tables, both of which have the IDENTITY property, and you INSERT INTO the VIEW. For SQL Server, consider if there are triggers that in turn insert records into another table that also has the IDENTITY property.

BTW DMax would not work as if someone else inserts a record just after you've inserted one but before your Dmax function finishes excecuting, then you would get their record.

How do you get the current project directory from C# code when creating a custom MSBuild task?

If you want ot know what is the directory where your solution is located, you need to do this:

 var parent = Directory.GetParent(Directory.GetCurrentDirectory()).Parent;
            if (parent != null)
            {
                var directoryInfo = parent.Parent;
                string startDirectory = null;
                if (directoryInfo != null)
                {
                    startDirectory = directoryInfo.FullName;
                }
                if (startDirectory != null)
                { /*Do whatever you want "startDirectory" variable*/}
            }

If you let only with GetCurrrentDirectory() method, you get the build folder no matter if you are debugging or releasing. I hope this help! If you forget about validations it would be like this:

var startDirectory = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName;

How can I compile a Java program in Eclipse without running it?

You can un-check the build automatically in Project menu and then build by hand by type Ctrl + B, or clicking an icon the appears to the right of the printer icon.

Can VS Code run on Android?

The accepted answer is correct as asked, below answers the opposite question of developing Android on VS Code.

Extensions

Ultimately you can automate building and running your app on a device emulator by adding the function below to your $PATH and running runDebugApp <module> <start activity> from the integrated terminal:

# run android app
# usage runDebugApp [module] [fully qualified start activity com.package/com.package.MainActivity]
function runDebugApp(){
  ./gradlew -offline :"$1":installDebug && adb shell am start "$2" && adb logcat -d > logcat.log
}

How to convert Milliseconds to "X mins, x seconds" in Java?

This answer is similar to some answers above. However, I feel that it would be beneficial because, unlike other answers, this will remove any extra commas or whitespace and handles abbreviation.

/**
 * Converts milliseconds to "x days, x hours, x mins, x secs"
 * 
 * @param millis
 *            The milliseconds
 * @param longFormat
 *            {@code true} to use "seconds" and "minutes" instead of "secs" and "mins"
 * @return A string representing how long in days/hours/minutes/seconds millis is.
 */
public static String millisToString(long millis, boolean longFormat) {
    if (millis < 1000) {
        return String.format("0 %s", longFormat ? "seconds" : "secs");
    }
    String[] units = {
            "day", "hour", longFormat ? "minute" : "min", longFormat ? "second" : "sec"
    };
    long[] times = new long[4];
    times[0] = TimeUnit.DAYS.convert(millis, TimeUnit.MILLISECONDS);
    millis -= TimeUnit.MILLISECONDS.convert(times[0], TimeUnit.DAYS);
    times[1] = TimeUnit.HOURS.convert(millis, TimeUnit.MILLISECONDS);
    millis -= TimeUnit.MILLISECONDS.convert(times[1], TimeUnit.HOURS);
    times[2] = TimeUnit.MINUTES.convert(millis, TimeUnit.MILLISECONDS);
    millis -= TimeUnit.MILLISECONDS.convert(times[2], TimeUnit.MINUTES);
    times[3] = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
    StringBuilder s = new StringBuilder();
    for (int i = 0; i < 4; i++) {
        if (times[i] > 0) {
            s.append(String.format("%d %s%s, ", times[i], units[i], times[i] == 1 ? "" : "s"));
        }
    }
    return s.toString().substring(0, s.length() - 2);
}

/**
 * Converts milliseconds to "x days, x hours, x mins, x secs"
 * 
 * @param millis
 *            The milliseconds
 * @return A string representing how long in days/hours/mins/secs millis is.
 */
public static String millisToString(long millis) {
    return millisToString(millis, false);
}

Transparent background on winforms?

The manner I have used before is to use a wild color (a color no one in their right mind would use) for the BackColor and then set the transparency key to that.

this.BackColor = Color.LimeGreen;
this.TransparencyKey = Color.LimeGreen;

Add row to query result using select

is it possible to extend query results with literals like this?

Yes.

Select Name
From Customers
UNION ALL
Select 'Jason'
  • Use UNION to add Jason if it isn't already in the result set.
  • Use UNION ALL to add Jason whether or not he's already in the result set.

Slick Carousel Uncaught TypeError: $(...).slick is not a function

Recently had the same problem: TypeError: $(...).slick is not a function

Found an interesting solution. Hope, it might be useful to somebody.

In my particular situation there are: jQuery + WHMCS + slick. It works normal standalone, without WHMCS. But after the integration to WHMCS an error appears.

The solution was to use jQuery in noConflict mode.

Ex: Your code:

$(document).ready(function() { 
  $('a').click( function(event) {
    $(this).hide();
    event.preventDefault();
  });
});

Code in noConflict mode:

var $jq = jQuery.noConflict();
$jq(document).ready(function() { 
  $jq('a').click( function(event) {
    $jq(this).hide();
    event.preventDefault();
  });
});

The solution was found here: http://zenverse.net/jquery-how-to-fix-the-is-not-a-function-error-using-noconflict/

Can someone provide an example of a $destroy event for scopes in AngularJS?

$destroy can refer to 2 things: method and event

1. method - $scope.$destroy

.directive("colorTag", function(){
  return {
    restrict: "A",
    scope: {
      value: "=colorTag"
    },
    link: function (scope, element, attrs) {
      var colors = new App.Colors();
      element.css("background-color", stringToColor(scope.value));
      element.css("color", contrastColor(scope.value));

      // Destroy scope, because it's no longer needed.
      scope.$destroy();
    }
  };
})

2. event - $scope.$on("$destroy")

See @SunnyShah's answer.

how to stop a loop arduino

Matti Virkkunen said it right, there's no "decent" way of stopping the loop. Nonetheless, by looking at your code and making several assumptions, I imagine you're trying to output a signal with a given frequency, but you want to be able to stop it.

If that's the case, there are several solutions:

  1. If you want to generate the signal with the input of a button you could do the following

    int speakerOut = A0;
    int buttonPin = 13;
    
    void setup() {
        pinMode(speakerOut, OUTPUT);
        pinMode(buttonPin, INPUT_PULLUP);
    }
    
    int a = 0;
    
    void loop() {
        if(digitalRead(buttonPin) == LOW) {
            a ++;
            Serial.println(a);
            analogWrite(speakerOut, NULL);
    
            if(a > 50 && a < 300) {
                analogWrite(speakerOut, 200);
            }
    
            if(a <= 49) {
                analogWrite(speakerOut, NULL);
            }
    
            if(a >= 300 && a <= 2499) {
                analogWrite(speakerOut, NULL);
            }
        }
    }
    

    In this case we're using a button pin as an INPUT_PULLUP. You can read the Arduino reference for more information about this topic, but in a nutshell this configuration sets an internal pullup resistor, this way you can just have your button connected to ground, with no need of external resistors. Note: This will invert the levels of the button, LOW will be pressed and HIGH will be released.

  2. The other option would be using one of the built-ins hardware timers to get a function called periodically with interruptions. I won't go in depth be here's a great description of what it is and how to use it.

"Can't find Project or Library" for standard VBA functions

I have seen errors on standard functions if there was a reference to a totally different library missing.

In the VBA editor launch the Compile command from the menu and then check the References dialog to see if there is anything missing and if so try to add these libraries.

In general it seems to be good practice to compile the complete VBA code and then saving the document before distribution.

How to set a text box for inputing password in winforms?

The best way to solve your problem is to set the UseSystemPasswordChar property to true. Then, the Caps-lock message is shown when the user enters the field and the Caps-Lock is on (at least for Vista and Windows 7).

Another alternative is to set the PasswordChar property to a character value (* for example). This also triggers the automatic Caps-Lock handling.

Detecting the character encoding of an HTTP POST request

Try setting the charset on your Content-Type:

httpCon.setRequestProperty( "Content-Type", "multipart/form-data; charset=UTF-8; boundary=" + boundary );

Reversing a string in C

Rather than breaking half-way through, you should simply shorten your loop.

size_t length = strlen(str);
size_t i;

for (i = 0; i < (length / 2); i++)
{
    char temp = str[length - i - 1];
    str[length - i - 1] = str[i];
    str[i] = temp;
}

How can I get the DateTime for the start of the week?

Tried several but did not solve the issue with a week starting on a Monday, resulting in giving me the coming Monday on a Sunday. So I modified it a bit and got it working with this code:

int delta = DayOfWeek.Monday - DateTime.Now.DayOfWeek;
DateTime monday = DateTime.Now.AddDays(delta == 1 ? -6 : delta);
return monday;

View a file in a different Git branch without changing branches

git show somebranch:path/to/your/file

you can also do multiple files and have them concatenated:

git show branchA~10:fileA branchB^^:fileB

You do not have to provide the full path to the file, relative paths are acceptable e.g.:

git show branchA~10:../src/hello.c

If you want to get the file in the local directory (revert just one file) you can checkout:

git checkout somebranch^^^ -- path/to/file

Updating a JSON object using Javascript

var i = jsonObj.length;
while ( i --> 0 ) {
    if ( jsonObj[i].Id === 3 ) {
        jsonObj[ i ].Username = 'Thomas';
        break;
    }
}

Or, if the array is always ordered by the IDs:

jsonObj[ 2 ].Username = 'Thomas';

Text File Parsing with Python

There are a few ways to go about this. One option would be to use inputfile.read() instead of inputfile.readlines() - you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.

A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text). This is a little inefficient, but if speed isn't a major concern, the code will be simplest.

Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:

def data_parser(lines, dic):
    for i, j in dic.iteritems():
        for (k, line) in enumerate(lines):
            lines[k] = line.replace(i, j)
    return lines

how to create a login page when username and password is equal in html

<html>
    <head>
        <title>Login page</title>
    </head>
    <body>
        <h1>Simple Login Page</h1>
        <form name="login">
            Username<input type="text" name="userid"/>
            Password<input type="password" name="pswrd"/>
            <input type="button" onclick="check(this.form)" value="Login"/>
            <input type="reset" value="Cancel"/>
        </form>
        <script language="javascript">
            function check(form) { /*function to check userid & password*/
                /*the following code checkes whether the entered userid and password are matching*/
                if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
                    window.open('target.html')/*opens the target page while Id & password matches*/
                }
                else {
                    alert("Error Password or Username")/*displays error message*/
                }
            }
        </script>
    </body>
</html>

MySQL Event Scheduler on a specific time everyday

CREATE EVENT test_event_03
ON SCHEDULE EVERY 1 MINUTE
STARTS CURRENT_TIMESTAMP
ENDS CURRENT_TIMESTAMP + INTERVAL 1 HOUR
DO
   INSERT INTO messages(message,created_at)
   VALUES('Test MySQL recurring Event',NOW());

How to save a plot as image on the disk?

If you use R Studio http://rstudio.org/ there is a special menu to save you plot as any format you like and at any resolution you choose

nodejs - How to read and output jpg image?

Two things to keep in mind Content-Type and the Encoding

1) What if the file is css

if (/.(css)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'text/css'}); 
  res.write(data, 'utf8');
} 

2) What if the file is jpg/png

if (/.(jpg)$/.test(path)) {
  res.writeHead(200, {'Content-Type': 'image/jpg'});
  res.end(data,'Base64');
}

Above one is just a sample code to explain the answer and not the exact code pattern.

Where does MAMP keep its php.ini?

I'm not sure if in MAMP (non-PRO) is the same, but MAMP overrides the modified php.ini everytime it starts.

In my case, I needed to use the MAMP menu to change my php.ini file (File -> Edit Template -> PHP -> PHP 5.xx -> php.ini).

Incorrect integer value: '' for column 'id' at row 1

That probably means that your id is an AUTO_INCREMENT integer and you're trying to send a string. You should specify a column list and omit it from your INSERT.

INSERT INTO workorders (column1, column2) VALUES ($column1, $column2)

Check if two lists are equal

Use SequenceEqual to check for sequence equality because Equals method checks for reference equality.

var a = ints1.SequenceEqual(ints2);

Or if you don't care about elements order use Enumerable.All method:

var a = ints1.All(ints2.Contains);

The second version also requires another check for Count because it would return true even if ints2 contains more elements than ints1. So the more correct version would be something like this:

var a = ints1.All(ints2.Contains) && ints1.Count == ints2.Count;

In order to check inequality just reverse the result of All method:

var a = !ints1.All(ints2.Contains)

How to check if a char is equal to an empty space?

In this case, you are thinking of the String comparing function "String".equals("some_text"). Chars do not need to use this function. Instead a standard == comparison operator will suffice.

private static int countNumChars(String s) {
    for(char c : s.toCharArray()){
        if (c == ' ') // your resulting outcome
    }
}

100% width background image with an 'auto' height

Try this

html { 
  background: url(image.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
     -moz-background-size: cover;
       -o-background-size: cover;
          background-size: cover;
}

Simplified version

html {
  background: url(image.jpg) center center / cover no-repeat fixed;
}

Matplotlib-Animation "No MovieWriters Available"

I'm running Ubuntu 20 and I had a similar problem

Installed ffmpeg

pip install ffmpeg

then

sudo apt install ffmpeg

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

What It Is

This is an arrow function. Arrow functions are a short syntax, introduced by ECMAscript 6, that can be used similarly to the way you would use function expressions. In other words, you can often use them in place of expressions like function (foo) {...}. But they have some important differences. For example, they do not bind their own values of this (see below for discussion).

Arrow functions are part of the ECMAscript 6 specification. They are not yet supported in all browsers, but they are partially or fully supported in Node v. 4.0+ and in most modern browsers in use as of 2018. (I’ve included a partial list of supporting browsers below).

You can read more in the Mozilla documentation on arrow functions.

From the Mozilla documentation:

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous. These function expressions are best suited for non-method functions and they can not be used as constructors.

A Note on How this Works in Arrow Functions

One of the most handy features of an arrow function is buried in the text above:

An arrow function... lexically binds the this value (does not bind its own this...)

What this means in simpler terms is that the arrow function retains the this value from its context and does not have its own this. A traditional function may bind its own this value, depending on how it is defined and called. This can require lots of gymnastics like self = this;, etc., to access or manipulate this from one function inside another function. For more info on this topic, see the explanation and examples in the Mozilla documentation.

Example Code

Example (also from the docs):

var a = [
  "We're up all night 'til the sun",
  "We're up all night to get some",
  "We're up all night for good fun",
  "We're up all night to get lucky"
];

// These two assignments are equivalent:

// Old-school:
var a2 = a.map(function(s){ return s.length });

// ECMAscript 6 using arrow functions
var a3 = a.map( s => s.length );

// both a2 and a3 will be equal to [31, 30, 31, 31]

Notes on Compatibility

You can use arrow functions in Node, but browser support is spotty.

Browser support for this functionality has improved quite a bit, but it still is not widespread enough for most browser-based usages. As of December 12, 2017, it is supported in current versions of:

  • Chrome (v. 45+)
  • Firefox (v. 22+)
  • Edge (v. 12+)
  • Opera (v. 32+)
  • Android Browser (v. 47+)
  • Opera Mobile (v. 33+)
  • Chrome for Android (v. 47+)
  • Firefox for Android (v. 44+)
  • Safari (v. 10+)
  • iOS Safari (v. 10.2+)
  • Samsung Internet (v. 5+)
  • Baidu Browser (v. 7.12+)

Not supported in:

  • IE (through v. 11)
  • Opera Mini (through v. 8.0)
  • Blackberry Browser (through v. 10)
  • IE Mobile (through v. 11)
  • UC Browser for Android (through v. 11.4)
  • QQ (through v. 1.2)

You can find more (and more current) information at CanIUse.com (no affiliation).

Express.js: how to get remote client address

If you are running behind a proxy like NGiNX or what have you, only then you should check for 'x-forwarded-for':

var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;

If the proxy isn't 'yours', I wouldn't trust the 'x-forwarded-for' header, because it can be spoofed.

send checkbox value in PHP form

if(isset($_POST["newsletter"]) && $_POST["newsletter"] == "newsletter"){
    //checked
}

How to implement my very own URI scheme on Android

Another alternate approach to Diego's is to use a library:

https://github.com/airbnb/DeepLinkDispatch

You can easily declare the URIs you'd like to handle and the parameters you'd like to extract through annotations on the Activity, like:

@DeepLink("path/to/what/i/want")
public class SomeActivity extends Activity {
  ...
}

As a plus, the query parameters will also be passed along to the Activity as well.

Entity Framework Refresh context?

If you want to reload specific entities, with the DbContextApi, RX_DID_RX already gave you the answer.

If you want to reload / refresh all the entities you loaded:

If you are using Entity Framework 4.1+ (EF5, or EF 6 probably), DbContext API:

public void RefreshAll()
{
     foreach (var entity in ctx.ChangeTracker.Entries())
     {
           entity.Reload();
     }
}

If you are using entityFramework 4 (ObjectContext API):

public void RefreshAll()
{
     // Get all objects in statemanager with entityKey
     // (context.Refresh will throw an exception otherwise)
     var refreshableObjects = (from entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted
                                               | EntityState.Modified
                                               | EntityState.Unchanged)
                                      where entry.EntityKey != null
                                      select entry.Entity);

     context.Refresh(RefreshMode.StoreWins, refreshableObjects);
}

Best advice anyway is, try to use a "short lived context" and you'll avoid this kind of problems.

I wrote a couple of articles on the matter:

https://christianarg.wordpress.com/2013/06/13/entityframework-refreshall-loaded-entities-from-database/

AngularJS ui-router login authentication

First you'll need a service that you can inject into your controllers that has some idea of app authentication state. Persisting auth details with local storage is a decent way to approach it.

Next, you'll need to check the state of auth right before state changes. Since your app has some pages that need to be authenticated and others that don't, create a parent route that checks auth, and make all other pages that require the same be a child of that parent.

Finally, you'll need some way to tell if your currently logged in user can perform certain operations. This can be achieved by adding a 'can' function to your auth service. Can takes two parameters: - action - required - (ie 'manage_dashboards' or 'create_new_dashboard') - object - optional - object being operated on. For example, if you had a dashboard object, you may want to check to see if dashboard.ownerId === loggedInUser.id. (Of course, information passed from the client should never be trusted and you should always verify this on the server before writing it to your database).

angular.module('myApp', ['ngStorage']).config([
   '$stateProvider',
function(
   $stateProvider
) {
   $stateProvider
     .state('home', {...}) //not authed
     .state('sign-up', {...}) //not authed
     .state('login', {...}) //not authed
     .state('authed', {...}) //authed, make all authed states children
     .state('authed.dashboard', {...})
}])
.service('context', [
   '$localStorage',
function(
   $localStorage
) {
   var _user = $localStorage.get('user');
   return {
      getUser: function() {
         return _user;
      },
      authed: function() {
         return (_user !== null);
      },
      // server should return some kind of token so the app 
      // can continue to load authenticated content without having to
      // re-authenticate each time
      login: function() {
         return $http.post('/login.json').then(function(reply) {
            if (reply.authenticated === true) {
               $localStorage.set(_userKey, reply.user);
            }
         });
      },
      // this request should expire that token, rendering it useless
      // for requests outside of this session
      logout: function() {
         return $http.post('logout.json').then(function(reply) {
            if (reply.authenticated === true) {
               $localStorage.set(_userKey, reply.user);
            }
         });
      },
      can: function(action, object) {
         if (!this.authed()) {
            return false;
         }

         var user = this.getUser();

         if (user && user.type === 'admin') {
             return true;
         }

         switch(action) {
            case 'manage_dashboards':
               return (user.type === 'manager');
         }

         return false;


      }
   }
}])
.controller('AuthCtrl', [
   'context', 
   '$scope', 
function(
   context, 
   $scope
) {
   $scope.$root.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) {
      //only require auth if we're moving to another authed page
      if (toState && toState.name.indexOf('authed') > -1) {
         requireAuth();
      }
   });

   function requireAuth() {
      if (!context.authed()) {
         $state.go('login');
      }
   }
}]

** DISCLAIMER: The above code is pseudo-code and comes with no guarantees **

Appending to an existing string

Here's another way:

fist_segment = "hello,"
second_segment = "world."
complete_string = "#{first_segment} #{second_segment}"

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

I got the same error, but when i did as below, it resolved the issue.
Instead of writing like this:

List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

use the below one:

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

Method #1: Download from Here and insert it to your projects, or
Method #2: use below code before your bootstrap script source:

<script src="https://npmcdn.com/[email protected]/dist/js/tether.min.js"></script>

ORA-01031: insufficient privileges when selecting view

Let me make a recap.

When you build a view containing object of different owners, those other owners have to grant "with grant option" to the owner of the view. So, the view owner can grant to other users or schemas....

Example: User_a is the owner of a table called mine_a User_b is the owner of a table called yours_b

Let's say user_b wants to create a view with a join of mine_a and yours_b

For the view to work fine, user_a has to give "grant select on mine_a to user_b with grant option"

Then user_b can grant select on that view to everybody.

"Could not find or load main class" Error while running java program using cmd prompt

I faced the same problem and tried everything mentioned here. The thing was I didn't refresh my project in eclipse after class creation . And once I refreshed it things worked as expected.

Executing a batch file in a remote machine through PsExec

You have an extra -c you need to get rid of:

psexec -u administrator -p force \\135.20.230.160 -s -d cmd.exe /c "C:\Amitra\bogus.bat"

How do I get a Date without time in Java?

If you need the date part just for echoing purpose, then

Date d = new Date(); 
String dateWithoutTime = d.toString().substring(0, 10);

Java Date cut off time information

The recommended way to do date/time manipulation is to use a Calendar object:

Calendar cal = Calendar.getInstance(); // locale-specific
cal.setTime(dateObject);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long time = cal.getTimeInMillis();

Excel: Use a cell value as a parameter for a SQL query

If you are using microsoft query, you can add "?" to your query...

select name from user where id= ?

that will popup a small window asking for the cell/data/etc when you go back to excel.

In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.

In C#, can a class inherit from another class and an interface?

No, not exactly. But it can inherit from a class and implement one or more interfaces.

Clear terminology is important when discussing concepts like this. One of the things that you'll see mark out Jon Skeet's writing, for example, both here and in print, is that he is always precise in the way he decribes things.

Using XPATH to search text containing &nbsp;

As per the HTML you have provided:

<tr>
  <td>abc</td>
  <td>&nbsp;</td>
</tr>

To locate the node with the string &nbsp; you can use either of the following based solutions:

  • Using text():

    "//td[text()='\u00A0']"
    
  • Using contains():

    "//td[contains(., '\u00A0')]"
    

However, ideally you may like to avoid the NO-BREAK SPACE character and use either of the following Locator Strategies:

  • Using the parent <tr> node and following-sibling:

    "//tr//following-sibling::td[2]"
    
  • Using starts-with():

    "//tr//td[last()]"
    
  • Using the preceeding <td> node and followingnode andfollowing-sibling`:

    "//td[text()='abc']//following::td[1]"
    

Reference

You can find a relevant detailed discussion in:


tl; dr

Unicode Character 'NO-BREAK SPACE' (U+00A0)

How to clear the interpreter console?

Just enter

import os
os.system('cls') # Windows
os.system('clear') # Linux, Unix, Mac OS X

Returning multiple values from a C++ function

I'd say there is no preferred method, it all depends on what you're going to do with the response. If the results are going to be used together in further processing then structures make sense, if not I'd tend to pass then as individual references unless the function was going to be used in a composite statement:

x = divide( x, y, z ) + divide( a, b, c );

I often choose to pass 'out structures' by reference in the parameter list rather than having the pass by copy overhead of returning a new structure (but this is sweating the small stuff).

void divide(int dividend, int divisor, Answer &ans)

Are out parameters confusing? A parameter sent as reference suggests the value is going to change (as opposed to a const reference). Sensible naming also removes confusion.

What is the difference between rb and r+b modes in file objects

My understanding is that adding r+ opens for both read and write (just like w+, though as pointed out in the comment, will truncate the file). The b just opens it in binary mode, which is supposed to be less aware of things like line separators (at least in C++).

Target WSGI script cannot be loaded as Python module

I was getting this error. I'm using python 3 in a virtual environment found this in my apache logs

[Fri Dec 21 08:01:43.471561 2018] [mpm_prefork:notice] [pid 21786] AH00163: Apache/2.4.6 (Red Hat Enterprise Linux) mod_wsgi/3.4 Python/2.7.5 configured -- resuming normal operations

I had installed wsgi using yum -y install mod_wsgi. This had installed mod_wsgi compiled for python 2. So I uninstalled it

yum remove mod_wsgi

and installed mod_wsgi compiled for python 3 using

yum install python35u-mod_wsgi

It worked after that

Visual Studio Post Build Event - Copy to Relative Directory Location

I think this is related, but I had a problem when building directly using msbuild command line (from a batch file) vs building from within VS.

Using something like the following:

<PostBuildEvent>
  MOVE /Y "$(TargetDir)something.file1" "$(ProjectDir)something.file1"
  start XCOPY /Y /R "$(SolutionDir)SomeConsoleApp\bin\$(ConfigurationName)\*" "$(ProjectDir)App_Data\Consoles\SomeConsoleApp\"
</PostBuildEvent>

(note: start XCOPY rather than XCOPY used to get around a permissions issue which prevented copying)

The macro $(SolutionDir) evaluated to ..\ when executing msbuild from a batchfile, which resulted in the XCOPY command failing. It otherwise worked fine when built from within Visual Studio. Confirmed using /verbosity:diagnostic to see the evaluated output.

Using the macro $(ProjectDir)..\ instead, which amounts to the same thing, worked fine and retained the full path in both build scenarios.

"And" and "Or" troubles within an IF statement

The problem is probably somewhere else. Try this code for example:

Sub test()

  origNum = "006260006"
  creditOrDebit = "D"

  If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
    MsgBox "OK"
  End If

End Sub

And you will see that your Or works as expected. Are you sure that your ElseIf statement is executed (it will not be executed if any of the if/elseif before is true)?

Get current time as formatted string in Go?

For readability, best to use the RFC constants in the time package (me thinks)

import "fmt" 
import "time"

func main() {
    fmt.Println(time.Now().Format(time.RFC850))
}

How to pass url arguments (query string) to a HTTP request on Angular?

In latest Angular 7/8, you can use the simplest approach:-

import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';

getDetails(searchParams) {
    const httpOptions = {
        headers: { 'Content-Type': 'application/json' },
        params: { ...searchParams}
    };
    return this.http.get(this.Url, httpOptions);
}

How to call a REST web service API from JavaScript?

Here is another Javascript REST API Call with authentication using json:

<script type="text/javascript" language="javascript">

function send()
{
    var urlvariable;

    urlvariable = "text";

    var ItemJSON;

    ItemJSON = '[  {    "Id": 1,    "ProductID": "1",    "Quantity": 1,  },  {    "Id": 1,    "ProductID": "2",    "Quantity": 2,  }]';

    URL = "https://testrestapi.com/additems?var=" + urlvariable;  //Your URL

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
    xmlhttp.open("POST", URL, false);
    xmlhttp.setRequestHeader("Content-Type", "application/json");
    xmlhttp.setRequestHeader('Authorization', 'Basic ' + window.btoa('apiusername:apiuserpassword')); //in prod, you should encrypt user name and password and provide encrypted keys here instead 
    xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
    xmlhttp.send(ItemJSON);
    alert(xmlhttp.responseText);
    document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + xmlhttp.responseText + "</textarea>";
}

function callbackFunction(xmlhttp) 
{
    //alert(xmlhttp.responseXML);
}
</script>


<html>
<body id='bod'><button type="submit" onclick="javascript:send()">call</button>
<div id='div'>

</div></body>
</html>

I got error "The DELETE statement conflicted with the REFERENCE constraint"

You are trying to delete a row that is referenced by another row (possibly in another table).

You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.

Replace words in the body text

I was trying to replace a really large string and for some reason regular expressions were throwing some errors/exceptions.

So I found this alternative to regular expressions which also runs pretty fast. At least it was fast enough for me:

var search = "search string";
var replacement = "replacement string";

document.body.innerHTML = document.body.innerHTML.split(search).join(replacement)

src: How to replace all occurrences of a string in JavaScript?

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

Http Get using Android HttpURLConnection

A more contemporary way of doing it on a separate thread using Tasks and Kotlin

private val mExecutor: Executor = Executors.newSingleThreadExecutor()

private fun createHttpTask(u:String): Task<String> {
    return Tasks.call(mExecutor, Callable<String>{
        val url = URL(u)
        val conn: HttpURLConnection = url.openConnection() as HttpURLConnection
        conn.requestMethod = "GET"
        conn.connectTimeout = 3000
        conn.readTimeout = 3000
        val rc = conn.responseCode
        if ( rc != HttpURLConnection.HTTP_OK) {
            throw java.lang.Exception("Error: ${rc}")
        }
        val inp: InputStream = BufferedInputStream(conn.inputStream)
        val resp: String = inp.bufferedReader(UTF_8).use{ it.readText() }
        return@Callable resp
    })
}

and now you can use it like below in many places:

            createHttpTask("https://google.com")
                    .addOnSuccessListener {
                        Log.d("HTTP", "Response: ${it}") // 'it' is a response string here
                    }
                    .addOnFailureListener {
                        Log.d("HTTP", "Error: ${it.message}") // 'it' is an Exception object here
                    }

How do I get interactive plots again in Spyder/IPython/matplotlib?

After applying : Tools > preferences > Graphics > Backend > Automatic Just restart the kernel enter image description here

And you will surely get Interactive Plot. Happy Coding!

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

inline conditionals in angular.js

Angular UI library has built-in directive ui-if for condition in template/Views upto angular ui 1.1.4

Example: Support in Angular UI upto ui 1.1.4

<div ui-if="array.length>0"></div>

ng-if available in all the angular version after 1.1.4

<div ng-if="array.length>0"></div>

if you have any data in array variable then only the div will appear

document.body.appendChild(i)

May also want to use "documentElement":

var elem = document.createElement("div");
elem.style = "width:100px;height:100px;position:relative;background:#FF0000;";
document.documentElement.appendChild(elem);

Use "ENTER" key on softkeyboard instead of clicking button

To avoid the focus advancing to the next editable field (if you have one) you might want to ignore the key-down events, but handle key-up events. I also prefer to filter first on the keyCode, assuming that it would be marginally more efficient. By the way, remember that returning true means that you have handled the event, so no other listener will. Anyway, here is my version.

ETFind.setOnKeyListener(new OnKeyListener()
{
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if (keyCode ==  KeyEvent.KEYCODE_DPAD_CENTER
        || keyCode ==  KeyEvent.KEYCODE_ENTER) {

            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                // do nothing yet
            } else if (event.getAction() == KeyEvent.ACTION_UP) {
                        findForward();      
            } // is there any other option here?...

            // Regardless of what we did above,
            // we do not want to propagate the Enter key up
            // since it was our task to handle it.
            return true;

        } else {
            // it is not an Enter key - let others handle the event
            return false;
        }
    }

});

htaccess redirect to https://www

Michals answer worked for me, albeit with one small modification:

Problem:

when you have a single site security certificate, a browser that tries to access your page without https:// www. (or whichever domain your certificate covers) will display an ugly red warning screen before it even gets to receive the redirect to the safe and correct https page.

Solution

First use the redirect to the www (or whichever domain is covered by your certificate) and only then do the https redirect. This will ensure that your users are not confronted with any error because your browser sees a certificate that doesn't cover the current url.

#First rewrite any request to the wrong domain to use the correct one (here www.)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Convert character to Date in R

You may be overcomplicating things, is there any reason you need the stringr package?

 df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
 as.Date(df$Date, "%m/%d/%Y %H:%M:%S")

[1] "2009-10-09" "2009-10-15"

More generally and if you need the time component as well, use strptime:

strptime(df$Date, "%m/%d/%Y %H:%M:%S")

I'm guessing at what your actual data might look at from the partial results you give.

How to cut first n and last n columns?

You can cut using following ,
-d: delimiter ,-f for fields
\t used for tab separated fields

cut -d$'\t' -f 1-3,7-

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

What is "406-Not Acceptable Response" in HTTP?

In my case, I added:

Content-Type: application/x-www-form-urlencoded

solved my problem completely.

Submit button doesn't work

Hello from the future.

For clarity, I just wanted to add (as this was pretty high up in google) - we can now use

<button type="submit">Upload Stuff</button>

And to reset a form

<button type="reset" value="Reset">Reset</button>

Check out button types

We can also attach buttons to submit forms like this:

<button type="submit" form="myform" value="Submit">Submit</button>

How to use global variable in node.js?

Most people advise against using global variables. If you want the same logger class in different modules you can do this

logger.js

  module.exports = new logger(customConfig);

foobar.js

  var logger = require('./logger');
  logger('barfoo');

If you do want a global variable you can do:

global.logger = new logger(customConfig);

Where to find the complete definition of off_t type?

If you are having trouble tracing the definitions, you can use the preprocessed output of the compiler which will tell you all you need to know. E.g.

$ cat test.c
#include <stdio.h>
$ cc -E test.c | grep off_t
typedef long int __off_t;
typedef __off64_t __loff_t;
  __off_t __pos;
  __off_t _old_offset;
typedef __off_t off_t;
extern int fseeko (FILE *__stream, __off_t __off, int __whence);
extern __off_t ftello (FILE *__stream) ;

If you look at the complete output you can even see the exact header file location and line number where it was defined:

# 132 "/usr/include/bits/types.h" 2 3 4


typedef unsigned long int __dev_t;
typedef unsigned int __uid_t;
typedef unsigned int __gid_t;
typedef unsigned long int __ino_t;
typedef unsigned long int __ino64_t;
typedef unsigned int __mode_t;
typedef unsigned long int __nlink_t;
typedef long int __off_t;
typedef long int __off64_t;

...

# 91 "/usr/include/stdio.h" 3 4
typedef __off_t off_t;

Can a background image be larger than the div itself?

You can use a css3 psuedo element (:before and/or :after) as shown in this article

https://www.exratione.com/2011/09/how-to-overflow-a-background-image-using-css3/

Good Luck...

How to see top processes sorted by actual memory usage?

List and Sort Processes by Memory Usage:

ps -e -orss=,args= | sort -b -k1,1n | pr -TW$COLUMNS

How to connect to a remote MySQL database with Java?

Plus, you should make sure the MySQL server's config (/etc/mysql/my.cnf, /etc/default/mysql on Debian) doesn't have "skip-networking" activated and is not binded exclusively to the loopback interface (127.0.0.1) but also to the interface/IP address you want connect to.

How to redirect stderr and stdout to different files in the same line in script?

Multiple commands' output can be redirected. This works for either the command line or most usefully in a bash script. The -s directs the password prompt to the screen.

Hereblock cmds stdout/stderr are sent to seperate files and nothing to display.

sudo -s -u username <<'EOF' 2>err 1>out
ls; pwd;
EOF

Hereblock cmds stdout/stderr are sent to a single file and display.

sudo -s -u username <<'EOF' 2>&1 | tee out
ls; pwd;
EOF

Hereblock cmds stdout/stderr are sent to separate files and stdout to display.

sudo -s -u username <<'EOF' 2>err | tee out
ls; pwd;
EOF

Depending on who you are(whoami) and username a password may or may not be required.

Correct way to read a text file into a buffer in C?

Not tested, but should work.. And yes, it could be better implemented with fread, I'll leave that as an exercise to the reader.

#define DEFAULT_SIZE 100
#define STEP_SIZE 100

char *buffer[DEFAULT_SIZE];
size_t buffer_sz=DEFAULT_SIZE;
size_t i=0;
while(!feof(fp)){
  buffer[i]=fgetc(fp);
  i++;
  if(i>=buffer_sz){
    buffer_sz+=STEP_SIZE;
    void *tmp=buffer;
    buffer=realloc(buffer,buffer_sz);
    if(buffer==null){ free(tmp); exit(1);} //ensure we don't have a memory leak
  }
}
buffer[i]=0;

git pull fails "unable to resolve reference" "unable to update local ref"

In my case, the problem was solved after I've deleted all the remove reference files under the directory .git.

If you look at the message, it would tell you which files you need to delete (specifically).

The files to delete sit under .git/refs/remotes.

I've just deleted all the files there, and ran gc prune

git gc --prune=now

After that, everything works just fine.

Remove trailing zeros from decimal in SQL Server

I understand this is an old post but would like to provide SQL that i came up with

DECLARE @value DECIMAL(23,3)
set @value = 1.2000
select @value original_val, 
    SUBSTRING(  CAST( @value as VARCHAR(100)), 
                0,
                PATINDEX('%.%',CAST(@value as VARCHAR(100)))
            )
      + CASE WHEN ROUND( 
                        REVERSE( SUBSTRING( CAST(@value as VARCHAR(100)),
                                        PATINDEX('%.%',CAST(@value as VARCHAR(100)))+1,
                                        LEN(CAST(@value as VARCHAR(100)))
                                        )
                                )
                    ,1) > 0 THEN 
            '.' 
            +  REVERSE(ROUND(REVERSE(SUBSTRING( CAST(@value as VARCHAR(100)),
                                                PATINDEX('%.%',CAST(@value as VARCHAR(100)))+1,
                                                LEN(CAST(@value as VARCHAR(100)))
                                                )
                ),1))
        ELSE '' END  AS modified_val

SQL Server Installation - What is the Installation Media Folder?

For me the Issue was I didn't run the setup as Administrator, after running the setup as administrator the message go away and I was prompted to install and continue process.

Alternative for PHP_excel

I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.

http://github.com/elidickinson/php-export-data

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

Final Solution for this problem is below :

  1. First make changes in applicationHost config file. replace below string setProfileEnvironment="false" TO setProfileEnvironment="true"

  2. In your database connection string add below attribute : Integrated Security = SSPI

Python read-only property

While I like the class decorator from Oz123, you could also do the following, which uses an explicit class wrapper and __new__ with a class Factory method returning the class within a closure:

class B(object):
    def __new__(cls, val):
        return cls.factory(val)

@classmethod
def factory(cls, val):
    private = {'var': 'test'}

    class InnerB(object):
        def __init__(self):
            self.variable = val
            pass

        @property
        def var(self):
            return private['var']

    return InnerB()

Creating a file only if it doesn't exist in Node.js

This method is no longer recommended. fs.exists is deprecated. See comments.

Here are some options:

1) Have 2 "fs" calls. The first one is the "fs.exists" call, and the second is "fs.write / read, etc"

//checks if the file exists. 
//If it does, it just calls back.
//If it doesn't, then the file is created.
function checkForFile(fileName,callback)
{
    fs.exists(fileName, function (exists) {
        if(exists)
        {
            callback();
        }else
        {
            fs.writeFile(fileName, {flag: 'wx'}, function (err, data) 
            { 
                callback();
            })
        }
    });
}

function writeToFile()
{
    checkForFile("file.dat",function()
    {
       //It is now safe to write/read to file.dat
       fs.readFile("file.dat", function (err,data) 
       {
          //do stuff
       });
    });
}

2) Or Create an empty file first:

--- Sync:

//If you want to force the file to be empty then you want to use the 'w' flag:

var fd = fs.openSync(filepath, 'w');

//That will truncate the file if it exists and create it if it doesn't.

//Wrap it in an fs.closeSync call if you don't need the file descriptor it returns.

fs.closeSync(fs.openSync(filepath, 'w'));

--- ASync:

var fs = require("fs");
fs.open(path, "wx", function (err, fd) {
    // handle error
    fs.close(fd, function (err) {
        // handle error
    });
});

3) Or use "touch": https://github.com/isaacs/node-touch

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Try:

cl /v

Actually, any time I give cl an argument, it prints out the version number on the first line.

You could just feed it a garbage argument and then parse the first line of the output, which contains the verison number.

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

This error is occur,because the function is not defined. In my case i have called the datepicker function without including the datepicker js file that time I got this error.

How to convert a String to Bytearray

String.prototype.encodeHex = function () {
    return this.split('').map(e => e.charCodeAt())
};

String.prototype.decodeHex = function () {    
    return this.map(e => String.fromCharCode(e)).join('')
};

How do I iterate over a range of numbers defined by variables in Bash?

You can use

for i in $(seq $END); do echo $i; done

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an array but got an object?

In order to handle arrays with the $resource service, it's suggested that you use the query method. As you can see below, the query method is built to handle arrays.

    { 'get':    {method:'GET'},
      'save':   {method:'POST'},
      'query':  {method:'GET', isArray:true},
      'remove': {method:'DELETE'},
      'delete': {method:'DELETE'} 
   };

User $resource("apiUrl").query();

make iframe height dynamic based on content inside- JQUERY/Javascript

The simple solution is to measure the width and height of the content area, and then use those measurements to calculate the bottom padding percentage.

In this case, the measurements are 1680 x 720 px, so the padding on the bottom is 720 / 1680 = 0.43 * 100, which comes out to 43%.

.canvas-container {    
    position: relative;
    padding-bottom: 43%; // (720 ÷ 1680 = 0.4286 = 43%)
    height: 0;
    overflow: hidden;   
}

.canvas-container iframe {    
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;   
}

How to generate random float number in C

Try:

float x = (float)rand()/(float)(RAND_MAX/a);

To understand how this works consider the following.

N = a random value in [0..RAND_MAX] inclusively.

The above equation (removing the casts for clarity) becomes:

N/(RAND_MAX/a)

But division by a fraction is the equivalent to multiplying by said fraction's reciprocal, so this is equivalent to:

N * (a/RAND_MAX)

which can be rewritten as:

a * (N/RAND_MAX)

Considering N/RAND_MAX is always a floating point value between 0.0 and 1.0, this will generate a value between 0.0 and a.

Alternatively, you can use the following, which effectively does the breakdown I showed above. I actually prefer this simply because it is clearer what is actually going on (to me, anyway):

float x = ((float)rand()/(float)(RAND_MAX)) * a;

Note: the floating point representation of a must be exact or this will never hit your absolute edge case of a (it will get close). See this article for the gritty details about why.

Sample

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(int argc, char *argv[])
{
    srand((unsigned int)time(NULL));

    float a = 5.0;
    for (int i=0;i<20;i++)
        printf("%f\n", ((float)rand()/(float)(RAND_MAX)) * a);
    return 0;
}

Output

1.625741
3.832026
4.853078
0.687247
0.568085
2.810053
3.561830
3.674827
2.814782
3.047727
3.154944
0.141873
4.464814
0.124696
0.766487
2.349450
2.201889
2.148071
2.624953
2.578719

Auto Generate Database Diagram MySQL

Here is a tool that generates relational diagrams from MySQL (on Windows at the moment). I have used it on a database with 400 tables. If the diagram is too big for a single diagram, it gets broken down into smaller ones. So you will probably end up with multiple diagrams and you can navigate between them by right clicking. It is all explained in the link below. The tool is free (as in free beer), the author uses it himself on consulting assignments, and lets other people use it. http://www.scmlite.com/Quick%20overview

Entity Framework change connection at runtime

The created class is 'partial'!

public partial class Database1Entities1 : DbContext
{
    public Database1Entities1()
        : base("name=Database1Entities1")
    {
    }

... and you call it like this:

using (var ctx = new Database1Entities1())
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

so, you need only create a partial own class file for original auto-generated class (with same class name!) and add a new constructor with connection string parameter, like Moho's answer before.

After it you able to use parametrized constructor against original. :-)

example:

using (var ctx = new Database1Entities1(myOwnConnectionString))
      {
        #if DEBUG
        ctx.Database.Log = Console.Write;
        #endif

How to return a file using Web API?

Better to return HttpResponseMessage with StreamContent inside of it.

Here is example:

public HttpResponseMessage GetFile(string id)
{
    if (String.IsNullOrEmpty(id))
        return Request.CreateResponse(HttpStatusCode.BadRequest);

    string fileName;
    string localFilePath;
    int fileSize;

    localFilePath = getFileFromID(id, out fileName, out fileSize);

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
    response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    response.Content.Headers.ContentDisposition.FileName = fileName;
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");

    return response;
}

UPD from comment by patridge: Should anyone else get here looking to send out a response from a byte array instead of an actual file, you're going to want to use new ByteArrayContent(someData) instead of StreamContent (see here).

How to call any method asynchronously in c#

Here's a way to do it:

// The method to call
void Foo()
{
}


Action action = Foo;
action.BeginInvoke(ar => action.EndInvoke(ar), null);

Of course you need to replace Action by another type of delegate if the method has a different signature

How to select different app.config for several build configurations

Using the same as approach as Romeo, I adapted it to Visual Studio 2010 :

 <None Condition=" '$(Configuration)' == 'Debug' " Include="appDebug\App.config" />

 <None Condition=" '$(Configuration)' == 'Release' " Include="appRelease\App.config" />

Here you need to keep both App.config files in different directories (appDebug and appRelease). I tested it and it works fine!

How to get a index value from foreach loop in jstl

use varStatus to get the index c:forEach varStatus properties

<c:forEach var="categoryName" items="${categoriesList}" varStatus="loop">
    <li><a onclick="getCategoryIndex(${loop.index})" href="#">${categoryName}</a></li>
</c:forEach>

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I got the same problem and I have read that this happened in Samsung phones only...But the reality showed that this happens in a lot of brands.

After testing I realized that this happens only when you scroll fast the RecyclerView and then you go back either with the back button or the Up button. So I put inside Up button and onBackpressed the below snippet:

someList = new ArrayList<>();
mainRecyclerViewAdapter = new MainRecyclerViewAdapter(this, someList, this);
recyclerViewMain.setAdapter(mainRecyclerViewAdapter);
finish();

With this solution you just load a new Arraylist to the adapter and new adapter to recyclerView and then you finish activity.

Hope it helps someone

SQLPLUS error:ORA-12504: TNS:listener was not given the SERVICE_NAME in CONNECT_DATA

I ran into the exact same problem under identical circumstances. I don't have the tnsnames.ora file, and I wanted to use SQL*Plus with Easy Connection Identifier format in command line. I solved this problem as follows.

The SQL*Plus® User's Guide and Reference gives an example:

sqlplus hr@\"sales-server:1521/sales.us.acme.com\"

Pay attention to two important points:

  1. The connection identifier is quoted. You have two options:
    1. You can use SQL*Plus CONNECT command and simply pass quoted string.
    2. If you want to specify connection parameters on the command line then you must add backslashes as shields before quotes. It instructs the bash to pass quotes into SQL*Plus.
  2. The service name must be specified in FQDN-form as it configured by your DBA.

I found these good questions to detect service name via existing connection: 1, 2. Try this query for example:

SELECT value FROM V$SYSTEM_PARAMETER WHERE UPPER(name) = 'SERVICE_NAMES'

How to commit to remote git repository

You just need to make sure you have the rights to push to the remote repository and do

git push origin master

or simply

git push

Show tables, describe tables equivalent in redshift

You can simply use the command below to describe a table.

desc table-name

or

desc schema-name.table-name

TSQL How do you output PRINT in a user defined function?

I got around this by temporarily rewriting my function to something like this:

IF OBJECT_ID ('[dbo].[fx_dosomething]', 'TF') IS NOT NULL
  drop function [dbo].[fx_dosomething];
GO

create FUNCTION dbo.fx_dosomething ( @x numeric )
returns @t table (debug varchar(100), x2 numeric)
as
begin
 declare @debug varchar(100)
 set @debug = 'printme';

 declare @x2 numeric
 set @x2 = 0.123456;

 insert into @t values (@debug, @x2)
 return 
end
go

select * from fx_dosomething(0.1)

Difference between x86, x32, and x64 architectures?

x86 refers to the Intel processor architecture that was used in PCs. Model numbers were 8088 (8 bit bus version of 8086 and used in the first IBM PC), 8086, 286, 386, 486. After which they switched to names instead of numbers to stop AMD from copying the processor names. Pentium etc, never a Hexium :).

x64 is the architecture name for the extensions to the x86 instruction set that enable 64-bit code. Invented by AMD and later copied by Intel when they couldn't get their own 64-bit arch to be competitive, Itanium didn't fare well. Other names for it are x86_64, AMD's original name and commonly used in open source tools. And amd64, AMD's next name and commonly used in Microsoft tools. Intel's own names for it (EM64T and "Intel 64") never caught on.

x32 is a fuzzy term that's not associated with hardware. It tends to be used to mean "32-bit" or "32-bit pointer architecture", Linux has an ABI by that name.

The type must be a reference type in order to use it as parameter 'T' in the generic type or method

I can't repro, but I suspect that in your actual code there is a constraint somewhere that T : class - you need to propagate that to make the compiler happy, for example (hard to say for sure without a repro example):

public class Derived<SomeModel> : Base<SomeModel> where SomeModel : class, IModel
                                                                    ^^^^^
                                                                 see this bit

Failed to load ApplicationContext (with annotation)

In my case, I had to do the following while running with Junit5

@SpringBootTest(classes = {abc.class}) @ExtendWith(SpringExtension.class

Here abc.class was the class that was being tested

How to call code behind server method from a client side JavaScript function?

JS Code:

<script type="text/javascript">
         function ShowCurrentTime(name) {
         PageMethods.GetCurrentTime(name, OnSuccess);
         }
         function OnSuccess(response, userContext, methodName) {
          alert(response);
         }
</script>

HTML Code:

<asp:ImageButton ID="IMGBTN001" runat="server" ImageUrl="Images/ico/labaniat.png"
class="img-responsive em-img-lazy" OnClientClick="ShowCurrentTime('01')" />

Code Behind C#

[System.Web.Services.WebMethod]
public static string GetCurrentTime(string name)
{
    return "Hello " + name + Environment.NewLine + "The Current Time is: "
            + DateTime.Now.ToString();
}

Table fixed header and scrollable body

For tables that are full height (the page scrolls, not the table)

Note: I move the whole <thead>...</thead> beause In my case I had two rows (Title and filters)

With JS (jQuery)

$( function() {

            let marginTop = 0; // Add margin if the page has a top nav-bar
            let $thead = $('.table-fixed-head').find('thead');
            let offset = $thead.first().offset().top - marginTop;
            let lastPos = 0;

            $(window).on('scroll', function () {

                if ( window.scrollY > offset )
                {
                    if ( lastPos === 0 )
                    {
                        // Add a class for styling
                        $thead.addClass('floating-header');
                    }

                    lastPos = window.scrollY - offset;
                    $thead.css('transform', 'translateY(' + ( lastPos ) + 'px)');
                }
                else if ( lastPos !== 0 )
                {
                    lastPos = 0;
                    $thead.removeClass('floating-header');
                    $thead.css('transform', 'translateY(' + 0 + 'px)');
                }
            });
});

CSS (Just for styling)

 thead.floating-header>tr>th {
       background-color: #efefef;
 }

thead.floating-header>tr:last-child>th {
       border-bottom: 1px solid #aaa;
}

Chrome hangs after certain amount of data transfered - waiting for available socket

Our first thought is that the site is down or the like, but the truth is that this is not the problem or disability. Nor is it a problem because a simple connection when tested under Firefox, Opera or services Explorer open as normal.

The error in Chrome displays a sign that says "This site is not available" and clarification with the legend "Error 15 (net :: ERR_SOCKET_NOT_CONNECTED): Unknown error". The error is quite usual in Google Chrome, more precisely in its updates, and its workaround is to restart the computer.

As partial solutions are not much we offer a tutorial for you solve the fault in less than a minute. To avoid this problem and ensure that services are normally open in Google Chrome should insert the following into the address bar: chrome: // net-internals (then give "Enter"). They then have to go to the "Socket" in the left menu and choose "Flush Socket Pools" (look at the following screenshots to guide http://www.fixotip.com/how-to-fix-error-waiting-for-available-sockets-in-google-chrome/) This has the problem solved and no longer will experience problems accessing Gmail, Google or any of the services of the Mountain View giant. I hope you found it useful and share the tutorial with whom they need or social networks: Facebook, Twitter or Google+.

Convert String to Date in MS Access Query

If you need to display all the records after 2014-09-01, add this to your query:

SELECT * FROM Events
WHERE Format(Events.DATE_TIME,'yyyy-MM-dd hh:mm:ss')  >= Format("2014-09-01 00:00:00","yyyy-MM-dd hh:mm:ss")

How do I set the default schema for a user in MySQL

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

How can I install a .ipa file to my iPhone simulator

For Xcode 10, here's an easy way that worked for me for a debug IPA (development profiles)

  1. Unzip the IPA to get the Payload folder.
  2. Within the Payload folder is the app executable.
  3. Drag and drop the app to an open simulator. (You might see a green add button when you drag it over the simulator)

It should install that app on that simulator.

Foreign Key Django Model

You create the relationships the other way around; add foreign keys to the Person type to create a Many-to-One relationship:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(
        Address, on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person entries.

Anniversary and Address objects will be given a reverse, backwards relationship too; by default it'll be called person_set but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.

Auto detect mobile browser (via user-agent?)

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Browser.IsMobileDevice == true)
    {
        Response.Redirect("Mobile//home.aspx");
    }
}

This example works in asp.net

How to send list of file in a folder to a txt file in Linux

you can just use

ls > filenames.txt

(usually, start a shell by using "Terminal", or "shell", or "Bash".) You may need to use cd to go to that folder first, or you can ls ~/docs > filenames.txt

How can I put CSS and HTML code in the same file?

Two options: 1, add css inline like style="background:black" Or 2. In the head include the css as a style tag block.

generate days from date range

Procedure + temporary table:

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `days`(IN dateStart DATE, IN dateEnd DATE)
BEGIN

    CREATE TEMPORARY TABLE IF NOT EXISTS date_range (day DATE);

    WHILE dateStart <= dateEnd DO
      INSERT INTO date_range VALUES (dateStart);
      SET dateStart = DATE_ADD(dateStart, INTERVAL 1 DAY);
    END WHILE;

    SELECT * FROM date_range;
    DROP TEMPORARY TABLE IF EXISTS date_range;

END

Invalid default value for 'dateAdded'

Change the type from datetime to timestamp and it will work! I had the same issue for mysql 5.5.56-MariaDB - MariaDB Server Hope it can help... sorry if depricated

VARCHAR to DECIMAL

My explanation is in the code. :)

DECLARE @TestConvert VARCHAR(MAX) = '123456789.1234567'
BEGIN TRY
    SELECT CAST(@TestConvert AS DECIMAL(10, 4))
END TRY
BEGIN CATCH
    SELECT 'The reason you get the message "' + ERROR_MESSAGE() + '" is because DECIMAL(10, 4) only allows for 4 numbers after the decimal.'
END CATCH

-- Here's one way to truncate the string to a castable value.
SELECT CAST(LEFT(@TestConvert, (CHARINDEX('.', @TestConvert, 1) + 4)) AS DECIMAL(14, 4))

-- If you noticed, I changed it to DECIMAL(14, 4) instead of DECIMAL(10, 4) That's because this number has 14 digits, as proven below.
-- Read this for a better explanation as to what precision, scale and length mean: http://msdn.microsoft.com/en-us/library/ms190476(v=sql.105).aspx
SELECT LEN(LEFT(@TestConvert, (CHARINDEX('.', @TestConvert, 1) + 4)))

Android XXHDPI resources

As per this PPI calculation tool, Google Nexus 10 has a display density of about 300 DPI...

However, Android documentation states that:

ldpi : ~120dpi mdpi : ~160dpi hdpi : ~240dpi xhdpi : ~320dpi xxhdpi is not specified.

I think we just let Android OS scale up xhdpi resources...

Java - sending HTTP parameters via POST method easily

For those having trouble receiving the request on a php page using $_POST because you expect key-value pairs:

While all the answers where very helpful, I lacked some basic understanding on which string actually to post, since in the old apache HttpClient I used

new UrlEncodedFormEntity(nameValuePairs); (Java)

and then could use $_POST in php do get the key-value pairs.

To my understanding now one has build that string manually before posting. So the string needs to look like

val data = "key1=val1&key2=val2"

but instead just adding it to the url it is posted (in the header).

The alternative would be to use a json-string instead:

val data = "{\"key1\":\"val1\",\"key2\":\"val2\"}" // {"key1":"val1","key2":"val2"}

and pull it in php without $_POST:

$json_params = file_get_contents('php://input');
// echo_p("Data: $json_params");
$data = json_decode($json_params, true);

Here you find a sample code in Kotlin:

class TaskDownloadTest : AsyncTask<Void, Void, Void>() {
    override fun doInBackground(vararg params: Void): Void? {
        var urlConnection: HttpURLConnection? = null

        try {

            val postData = JsonObject()
            postData.addProperty("key1", "val1")
            postData.addProperty("key2", "val2")

            // reformat json to key1=value1&key2=value2
            // keeping json because I may change the php part to interpret json requests, could be a HashMap instead
            val keys = postData.keySet()
            var request = ""
            keys.forEach { key ->
                // Log.i("data", key)
                request += "$key=${postData.get(key)}&"
            }
            request = request.replace("\"", "").removeSuffix("&")
            val requestLength = request.toByteArray().size
            // Warning in Android 9 you need to add a line in the application part of the manifest: android:usesCleartextTraffic="true"
            // https://stackoverflow.com/questions/45940861/android-8-cleartext-http-traffic-not-permitted
            val url = URL("http://10.0.2.2/getdata.php")
            urlConnection = url.openConnection() as HttpURLConnection
            // urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded") // apparently default
            // Not sure what these are for, I do not use them
            // urlConnection.setRequestProperty("Content-Type", "application/json")
            // urlConnection.setRequestProperty("Key","Value")
            urlConnection.readTimeout = 5000
            urlConnection.connectTimeout = 5000
            urlConnection.requestMethod = "POST"
            urlConnection.doOutput = true
            // urlConnection.doInput = true
            urlConnection.useCaches = false
            urlConnection.setFixedLengthStreamingMode(requestLength)
            // urlConnection.setChunkedStreamingMode(0) // if you do not want to handle request length which is fine for small requests

            val out = urlConnection.outputStream
            val writer = BufferedWriter(
                OutputStreamWriter(
                    out, "UTF-8"
                )
            )
            writer.write(request)
            // writer.write("{\"key1\":\"val1\",\"key2\":\"val2\"}") // {"key1":"val1","key2":"val2"} JsonFormat or just postData.toString() for $json_params=file_get_contents('php://input'); json_decode($json_params, true); in php
            // writer.write("key1=val1&key2=val2") // key=value format for $_POST in php
            writer.flush()
            writer.close()
            out.close()

            val code = urlConnection.responseCode
            if (code != 200) {
                throw IOException("Invalid response from server: $code")
            }

            val rd = BufferedReader(
                InputStreamReader(
                    urlConnection.inputStream
                )
            )
            var line = rd.readLine()
            while (line != null) {
                Log.i("data", line)
                line = rd.readLine()
            }
        } catch (e: Exception) {
            e.printStackTrace()
        } finally {
            urlConnection?.disconnect()
        }

        return null
    }
}

Converting string to Date and DateTime

For first Date

$_firstDate = date("m-d-Y", strtotime($_yourDateString));

For New Date

$_newDate = date("Y-m-d",strtotime($_yourDateString));

How to autowire RestTemplate using annotations

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

@Configuration
public class RestTemplateClient {
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }
}

How to append elements at the end of ArrayList in Java?

I ran into a similar problem and just passed the end of the array to the ArrayList.add() index param like so:

public class Stack {

    private ArrayList<String> stringList = new ArrayList<String>();

    RandomStringGenerator rsg = new RandomStringGenerator();

    private void push(){
        String random = rsg.randomStringGenerator();
        stringList.add(stringList.size(), random);
    }

}

How to set Java environment path in Ubuntu

Step1:

sudo gedit ~/.bash_profile

Step2:

JAVA_HOME=/home/user/tool/jdk-8u201-linux-x64/jdk1.8.0_201
PATH=$PATH:$HOME/bin:$JAVA_HOME/bin
export JAVA_HOME
export JRE_HOME
export PATH

Step3:

source ~/.bash_profile

How to replace all dots in a string using JavaScript

String.prototype.replaceAll = function (needle, replacement) {
    return this.replace(new RegExp(needle, 'g'), replacement);
};

android: changing option menu items programmatically

To disable certain items:

MenuItem item = menu.findItem(R.id.ID_ASSING_TO_THE_ITEM_IN_MENU_XML);
item.setEnabled(false);

How to wait for all threads to finish, using ExecutorService?

In Java8 you can do it with CompletableFuture:

ExecutorService es = Executors.newFixedThreadPool(4);
List<Runnable> tasks = getTasks();
CompletableFuture<?>[] futures = tasks.stream()
                               .map(task -> CompletableFuture.runAsync(task, es))
                               .toArray(CompletableFuture[]::new);
CompletableFuture.allOf(futures).join();    
es.shutdown();

pdftk compression option

In case you want to compress a PDF which contains a lot of selectable text, on Windows you can use NicePDF Compressor - choose "Flate" option. After trying everything (cpdf, pdftk, gs) it finally helped me to compress my 1360 pages PDF from 500 MB down to 10 MB.

Using Excel VBA to export data to MS Access table

is it possible to export without looping through all records

For a range in Excel with a large number of rows you may see some performance improvement if you create an Access.Application object in Excel and then use it to import the Excel data into Access. The code below is in a VBA module in the same Excel document that contains the following test data

SampleData.png

Option Explicit

Sub AccImport()
    Dim acc As New Access.Application
    acc.OpenCurrentDatabase "C:\Users\Public\Database1.accdb"
    acc.DoCmd.TransferSpreadsheet _
            TransferType:=acImport, _
            SpreadSheetType:=acSpreadsheetTypeExcel12Xml, _
            TableName:="tblExcelImport", _
            Filename:=Application.ActiveWorkbook.FullName, _
            HasFieldNames:=True, _
            Range:="Folio_Data_original$A1:B10"
    acc.CloseCurrentDatabase
    acc.Quit
    Set acc = Nothing
End Sub

AngularJS ng-repeat handle empty list case

You can use this ng-switch:

<div ng-app ng-controller="friendsCtrl">
  <label>Search: </label><input ng-model="searchText" type="text">
  <div ng-init="filtered = (friends | filter:searchText)">
  <h3>'Found '{{(friends | filter:searchText).length}} friends</h3>
  <div ng-switch="(friends | filter:searchText).length">
    <span class="ng-empty" ng-switch-when="0">No friends</span>
    <table ng-switch-default>
      <thead>  
        <tr>
          <th>Name</th>
          <th>Phone</th>
        </tr>
      </thead>
      <tbody>
      <tr ng-repeat="friend in friends | filter:searchText">
        <td>{{friend.name}}</td>
        <td>{{friend.phone}}</td>
      </tr>
    </tbody>
  </table>
</div>

Insert into ... values ( SELECT ... FROM ... )

Claude Houle's answer: should work fine, and you can also have multiple columns and other data as well:

INSERT INTO table1 ( column1, column2, someInt, someVarChar )
SELECT  table2.column1, table2.column2, 8, 'some string etc.'
FROM    table2
WHERE   table2.ID = 7;

I've only used this syntax with Access, SQL 2000/2005/Express, MySQL, and PostgreSQL, so those should be covered. It should also work with SQLite3.

rand() returns the same number each time the program is run

You need to "seed" the generator. Check out this short video, it will clear things up.

https://www.thenewboston.com/videos.php?cat=16&video=17503

Find the max of 3 numbers in Java with different data types

You can do like this:

public static void main(String[] args) {

    int x=2 , y=7, z=14;
    int max1= Math.max(x,y);

    System.out.println("Max value is: "+ Math.max(max1, z)); 
}  

How to read request body in an asp.net core webapi controller?

I also wanted to read the Request.Body without automatically map it to some action parameter model. Tested a lot of different ways before solved this. And I didn´t find any working solution described here. This solution is currently based on the .NET Core 3.0 framework.

reader.readToEnd() seamed like a simple way, even though it compiled, it throwed an runtime exception required me to use async call. So instead I used ReadToEndAsync(), however it worked sometimes, and sometimes not. Giving me errors like, cannot read after stream is closed. The problem is that we cannot guarantee that it will return the result in the same thread (even if we use the await). So we need some kind of callback. This solution worked for me.

[Route("[controller]/[action]")]
public class MyController : ControllerBase
{

    // ...

    [HttpPost]
    public async void TheAction()
    {
        try
        {
            HttpContext.Request.EnableBuffering();
            Request.Body.Position = 0;
            using (StreamReader stream = new StreamReader(HttpContext.Request.Body))
            {
                var task = stream
                    .ReadToEndAsync()
                    .ContinueWith(t => {
                        var res = t.Result;
                        // TODO: Handle the post result!
                    });

                // await processing of the result
                task.Wait();
            }
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "Failed to handle post!");
        }
    }

How to write string literals in python without having to escape them?

Raw string literals:

>>> r'abc\dev\t'
'abc\\dev\\t'

Process escape sequences in a string in Python

The (currently) accepted answer by Jerub is correct for python2, but incorrect and may produce garbled results (as Apalala points out in a comment to that solution), for python3. That's because the unicode_escape codec requires its source to be coded in latin-1, not utf-8, as per the official python docs. Hence, in python3 use:

>>> myString="špåm\\nëðþ\\x73"
>>> print(myString)
špåm\nëðþ\x73
>>> decoded_string = myString.encode('latin-1','backslashreplace').decode('unicode_escape')
>>> print(decoded_string)
špåm
ëðþs

This method also avoids the extra unnecessary roundtrip between strings and bytes in metatoaster's comments to Jerub's solution (but hats off to metatoaster for recognizing the bug in that solution).

Is there a limit on number of tcp/ip connections between machines on linux?

You might wanna check out /etc/security/limits.conf

Create a 3D matrix

Create a 3D matrix

A = zeros(20, 10, 3);   %# Creates a 20x10x3 matrix

Add a 3rd dimension to a matrix

B = zeros(4,4);  
C = zeros(size(B,1), size(B,2), 4);  %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B;                        %# Copy the content of B into C's first set of values

zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0 for a 3D matrix. To confirm the size of your matrices you can run: size(A) which gives 20 10 3.

There is no explicit bound on the number of dimensions a matrix may have.

How to remove all duplicate items from a list

Just make a new list to populate, if the item for your list is not yet in the new list input it, else just move on to the next item in your original list.

for i in mylist:
  if i not in newlist:
    newlist.append(i)

I think this is the correct syntax, but my python is a bit shaky, I hope you at least get the idea.

wordpress contactform7 textarea cols and rows change in smaller screens

Add it after Placeholder attribute.

[textarea* message id:message class:form-control 40x7 placeholder "Message"]

ASP.NET Button to redirect to another page

You can either do a Response.Redirect("YourPage.aspx"); or a Server.Transfer("YourPage.aspx"); on your button click event. So it's gonna be like the following:

protected void btnConfirm_Click(object sender, EventArgs e)
{
    Response.Redirect("YourPage.aspx");
    //or
    Server.Transfer("YourPage.aspx");
}

How to extract the decimal part from a floating point number in C?

I created a subroutine one using a double float, it returns 2 integer values.


void double2Ints(double f, int p, int *i, int *d)
{ 
  // f = float, p=decimal precision, i=integer, d=decimal
  int   li; 
  int   prec=1;

  for(int x=p;x>0;x--) 
  {
    prec*=10;
  };  // same as power(10,p)

  li = (int) f;              // get integer part
  *d = (int) ((f-li)*prec);  // get decimal part
  *i = li;
}

void test()
{ 
  double df = 3.14159265;
  int   i,d;
  for(int p=2;p<9;p++)
  {
    double2Ints(df, p, &i,&d); printf("d2i (%d) %f = %d.%d\r\n",p, df,i,d);
  }
}

How do I put double quotes in a string in vba?

I prefer the answer of tabSF . implementing the same to your answer. here below is my approach

Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"

jQuery : select all element with custom attribute

Use the "has attribute" selector:

$('p[MyTag]')

Or to select one where that attribute has a specific value:

$('p[MyTag="Sara"]')

There are other selectors for "attribute value starts with", "attribute value contains", etc.

How to set environment variable for everyone under my linux system?

Every process running under the Linux kernel receives its own, unique environment that it inherits from its parent. In this case, the parent will be either a shell itself (spawning a sub shell), or the 'login' program (on a typical system).

As each process' environment is protected, there is no way to 'inject' an environmental variable to every running process, so even if you modify the default shell .rc / profile, it won't go into effect until each process exits and reloads its start up settings.

Look in /etc/ to modify the default start up variables for any particular shell. Just realize that users can (and often do) change them in their individual settings.

Unix is designed to obey the user, within limits.

NB: Bash is not the only shell on your system. Pay careful attention to what the /bin/sh symbolic link actually points to. On many systems, this could actually be dash which is (by default, with no special invocation) POSIXLY correct. Therefore, you should take care to modify both defaults, or scripts that start with /bin/sh will not inherit your global defaults. Similarly, take care to avoid syntax that only bash understands when editing both, aka avoiding bashisms.

IntelliJ IDEA generating serialVersionUID

Add a live template called "ser" to the other group, set it to "Applicable in Java: declaration", and untick "Shorten FQ names". Give it a template text of just:

$serial$

Now edit variables and set serial to:

groovyScript("(System.env.JDK_HOME+'/bin/serialver -classpath '+com.intellij.openapi.fileEditor.FileDocumentManager.instance.getFile(_editor.document).path.replaceAll('/java/.*','').replaceAll('/src/','/build/classes/')+' '+_1).execute().text.replaceAll('.*: *','')",qualifiedClassName())

It assumes the standard Gradle project layout. Change /build/ to /target/ for Maven.

How do I undo the most recent local commits in Git?

To undo your local commit you use git reset <commit>. Also that tutorial is very helpful to show you how it works.

Alternatively, you can use git revert <commit>: reverting should be used when you want to add another commit that rolls back the changes (but keeps them in the project history).

Array copy values to keys in PHP

$final_array = array_combine($a, $a);

Reference: http://php.net/array-combine

P.S. Be careful with source array containing duplicated keys like the following:

$a = ['one','two','one'];

Note the duplicated one element.

What version of Java is running in Eclipse?

The one the eclipse run in is the default java installed in the system (unless set specifically in the eclipse.ini file, use the -vm option). You can of course add more Java runtimes and use them for your projects

The string you've written is the right one, but it is specific to your environment. If you want to know the exact update then run the following code:

public class JavaVersion {
  public static void main(String[] args) {
    System.out.println(System.getProperty("java.runtime.version"));
  }
}

Inserting NOW() into Database with CodeIgniter's Active Record

putting NOW() in quotes won't work as Active Records will put escape the NOW() into a string and tries to push it into the db as a string of "NOW()"... you will need to use

$this->db->set('time', 'NOW()', FALSE); 

to set it correctly.

you can always check your sql afterward with

$this->db->last_query();

Dynamically set value of a file input

I had similar problem, then I tried writing this from JavaScript and it works! : referenceToYourInputFile.value = "" ;

git reset --hard HEAD leaves untracked files behind

User interactive approach:

git clean -i -fd

Remove .classpath [y/N]? N
Remove .gitignore [y/N]? N
Remove .project [y/N]? N
Remove .settings/ [y/N]? N
Remove src/com/amazon/arsdumpgenerator/inspector/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/s3/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/s3/ [y/N]? y

-i for interactive
-f for force
-d for directory
-x for ignored files(add if required)

Note: Add -n or --dry-run to just check what it will do.

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

It is simple just write java -XshowSettings:properties on your command line in windows and then paste all the files in the path shown by the java.library.path.

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

How to check file MIME type with javascript before upload?

As Drake states this could be done with FileReader. However, what I present here is a functional version. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for other formats you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.

open program minimized via command prompt

Try:

start  "" "C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE" --new-window/min

I had the same problem, but I was trying to open chrome.exe maximized. If I put the /min anywhere else in the command line, like before or after the empty title, it was ignored.

How can I remove the last character of a string in python?

Answering the question: to remove the last character, just use:string = string[:-1].

If you want to remove the last '\' if there is one (or if there is more than one):

while string[-1]=='\\':
    string = string[:-1]

If it's a path, then use the os.path functions:

dir = "dir1\\dir2\\file.jpg\\"   #I'm using windows by the way
os.path.dirname(dir)

although I would 'add' a slash in the end to prevent missing the filename in case there's no slash at the end of the original string:

dir = "dir1\\dir2\\file.jpg"
os.path.dirname(dir + "\\")

When using abspath, (if the path isn't absolute I guess,) will add the current working directory to the path.

os.path.abspath(dir)

Read file data without saving it in Flask

I share my solution (assuming everything is already configured to connect to google bucket in flask)

from google.cloud import storage

@app.route('/upload/', methods=['POST'])
def upload():
    if request.method == 'POST':
        # FileStorage object wrapper
        file = request.files["file"]                    
        if file:
            os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = app.config['GOOGLE_APPLICATION_CREDENTIALS']
            bucket_name = "bucket_name" 
            storage_client = storage.Client()
            bucket = storage_client.bucket(bucket_name)
            # Upload file to Google Bucket
            blob = bucket.blob(file.filename) 
            blob.upload_from_string(file.read())

My post

Direct to Google Bucket in flask

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

With Angular CLI 6 you need to use builders as ng eject is deprecated and will soon be removed in 8.0. That's what it says when I try to do an ng eject

enter image description here

You can use angular-builders package (https://github.com/meltedspark/angular-builders) to provide your custom webpack config.

I have tried to summarize all in a single blog post on my blog - How to customize build configuration with custom webpack config in Angular CLI 6

but essentially you add following dependencies -

  "devDependencies": {
    "@angular-builders/custom-webpack": "^7.0.0",
    "@angular-builders/dev-server": "^7.0.0",
    "@angular-devkit/build-angular": "~0.11.0",

In angular.json make following changes -

  "architect": {
    "build": {
      "builder": "@angular-builders/custom-webpack:browser",
      "options": {
        "customWebpackConfig": {"path": "./custom-webpack.config.js"},

Notice change in builder and new option customWebpackConfig. Also change

    "serve": {
      "builder": "@angular-builders/dev-server:generic",

Notice the change in builder again for serve target. Post these changes you can create a file called custom-webpack.config.js in your same root directory and add your webpack config there.

However, unlike ng eject configuration provided here will be merged with default config so just add stuff you want to edit/add.

How to compare character ignoring case in primitive types

You have to consider the Turkish I problem when comparing characters/ lowercasing / uppercasing:

I suggest to convert to String and use toLowerCase with invariant culture (in most cases at least).

public final static Locale InvariantLocale = new Locale(Empty, Empty, Empty); str.toLowerCase(InvariantLocale)

See similar C# string.ToLower() and string.ToLowerInvariant()

Note: Don't use String.equalsIgnoreCase http://nikolajlindberg.blogspot.co.il/2008/03/beware-of-java-comparing-turkish.html

What is the cleanest way to disable CSS transition effects temporarily?

does

$('#elem').css('-webkit-transition','none !important'); 

in your js kill it?

obviously repeat for each.

What is com.sun.proxy.$Proxy

  1. Proxies are classes that are created and loaded at runtime. There is no source code for these classes. I know that you are wondering how you can make them do something if there is no code for them. The answer is that when you create them, you specify an object that implements InvocationHandler, which defines a method that is invoked when a proxy method is invoked.

  2. You create them by using the call

    Proxy.newProxyInstance(classLoader, interfaces, invocationHandler)
    

    The arguments are:

    1. classLoader. Once the class is generated, it is loaded with this class loader.
    2. interfaces. An array of class objects that must all be interfaces. The resulting proxy implements all of these interfaces.
    3. invocationHandler. This is how your proxy knows what to do when a method is invoked. It is an object that implements InvocationHandler. When a method from any of the supported interfaces, or hashCode, equals, or toString, is invoked, the method invoke is invoked on the handler, passing the Method object for the method to be invoked and the arguments passed.

    For more on this, see the documentation for the Proxy class.

  3. Every implementation of a JVM after version 1.3 must support these. They are loaded into the internal data structures of the JVM in an implementation-specific way, but it is guaranteed to work.

Regex pattern for checking if a string starts with a certain substring?

For the extension method fans:

public static bool RegexStartsWith(this string str, params string[] patterns)
{
    return patterns.Any(pattern => 
       Regex.Match(str, "^("+pattern+")").Success);
}

Usage

var answer = str.RegexStartsWith("mailto","ftp","joe");
//or
var answer2 = str.RegexStartsWith("mailto|ftp|joe");
//or
bool startsWithWhiteSpace = "  does this start with space or tab?".RegexStartsWith(@"\s");

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

int &z = 12;

On the right hand side, a temporary object of type int is created from the integral literal 12, but the temporary cannot be bound to non-const reference. Hence the error. It is same as:

int &z = int(12); //still same error

Why a temporary gets created? Because a reference has to refer to an object in the memory, and for an object to exist, it has to be created first. Since the object is unnamed, it is a temporary object. It has no name. From this explanation, it became pretty much clear why the second case is fine.

A temporary object can be bound to const reference, which means, you can do this:

const int &z = 12; //ok

C++11 and Rvalue Reference:

For the sake of the completeness, I would like to add that C++11 has introduced rvalue-reference, which can bind to temporary object. So in C++11, you can write this:

int && z = 12; //C+11 only 

Note that there is && intead of &. Also note that const is not needed anymore, even though the object which z binds to is a temporary object created out of integral-literal 12.

Since C++11 has introduced rvalue-reference, int& is now henceforth called lvalue-reference.

Getting Lat/Lng from Google marker

There are a lot of answers to this question, which never worked for me (including suggesting getPosition() which doesn't seem to be a method available for markers objects). The only method that worked for me in maps V3 is (simply) :

var lat = marker.lat();
var long = marker.lng();

Getting values from JSON using Python

What error is it giving you?

If you do exactly this:

data = json.loads('{"lat":444, "lon":555}')

Then:

data['lat']

SHOULD NOT give you any error at all.

How to pass a variable from Activity to Fragment, and pass it back?

thanks to @??s???? K and Terry ... it helps me a lot and works perfectly

From Activity you send data with intent as:

Bundle bundle = new Bundle(); 
bundle.putString("edttext", "From Activity"); 
// set Fragmentclass Arguments
Fragmentclass fragobj = new Fragmentclass();
fragobj.setArguments(bundle);

and in Fragment onCreateView method:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // get arguments
    String strtext = getArguments().getString("edttext");    
    return inflater.inflate(R.layout.fragment, container, false);
}

reference : Send data from activity to fragment in android

Are 2 dimensional Lists possible in c#?

This is the easiest way i have found to do it.

List<List<String>> matrix= new List<List<String>>(); //Creates new nested List
matrix.Add(new List<String>()); //Adds new sub List
matrix[0].Add("2349"); //Add values to the sub List at index 0
matrix[0].Add("The Prime of Your Life");
matrix[0].Add("Daft Punk");
matrix[0].Add("Human After All");
matrix[0].Add("3");
matrix[0].Add("2");

To retrieve values is even easier

string title = matrix[0][1]; //Retrieve value at index 1 from sub List at index 0

What does print(... sep='', '\t' ) mean?

sep='\t' is often used for Tab-delimited file.

Initializing a static std::map<int, int> in C++

Using C++11:

#include <map>
using namespace std;

map<int, char> m = {{1, 'a'}, {3, 'b'}, {5, 'c'}, {7, 'd'}};

Using Boost.Assign:

#include <map>
#include "boost/assign.hpp"
using namespace std;
using namespace boost::assign;

map<int, char> m = map_list_of (1, 'a') (3, 'b') (5, 'c') (7, 'd');

Is it possible to create a File object from InputStream

Since Java 7, you can do it in one line even without using any external libraries:

Files.copy(inputStream, outputPath, StandardCopyOption.REPLACE_EXISTING);

See the API docs.

How to len(generator())

Generators have no length, they aren't collections after all.

Generators are functions with a internal state (and fancy syntax). You can repeatedly call them to get a sequence of values, so you can use them in loop. But they don't contain any elements, so asking for the length of a generator is like asking for the length of a function.

if functions in Python are objects, couldn't I assign the length to a variable of this object that would be accessible to the new generator?

Functions are objects, but you cannot assign new attributes to them. The reason is probably to keep such a basic object as efficient as possible.

You can however simply return (generator, length) pairs from your functions or wrap the generator in a simple object like this:

class GeneratorLen(object):
    def __init__(self, gen, length):
        self.gen = gen
        self.length = length

    def __len__(self): 
        return self.length

    def __iter__(self):
        return self.gen

g = some_generator()
h = GeneratorLen(g, 1)
print len(h), list(h)

How to efficiently count the number of keys/properties of an object in JavaScript?

If you are using Underscore.js you can use _.size (thanks @douwe):
_.size(obj)

Alternatively you can also use _.keys which might be clearer for some:
_.keys(obj).length

I highly recommend Underscore, its a tight library for doing lots of basic things. Whenever possible they match ECMA5 and defer to the native implementation.

Otherwise I support @Avi's answer. I edited it to add a link to the MDC doc which includes the keys() method you can add to non-ECMA5 browsers.

Saving awk output to variable

as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.

awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:

variable=$(ps -ef | awk '/port 10 \-/ {print $12}')

variable=`ps -ef | awk '/port 10 \-/ {print $12}'`

The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.

How to add a class to body tag?

Something like this might work:

$("body").attr("class", "about");

It uses jQuery's attr() to add the class 'about' to the body.

if A vs if A is not None:

python >= 2.6,

if we write such as

if A:

will generate warning as,

FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead.

So we can use

if A is not None:

What is "entropy and information gain"?

As you are reading a book about NLTK it would be interesting you read about MaxEnt Classifier Module http://www.nltk.org/api/nltk.classify.html#module-nltk.classify.maxent

For text mining classification the steps could be: pre-processing (tokenization, steaming, feature selection with Information Gain ...), transformation to numeric (frequency or TF-IDF) (I think that this is the key step to understand when using text as input to a algorithm that only accept numeric) and then classify with MaxEnt, sure this is just an example.

How do I deal with installing peer dependencies in Angular CLI?

I found that running the npm install command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.

Specifically, I was trying to use ng2-completer

$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.

I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.

cd foo/foo_app
$ npm install ng2-completer --save

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

Lets see, numeric (3,2). That means you have 3 places for data and two of them are to the right of the decimal leaving only one to the left of the decimal. 15 has two places to the left of the decimal. BTW if you might have 100 as a value I'd increase that to numeric (5, 2)

How to detect a USB drive has been plugged in?

It is easy to check for removable devices. However, there's no guarantee that it is a USB device:

var drives = DriveInfo.GetDrives()
    .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);

This will return a list of all removable devices that are currently accessible. More information:

update query with join on two tables

this is Postgres UPDATE JOIN format:

UPDATE address 
SET cid = customers.id
FROM customers 
WHERE customers.id = address.id

Here's the other variations: http://mssql-to-postgresql.blogspot.com/2007/12/updates-in-postgresql-ms-sql-mysql.html

Is Xamarin free in Visual Studio 2015?

Seems like now it's free for small teams and students, according to Scott Hanselman post https://twitter.com/shanselman/status/715568774418595840

https://visualstudio.microsoft.com/vs/pricing/

Visual Studio Community
FREE

A free, full-featured and extensible IDE for Windows users to create Android and iOS apps with Xamarin, as well as Windows apps, web apps, and cloud services.

  • Students
  • OSS development
  • Small teams

and

Xamarin Studio Community FREE

A free, full-featured IDE for Mac users to create Android and iOS apps using Xamarin.

  • Students
  • OSS development
  • Small teams

MySql Table Insert if not exist otherwise update

I had a situation where I needed to update or insert on a table according to two fields (both foreign keys) on which I couldn't set a UNIQUE constraint (so INSERT ... ON DUPLICATE KEY UPDATE won't work). Here's what I ended up using:

replace into last_recogs (id, hasher_id, hash_id, last_recog) 
  select l.* from 
    (select id, hasher_id, hash_id, [new_value] from last_recogs 
     where hasher_id in (select id from hashers where name=[hasher_name])
     and hash_id in (select id from hashes where name=[hash_name]) 
     union 
     select 0, m.id, h.id, [new_value] 
     from hashers m cross join hashes h 
     where m.name=[hasher_name] 
     and h.name=[hash_name]) l 
  limit 1;

This example is cribbed from one of my databases, with the input parameters (two names and a number) replaced with [hasher_name], [hash_name], and [new_value]. The nested SELECT...LIMIT 1 pulls the first of either the existing record or a new record (last_recogs.id is an autoincrement primary key) and uses that as the value input into the REPLACE INTO.

iPhone is not available. Please reconnect the device

Developers who are using Xcode 11.5 and trying to install their app in iOS 13.6 device will also see this message. It's a very confusing message.

All you need to do is Download Device support files of iOS 13.6 from this link

filsv/iPhoneOSDeviceSupport

  • Close Xcode

  • Unzip and paste it in this location:

    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport/

  • Reopen Xcode.

Now you can install the app on the iOS 13.6 device using Xcode 11.5.

psql: command not found Mac

Mojave, Postgres was installed via

brew install https://raw.githubusercontent.com/lembacon/homebrew-core/bede8a46dea462769466f606f86f82511949066f/Formula/[email protected]

How to get psql in your path:

brew link [email protected] --force

In Angular, how do you determine the active route?

With the new Angular router, you can add a [routerLinkActive]="['your-class-name']" attribute to all your links:

<a [routerLink]="['/home']" [routerLinkActive]="['is-active']">Home</a>

Or the simplified non-array format if only one class is needed:

<a [routerLink]="['/home']" [routerLinkActive]="'is-active'">Home</a>

Or an even simpler format if only one class is needed:

<a [routerLink]="['/home']" routerLinkActive="is-active">Home</a>

See the poorly documented routerLinkActive directive for more info. (I mostly figured this out via trial-and-error.)

UPDATE: Better documentation for the routerLinkActive directive can now be found here. (Thanks to @Victor Hugo Arango A. in the comments below.)

Free Rest API to retrieve current datetime as string (timezone irrelevant)

This API gives you the current time and several formats in JSON - https://market.mashape.com/parsify/format#time. Here's a sample response:

{
  "time": {
    "daysInMonth": 31,
    "millisecond": 283,
    "second": 42,
    "minute": 55,
    "hour": 1,
    "date": 6,
    "day": 3,
    "week": 10,
    "month": 2,
    "year": 2013,
    "zone": "+0000"
  },
  "formatted": {
    "weekday": "Wednesday",
    "month": "March",
    "ago": "a few seconds",
    "calendar": "Today at 1:55 AM",
    "generic": "2013-03-06T01:55:42+00:00",
    "time": "1:55 AM",
    "short": "03/06/2013",
    "slim": "3/6/2013",
    "hand": "Mar 6 2013",
    "handTime": "Mar 6 2013 1:55 AM",
    "longhand": "March 6 2013",
    "longhandTime": "March 6 2013 1:55 AM",
    "full": "Wednesday, March 6 2013 1:55 AM",
    "fullSlim": "Wed, Mar 6 2013 1:55 AM"
  },
  "array": [
    2013,
    2,
    6,
    1,
    55,
    42,
    283
  ],
  "offset": 1362534942283,
  "unix": 1362534942,
  "utc": "2013-03-06T01:55:42.283Z",
  "valid": true,
  "integer": false,
  "zone": 0
}

Batch file to delete folders older than 10 days in Windows 7

FORFILES /S /D -10 /C "cmd /c IF @isdir == TRUE rd /S /Q @path"

I could not get Blorgbeard's suggestion to work, but I was able to get it to work with RMDIR instead of RD:

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

Since RMDIR won't delete folders that aren't empty so I also ended up using this code to delete the files that were over 10 days and then the folders that were over 10 days old.

FOR /d %%K in ("n:\test*") DO (

FOR /d %%J in ("%%K*") DO (

FORFILES /P %%J /S /M . /D -10 /C "cmd /c del @file"

)

)

FORFILES /p N:\test /S /D -10 /C "cmd /c IF @isdir == TRUE RMDIR /S /Q @path"

I used this code to purge out the sub folders in the folders within test (example n:\test\abc\123 would get purged when empty, but n:\test\abc would not get purged

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

Get everything after the dash in a string in JavaScript

For those trying to get everything after the first occurance:

Something like "Nic K Cage" to "K Cage".

You can use slice to get everything from a certain character. In this case from the first space:

const delim = " "
const name = "Nic K Cage"

const end = name.split(delim).slice(1).join(delim) // prints: "K Cage"

Or if OP's string had two hyphens:

const text = "sometext-20202-03"
// Option 1
const op1 = text.slice(text.indexOf('-')).slice(1) // prints: 20202-03
// Option 2
const op2 = text.split('-').slice(1).join("-")     // prints: 20202-03

Angular File Upload

Complete example of File upload using Angular and nodejs(express)

HTML Code

            <div class="form-group">
                <label for="file">Choose File</label><br/>
                <input type="file" id="file" (change)="uploadFile($event.target.files)" multiple>
            </div>

TS Component Code

uploadFile(files) {
    console.log('files', files)
        var formData = new FormData();

    for(let i =0; i < files.length; i++){
      formData.append("files", files[i], files[i]['name']);
        }

    this.httpService.httpPost('/fileUpload', formData)
      .subscribe((response) => {
        console.log('response', response)
      },
        (error) => {
      console.log('error in fileupload', error)
       })
  }

Node Js code

fileUpload API controller

function start(req, res) {
fileUploadService.fileUpload(req, res)
    .then(fileUploadServiceResponse => {
        res.status(200).send(fileUploadServiceResponse)
    })
    .catch(error => {
        res.status(400).send(error)
    })
}

module.exports.start = start

Upload service using multer

const multer = require('multer') // import library
const moment = require('moment')
const q = require('q')
const _ = require('underscore')
const fs = require('fs')
const dir = './public'

/** Store file on local folder */
let storage = multer.diskStorage({
destination: function (req, file, cb) {
    cb(null, 'public')
},
filename: function (req, file, cb) {
    let date = moment(moment.now()).format('YYYYMMDDHHMMSS')
    cb(null, date + '_' + file.originalname.replace(/-/g, '_').replace(/ /g,     '_'))
}
})

/** Upload files  */
let upload = multer({ storage: storage }).array('files')

/** Exports fileUpload function */
module.exports = {
fileUpload: function (req, res) {
    let deferred = q.defer()

    /** Create dir if not exist */
    if (!fs.existsSync(dir)) {
        fs.mkdirSync(dir)
        console.log(`\n\n ${dir} dose not exist, hence created \n\n`)
    }

    upload(req, res, function (err) {
        if (req && (_.isEmpty(req.files))) {
            deferred.resolve({ status: 200, message: 'File not attached', data: [] })
        } else {
            if (err) {
                deferred.reject({ status: 400, message: 'error', data: err })
            } else {
                deferred.resolve({
                    status: 200,
                    message: 'File attached',
                    filename: _.pluck(req.files,
                        'filename'),
                    data: req.files
                })
            }
        }
    })
    return deferred.promise
}
}

MySQL Install: ERROR: Failed to build gem native extension

A number of people found this post helpful.

Also, I needed to do first type this:

yum install mysql-devel

and then:

gem install mysql 

For some people you may need to type:

gem install mysql -- --with-mysql-config=/usr/local/mysql/mysql_config

How to play .mp4 video in videoview in android?

I'm not sure that is the problem but what worked for me is calling mVideoView.start(); inside the mVideoView.setOnPreparedListener event callback.

For example:

Uri uriVideo = Uri.parse(<your link here>);

MediaController mediaController = new MediaController(mContext);
mediaController.setAnchorView(mVideoView);
mVideoView.setMediaController(mediaController);
mVideoView.setVideoURI(uriVideo);
mVideoView.requestFocus();

mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
     @Override
     public void onPrepared(MediaPlayer mp)
     {
          mVideoViewPeekItem.start();
     }
});