Programs & Examples On #Bpmn

Business Process Model & Notation

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

If you using Spring mark the class as @Transactional, then Spring will handle session management.

@Transactional
public class MyClass {
    ...
}

By using @Transactional, many important aspects such as transaction propagation are handled automatically. In this case if another transactional method is called the method will have the option of joining the ongoing transaction avoiding the "no session" exception.

WARNING If you do use @Transactional, please be aware of the resulting behavior. See this article for common pitfalls. For example, updates to entities are persisted even if you don't explicitly call save

Can constructors throw exceptions in Java?

Yes, they can throw exceptions. If so, they will only be partially initialized and if non-final, subject to attack.

The following is from the Secure Coding Guidelines 2.0.

Partially initialized instances of a non-final class can be accessed via a finalizer attack. The attacker overrides the protected finalize method in a subclass, and attempts to create a new instance of that subclass. This attempt fails (in the above example, the SecurityManager check in ClassLoader's constructor throws a security exception), but the attacker simply ignores any exception and waits for the virtual machine to perform finalization on the partially initialized object. When that occurs the malicious finalize method implementation is invoked, giving the attacker access to this, a reference to the object being finalized. Although the object is only partially initialized, the attacker can still invoke methods on it (thereby circumventing the SecurityManager check).

HTML set image on browser tab

It's called a Favicon, have a read.

<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>

You can use this neat tool to generate cross-browser compatible Favicons.

Adding a new SQL column with a default value

If you are learning it's helpful to use a GUI like SQLyog, make the changes using the program and then see the History tab for the DDL statements that made those changes.

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

Everything is great but none of you explained where to download the SDK build tools

Everything is greate but none of you explained where to download the SDK build tools

Ant build failed: "Target "build..xml" does not exist"

Looks like you called it 'ant build..xml'. ant automatically choose a file build.xml in the current directory, so it is enough to call 'ant' (if a default-target is defined) or 'ant target' (the target named target will be called).

With the call 'ant -p' you get a list of targets defined in your build.xml.

Edit: In the comment is shown the call 'ant -verbose build.xml'. To be correct, this has to be called as 'ant -verbose'. The file build.xml in the current directory will be used automatically. If it is needed to explicitly specify the buildfile (because it's name isn't build.xml for example), you have to specify the buildfile with the '-f'-option: 'ant -verbose -f build.xml'. I hope this helps.

How do I find which application is using up my port?

On the command prompt, do:

netstat -nb

Function to convert column number to letter?

I'm surprised nobody suggested: **<code></code> <code>Columns(</code>***<code>Column Index</code>***<code>).Address</code> <code></code>**

  • For example: MsgBox Columns( 9347 ).Address returns **<code>$MUM:$MUM</code>**.

To return ONLY the column letter(s): Split((Columns(Column Index).Address(,0)),":")(0)

  • For example: MsgBox Split((Columns( 2734 ).Address(,0)),":")(0) returns **<code>DAD</code>**.

More Examples


How to make an installer for my C# application?

  1. Add a new install project to your solution.
  2. Add targets from all projects you want to be installed.
  3. Configure pre-requirements and choose "Check for .NET 3.5 and SQL Express" option. Choose the location from where missing components must be installed.
  4. Configure your installer settings - company name, version, copyright, etc.
  5. Build and go!

How to fetch FetchType.LAZY associations with JPA and Hibernate in a Spring Controller

Though this is an old post, please consider using @NamedEntityGraph (Javax Persistence) and @EntityGraph (Spring Data JPA). The combination works.

Example

@Entity
@Table(name = "Employee", schema = "dbo", catalog = "ARCHO")
@NamedEntityGraph(name = "employeeAuthorities",
            attributeNodes = @NamedAttributeNode("employeeGroups"))
public class EmployeeEntity implements Serializable, UserDetails {
// your props
}

and then the spring repo as below

@RepositoryRestResource(collectionResourceRel = "Employee", path = "Employee")
public interface IEmployeeRepository extends PagingAndSortingRepository<EmployeeEntity, String>           {

    @EntityGraph(value = "employeeAuthorities", type = EntityGraphType.LOAD)
    EmployeeEntity getByUsername(String userName);

}

How to get base64 encoded data from html image

You can try following sample http://jsfiddle.net/xKJB8/3/

<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());

Parsing a CSV file using NodeJS

My current solution uses the async module to execute in series:

var fs = require('fs');
var parse = require('csv-parse');
var async = require('async');

var inputFile='myfile.csv';

var parser = parse({delimiter: ','}, function (err, data) {
  async.eachSeries(data, function (line, callback) {
    // do something with the line
    doSomething(line).then(function() {
      // when processing finishes invoke the callback to move to the next one
      callback();
    });
  })
});
fs.createReadStream(inputFile).pipe(parser);

how to run two commands in sudo?

I usually do:

sudo bash -c 'whoami; whoami'

Using onBackPressed() in Android Fragments

Why don't you want to use the back stack? If there is an underlying problem or confusion maybe we can clear it up for you.

If you want to stick with your requirement just override your Activity's onBackPressed() method and call whatever method you're calling when the back arrow in your ActionBar gets clicked.

EDIT: How to solve the "black screen" fragment back stack problem:

You can get around that issue by adding a backstack listener to the fragment manager. That listener checks if the fragment back stack is empty and finishes the Activity accordingly:

You can set that listener in your Activity's onCreate method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FragmentManager fm = getFragmentManager();
    fm.addOnBackStackChangedListener(new OnBackStackChangedListener() {
        @Override
        public void onBackStackChanged() {
            if(getFragmentManager().getBackStackEntryCount() == 0) finish();
        }
    });
}

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

First install "Microsoft ASP.NET Web API Client" nuget package:

  PM > Install-Package Microsoft.AspNet.WebApi.Client

Then use the following function to post your data:

public static async Task<TResult> PostFormUrlEncoded<TResult>(string url, IEnumerable<KeyValuePair<string, string>> postData)
{
    using (var httpClient = new HttpClient())
    {
        using (var content = new FormUrlEncodedContent(postData))
        {
            content.Headers.Clear();
            content.Headers.Add("Content-Type", "application/x-www-form-urlencoded");

            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            return await response.Content.ReadAsAsync<TResult>();
        }
    }
}

And this is how to use it:

TokenResponse tokenResponse = 
    await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData);

or

TokenResponse tokenResponse = 
    (Task.Run(async () 
        => await PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData)))
        .Result

or (not recommended)

TokenResponse tokenResponse = 
    PostFormUrlEncoded<TokenResponse>(OAuth2Url, OAuth2PostData).Result;

Trying to get property of non-object MySQLi result

The cause of your problem is simple. So many people will run into the same problem, Because I did too and it took me hour to figure out. Just in case, someone else stumbles, The problem is in your query, your select statement is calling $dbname instead of table name. So its not found whereby returning false which is boolean. Good luck.

Hide Show content-list with only CSS, no javascript used

I know it's an old post but what about this solution (I've made a JSFiddle to illustrate it)... Solution that uses the :after pseudo elements of <span> to show/hide the <span> switch link itself (in addition to the .alert message it must show/hide). When the pseudo element loses it's focus, the message is hidden.

The initial situation is a hidden message that appears when the <span> with the :after content : "Show Me"; is focused. When this <span> is focused, it's :after content becomes empty while the :after content of the second <span> (that was initially empty) turns to "Hide Me". So, when you click this second <span> the first one loses it's focus and the situation comes back to it's initial state.

I started on the solution offered by @Vector I kept the DOM'situation presented ky @Frederic Kizar

HTML:

<span class="span3" tabindex="0"></span>
<span class="span2" tabindex="0"></span>
<p class="alert" >Some message to show here</p>

CSS:

body {
    display: inline-block;
}
.span3 ~ .span2:after{
    content:"";
}
.span3:focus ~ .alert  {
    display:block;
}
.span3:focus ~ .span2:after  {
    content:"Hide Me";
}
.span3:after  {
    content: "Show Me";
}
.span3:focus:after  {
    content: "";
}
.alert  {
    display:none;
}

How to get Django and ReactJS to work together?

I know this is a couple of years late, but I'm putting it out there for the next person on this journey.

GraphQL has been helpful and way easier compared to DjangoRESTFramework. It is also more flexible in terms of the responses you get. You get what you ask for and don't have to filter through the response to get what you want.

You can use Graphene Django on the server side and React+Apollo/Relay... You can look into it as that is not your question.

Embedding Windows Media Player for all browsers

The following works for me in Firefox and Internet Explorer:

<object id="mediaplayer" classid="clsid:22d6f312-b0f6-11d0-94ab-0080c74c7e95" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#version=5,1,52,701" standby="loading microsoft windows media player components..." type="application/x-oleobject" width="320" height="310">
<param name="filename" value="./test.wmv">
     <param name="animationatstart" value="true">
     <param name="transparentatstart" value="true">
     <param name="autostart" value="true">
     <param name="showcontrols" value="true">
     <param name="ShowStatusBar" value="true">
     <param name="windowlessvideo" value="true">
     <embed src="./test.wmv" autostart="true" showcontrols="true" showstatusbar="1" bgcolor="white" width="320" height="310">
</object>

Set auto height and width in CSS/HTML for different screen sizes

///UPDATED DEMO 2 WATCH SOLUTION////

I hope that is the solution you're looking for! DEMO1 DEMO2

With that solution the only scrollbar in the page is on your contents section in the middle! In that section build your structure with a sidebar or whatever you want!

You can do that with that code here:

<div class="navTop">
<h1>Title</h1>
    <nav>Dynamic menu</nav>
</div>
<div class="container">
    <section>THE CONTENTS GOES HERE</section>
</div>
<footer class="bottomFooter">
    Footer
</footer>

With that css:

.navTop{
width:100%;
border:1px solid black;
float:left;
}
.container{
width:100%;
float:left;
overflow:scroll;
}
.bottomFooter{
float:left;
border:1px solid black;
width:100%;
}

And a bit of jquery:

$(document).ready(function() {
  function setHeight() {
    var top = $('.navTop').outerHeight();
    var bottom = $('footer').outerHeight();
    var totHeight = $(window).height();
    $('section').css({ 
      'height': totHeight - top - bottom + 'px'
    });
  }

  $(window).on('resize', function() { setHeight(); });
  setHeight();
});

DEMO 1

If you don't want jquery

<div class="row">
    <h1>Title</h1>
    <nav>NAV</nav>
</div>

<div class="row container">
    <div class="content">
        <div class="sidebar">
            SIDEBAR
        </div>
        <div class="contents">
            CONTENTS
        </div>
    </div>
    <footer>Footer</footer>
</div>

CSS

*{
margin:0;padding:0;    
}
html,body{
height:100%;
width:100%;
}
body{
display:table;
}
.row{
width: 100%;
background: yellow;
display:table-row;
}
.container{
background: pink;
height:100%; 
}
.content {
display: block;
overflow:auto;
height:100%;
padding-bottom: 40px;
box-sizing: border-box;
}
footer{ 
position: fixed; 
bottom: 0; 
left: 0; 
background: yellow;
height: 40px;
line-height: 40px;
width: 100%;
text-align: center;
}
.sidebar{
float:left;
background:green;
height:100%;
width:10%;
}
.contents{
float:left;
background:red;
height:100%;
width:90%;
overflow:auto;
}

DEMO 2

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

What are .NumberFormat Options In Excel VBA?

Thanks to this question (and answers), I discovered an easy way to get at the exact NumberFormat string for virtually any format that Excel has to offer.


How to Obtain the NumberFormat String for Any Excel Number Format


Step 1: In the user interface, set a cell to the NumberFormat you want to use.

I manually formatted a cell to Chinese (PRC) currency

In my example, I selected the Chinese (PRC) Currency from the options contained in the "Account Numbers Format" combo box.

Step 2: Expand the Number Format dropdown and select "More Number Formats...".

Open the Number Format dropdown

Step 3: In the Number tab, in Category, click "Custom".

Click Custom

The "Sample" section shows the Chinese (PRC) currency formatting that I applied.

The "Type" input box contains the NumberFormat string that you can use programmatically.

So, in this example, the NumberFormat of my Chinese (PRC) Currency cell is as follows:

_ [$¥-804]* #,##0.00_ ;_ [$¥-804]* -#,##0.00_ ;_ [$¥-804]* "-"??_ ;_ @_ 

If you do these steps for each NumberFormat that you desire, then the world is yours.

I hope this helps.

Use of for_each on map elements

C++14 brings generic lambdas. Meaning we can use std::for_each very easily:

std::map<int, int> myMap{{1, 2}, {3, 4}, {5, 6}, {7, 8}};

std::for_each(myMap.begin(), myMap.end(), [](const auto &myMapPair) {
    std::cout << "first " << myMapPair.first << " second "
              << myMapPair.second << std::endl;
});

I think std::for_each is sometimes better suited than a simple range based for loop. For example when you only want to loop through a subset of a map.

Allow user to select camera or gallery for image

For those getting error on 4.4 upward while trying to use the Image selection can use the code below.

Rather than creating a Dialog with a list of Intent options, it is much better to use Intent.createChooser in order to get access to the graphical icons and short names of the various 'Camera', 'Gallery' and even Third Party filesystem browser apps such as 'Astro', etc.

This describes how to use the standard chooser-intent and add additional intents to that.

private void openImageIntent(){

    // Determine Uri of camera image to save.
    final File root = new File(Environment.getExternalStorageDirectory() + File.separator + "amfb" + File.separator);
    root.mkdir();
    final String fname = "img_" + System.currentTimeMillis() + ".jpg";
    final File sdImageMainDirectory = new File(root, fname);
    outputFileUri = Uri.fromFile(sdImageMainDirectory);

    // Camera.
    final List<Intent> cameraIntents = new ArrayList<Intent>();
    final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    final PackageManager packageManager = getPackageManager();
    final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
    for (ResolveInfo res : listCam){
        final String packageName = res.activityInfo.packageName;
        final Intent intent = new Intent(captureIntent);
        intent.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
        intent.setPackage(packageName);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        cameraIntents.add(intent);
    }

    //FileSystem
    final Intent galleryIntent = new Intent();
    galleryIntent.setType("image/");
    galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

    // Chooser of filesystem options.
    final Intent chooserIntent = Intent.createChooser(galleryIntent, "Select Source");
    // Add the camera options.
    chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));
    startActivityForResult(chooserIntent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    //super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK) {
        if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
            final boolean isCamera;
            if (data == null) {
                isCamera = true;
            } else {
                final String action = data.getAction();
                if (action == null) {
                    isCamera = false;
                } else {
                    isCamera = action.equals(MediaStore.ACTION_IMAGE_CAPTURE);
                }
            }

            Uri selectedImageUri;
            if (isCamera) {
                selectedImageUri = outputFileUri;
                //Bitmap factory
                BitmapFactory.Options options = new BitmapFactory.Options();
                // downsizing image as it throws OutOfMemory Exception for larger
                // images
                options.inSampleSize = 8;
                final Bitmap bitmap = BitmapFactory.decodeFile(selectedImageUri.getPath(), options);
                preview.setImageBitmap(bitmap);
            } else {
                selectedImageUri = data == null ? null : data.getData();
                Log.d("ImageURI", selectedImageUri.getLastPathSegment());
                // /Bitmap factory
                BitmapFactory.Options options = new BitmapFactory.Options();
                // downsizing image as it throws OutOfMemory Exception for larger
                // images
                options.inSampleSize = 8;
                try {//Using Input Stream to get uri did the trick
                    InputStream input = getContentResolver().openInputStream(selectedImageUri);
                    final Bitmap bitmap = BitmapFactory.decodeStream(input);
                    preview.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    } else if (resultCode == RESULT_CANCELED){
        // user cancelled Image capture
        Toast.makeText(getApplicationContext(),
                "User cancelled image capture", Toast.LENGTH_SHORT)
                .show();
    } else {
        // failed to capture image
        Toast.makeText(getApplicationContext(),
                "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                .show();
    }
}

Linq select object from list depending on objects attribute

Your expression is never going to evaluate.

You are comparing a with a property of a.

a is of type Answer. a.Correct, I'm guessing is a boolean.

Long form:-

Answer = answer.SingleOrDefault(a => a.Correct == true);

Short form:-

Answer = answer.SingleOrDefault(a => a.Correct);

android lollipop toolbar: how to hide/show the toolbar while scrolling?

For hiding the toolbar you can just do :

getSupportActionBar().hide();

So you just have to had a scroll listener and hide the toolbar when the user scroll !

Reading e-mails from Outlook with Python through MAPI

I had the same problem you did - didn't find much that worked. The following code, however, works like a charm.

import win32com.client

outlook = win32com.client.Dispatch("Outlook.Application").GetNamespace("MAPI")

inbox = outlook.GetDefaultFolder(6) # "6" refers to the index of a folder - in this case,
                                    # the inbox. You can change that number to reference
                                    # any other folder
messages = inbox.Items
message = messages.GetLast()
body_content = message.body
print body_content

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

As I commented, there are a few places on this site that write the contents of a worksheet out to a CSV. This one and this one to point out just two.

Below is my version

  • it explicitly looks out for "," inside a cell
  • It also uses UsedRange - because you want to get all of the contents in the worksheet
  • Uses an array for looping as this is faster than looping through worksheet cells
  • I did not use FSO routines, but this is an option

The code ...

Sub makeCSV(theSheet As Worksheet)
Dim iFile As Long, myPath As String
Dim myArr() As Variant, outStr As String
Dim iLoop As Long, jLoop As Long

myPath = Application.ActiveWorkbook.Path
iFile = FreeFile
Open myPath & "\myCSV.csv" For Output Lock Write As #iFile

myArr = theSheet.UsedRange
For iLoop = LBound(myArr, 1) To UBound(myArr, 1)
    outStr = ""
    For jLoop = LBound(myArr, 2) To UBound(myArr, 2) - 1
        If InStr(1, myArr(iLoop, jLoop), ",") Then
            outStr = outStr & """" & myArr(iLoop, jLoop) & """" & ","
        Else
            outStr = outStr & myArr(iLoop, jLoop) & ","
        End If
    Next jLoop
    If InStr(1, myArr(iLoop, jLoop), ",") Then
        outStr = outStr & """" & myArr(iLoop, UBound(myArr, 2)) & """"
    Else
        outStr = outStr & myArr(iLoop, UBound(myArr, 2))
    End If
    Print #iFile, outStr
Next iLoop

Close iFile
Erase myArr

End Sub

Mapping over values in a python dictionary

While my original answer missed the point (by trying to solve this problem with the solution to Accessing key in factory of defaultdict), I have reworked it to propose an actual solution to the present question.

Here it is:

class walkableDict(dict):
  def walk(self, callback):
    try:
      for key in self:
        self[key] = callback(self[key])
    except TypeError:
      return False
    return True

Usage:

>>> d = walkableDict({ k1: v1, k2: v2 ... })
>>> d.walk(f)

The idea is to subclass the original dict to give it the desired functionality: "mapping" a function over all the values.

The plus point is that this dictionary can be used to store the original data as if it was a dict, while transforming any data on request with a callback.

Of course, feel free to name the class and the function the way you want (the name chosen in this answer is inspired by PHP's array_walk() function).

Note: Neither the try-except block nor the return statements are mandatory for the functionality, they are there to further mimic the behavior of the PHP's array_walk.

How to specify a local file within html using the file: scheme?

the "file://" url protocol can only be used to locate files in the file system of the local machine. since this html code is interpreted by a browser, the "local machine" is the machine that is running the browser.

if you are getting file not found errors, i suspect it is because the file is not found. however, it could also be a security limitation of the browser. some browsers will not let you reference a filesystem file from a non-filesystem html page. you could try using the file path from the command line on the machine running the browser to confirm that this is a browser limitation and not a legitimate missing file.

Is ConfigurationManager.AppSettings available in .NET Core 2.0?

Yes, ConfigurationManager.AppSettings is available in .NET Core 2.0 after referencing NuGet package System.Configuration.ConfigurationManager.

Credits goes to @JeroenMostert for giving me the solution.

java.util.Date vs java.sql.Date

java.util.Date represents a specific instant in time with millisecond precision. It represents both date and time information without timezone. The java.util.Date class implements Serializable, Cloneable and Comparable interface. It is inherited by java.sql.Date, java.sql.Time and java.sql.Timestamp interfaces.

java.sql.Date extends java.util.Date class which represents date without time information and it should be used only when dealing with databases. To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

It inherits all public methods of java.util.Date such as getHours(), getMinutes(), getSeconds(), setHours(), setMinutes(), setSeconds(). As java.sql.Date does not store the time information, it override all the time operations from java.util.Dateand all of these methods throw java.lang.IllegalArgumentException if invoked as evident from their implementation details.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve com.android.support:appcompat-v7:26.1.0

Adding this in project gradle worked for me

allprojects {
 repositories {
     jcenter()
     maven {
         url "https://maven.google.com" // specifically this worked 
     }
 }}

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

I just came across this tonight. Can't say if they are legit, how long in business, and whether they'll be around long, but seems interesting. I may give them a try, and will post update if I do.

Per the website, they say they offer hourly pay-as-you-go and weekly/monthly plans, plus there's a free trial.

http://www.macincloud.com

Per @Iterator, posting update on my findings for this service, moving out from my comments:

I did the trial/evaluation. The trial can be misleading on how the trial works. You may need to signup to see prices but the trial so far, per the trial software download, doesn't appear to be time limited. It's just feature restricted. You signup to get your own account, but you actually use a generic trial login account to do the trial, not your own account. Your own account is used when you actually pay for the service. The trial limits what you can do, install, save, etc. but good enough to give you an idea of how things work. So it doesn't hurt to signup to evaluate and not pay anything.

Persistence of data is offered via saving files to DropBox (pre-installed, you just need login/configure), etc. There is no concept of AMIs, EBS, or some VM image. Their service is actually like a shared website hosting solution, where users timeshare a Mac machine (like timesharing a Unix/Linux server), and I think they limit or periodically purge what you put on the machine, or perhaps rather they don't backup your files, hence use of DropBox to do the backup. One should contact them to clarify this if desired.

They have various pricing options, as you mention the all day pass, monthly plans at $20, and their is a pay as you go plan at $1/hr. I'd probably go with pay as you go based on my usage. The pay as you go is based on prepaid credits (1 credit = 1 hour, billed at 30 credit increments). One caveat is that you need to periodically use the plan at least once every 60 days for the pay as you go plan or else you lose unused credits. So that's like minimum of spending 1 credit /1 hour every 60 days.

One last comment for now, from my evaluation, you'll need high bandwidth to use the service effectively. It's usable over 1.5 Mbps DSL but kind of slow in response. You'd want to use it from a corporate network with Gbps bandwidth for optimal use. Or at least a higher speed cable/DSL broadband connection. On my last test ~3Mbps seemed sufficient on the low bandwidth profile (they have multiple bandwidth connection profiles, low, medium, high, optimized for some bandwidth ranges). I didn't test on the higher ones. Your mileage may vary.

Delete statement in SQL is very slow

Check execution plan of this delete statement. Have a look if index seek is used. Also what is data type of col?

If you are using wrong data type, change update statement (like from '1' to 1 or N'1').

If index scan is used consider using some query hint..

What is the bower (and npm) version syntax?

Bower uses semver syntax, but here are a few quick examples:

You can install a specific version:

$ bower install jquery#1.11.1

You can use ~ to specify 'any version that starts with this':

$ bower install jquery#~1.11

You can specify multiple version requirements together:

$ bower install "jquery#<2.0 >1.10"

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

This can also come up when running unit tests if you are testing a component with custom elements. In that case custom_elements_schema needs to be added to the testingModule that gets setup at the beginning of the .spec.ts file for that component. Here is an example of how the header.component.spec.ts setup would begin:

import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';

describe('HeaderComponent', () => {
  let component: HeaderComponent;
  let fixture: ComponentFixture<HeaderComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [PrizeAddComponent],
      schemas: [
        CUSTOM_ELEMENTS_SCHEMA
      ],
    })
      .compileComponents();
  }));

Generate UML Class Diagram from Java Project

I´d say MoDisco is by far the most powerful one (though probably not the easiest one to work with).

MoDisco is a generic reverse engineering framework (so that you can customize your reverse engineering project, with MoDisco you can even reverse engineer the behaviour of the java methods, not only the structure and signatures) but also includes some predefined features like the generation of class diagrams out of Java code that you need.

All com.android.support libraries must use the exact same version specification

Highlight the error and press "ALT+ENTER", you'll see an option to:

Add Library dependency > Edit Intention settings

This will bring you to a menu where you'll see the specific problem support dependency that differs with support-compat. Create its dependency in gradle (com 'XXX') and set it's version to match that of support-compat. Sync gradle and you're done.

What is the difference between Scope_Identity(), Identity(), @@Identity, and Ident_Current()?

Good question.

  • @@IDENTITY: returns the last identity value generated on your SQL connection (SPID). Most of the time it will be what you want, but sometimes it isn't (like when a trigger is fired in response to an INSERT, and the trigger executes another INSERT statement).

  • SCOPE_IDENTITY(): returns the last identity value generated in the current scope (i.e. stored procedure, trigger, function, etc).

  • IDENT_CURRENT(): returns the last identity value for a specific table. Don't use this to get the identity value from an INSERT, it's subject to race conditions (i.e. multiple connections inserting rows on the same table).

  • IDENTITY(): used when declaring a column in a table as an identity column.

For more reference, see: http://msdn.microsoft.com/en-us/library/ms187342.aspx.

To summarize: if you are inserting rows, and you want to know the value of the identity column for the row you just inserted, always use SCOPE_IDENTITY().

How can I check if an ip is in a network in Python?

This article shows you can do it with socket and struct modules without too much extra effort. I added a little to the article as follows:

import socket,struct

def makeMask(n):
    "return a mask of n bits as a long integer"
    return (2L<<n-1) - 1

def dottedQuadToNum(ip):
    "convert decimal dotted quad string to long integer"
    return struct.unpack('L',socket.inet_aton(ip))[0]

def networkMask(ip,bits):
    "Convert a network address to a long integer" 
    return dottedQuadToNum(ip) & makeMask(bits)

def addressInNetwork(ip,net):
   "Is an address in a network"
   return ip & net == net

address = dottedQuadToNum("192.168.1.1")
networka = networkMask("10.0.0.0",24)
networkb = networkMask("192.168.0.0",24)
print (address,networka,networkb)
print addressInNetwork(address,networka)
print addressInNetwork(address,networkb)

This outputs:

False
True

If you just want a single function that takes strings it would look like this:

import socket,struct

def addressInNetwork(ip,net):
   "Is an address in a network"
   ipaddr = struct.unpack('L',socket.inet_aton(ip))[0]
   netaddr,bits = net.split('/')
   netmask = struct.unpack('L',socket.inet_aton(netaddr))[0] & ((2L<<int(bits)-1) - 1)
   return ipaddr & netmask == netmask

Android layout replacing a view with another view on run time

And if you do that very often, you could use a ViewSwitcher or a ViewFlipper to ease view substitution.

How to make a pure css based dropdown menu?

_x000D_
_x000D_
html, body {_x000D_
    font-family: Arial, Helvetica, sans-serif;_x000D_
}_x000D_
_x000D_
/* define a fixed width for the entire menu */_x000D_
.navigation {_x000D_
  width: 150px;_x000D_
}_x000D_
_x000D_
/* reset our lists to remove bullet points and padding */_x000D_
.mainmenu, .submenu {_x000D_
  list-style: none;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
/* make ALL links (main and submenu) have padding and background color */_x000D_
.mainmenu a {_x000D_
  display: block;_x000D_
  background-color: #CCC;_x000D_
  text-decoration: none;_x000D_
  padding: 10px;_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
/* add hover behaviour */_x000D_
.mainmenu a:hover {_x000D_
    background-color: #C5C5C5;_x000D_
}_x000D_
_x000D_
_x000D_
/* when hovering over a .mainmenu item,_x000D_
  display the submenu inside it._x000D_
  we're changing the submenu's max-height from 0 to 200px;_x000D_
*/_x000D_
_x000D_
.mainmenu li:hover .submenu {_x000D_
  display: block;_x000D_
  max-height: 200px;_x000D_
}_x000D_
_x000D_
/*_x000D_
  we now overwrite the background-color for .submenu links only._x000D_
  CSS reads down the page, so code at the bottom will overwrite the code at the top._x000D_
*/_x000D_
_x000D_
.submenu a {_x000D_
  background-color: #999;_x000D_
}_x000D_
_x000D_
/* hover behaviour for links inside .submenu */_x000D_
.submenu a:hover {_x000D_
  background-color: #666;_x000D_
}_x000D_
_x000D_
/* this is the initial state of all submenus._x000D_
  we set it to max-height: 0, and hide the overflowed content._x000D_
*/_x000D_
.submenu {_x000D_
  overflow: hidden;_x000D_
  max-height: 0;_x000D_
  -webkit-transition: all 0.5s ease-out;_x000D_
}
_x000D_
<html>_x000D_
<body>_x000D_
<head>_x000D_
<link rel="stylesheet" type="css/text" href="nav.css">_x000D_
</head>_x000D_
</body>_x000D_
<nav class="navigation">_x000D_
  <ul class="mainmenu">_x000D_
    <li><a href="">Home</a></li>_x000D_
    <li><a href="">About</a></li>_x000D_
    <li><a href="">Products</a>_x000D_
      <ul class="submenu">_x000D_
        <li><a href="">Tops</a></li>_x000D_
        <li><a href="">Bottoms</a></li>_x000D_
        <li><a href="">Footwear</a></li>_x000D_
      </ul>_x000D_
    </li>_x000D_
    <li><a href="">Contact us</a></li>_x000D_
  </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How to convert a char array back to a string?

String str = "wwwwww3333dfevvv";
char[] c = str.toCharArray();

Now to convert character array into String , there are two ways.

Arrays.toString(c);

Returns the string [w, w, w, w, w, w, 3, 3, 3, 3, d, f, e, v, v, v].

And:

String.valueOf(c)

Returns the string wwwwww3333dfevvv.

In Summary: pay attention to Arrays.toString(c), because you'll get "[w, w, w, w, w, w, 3, 3, 3, 3, d, f, e, v, v, v]" instead of "wwwwww3333dfevvv".

Setting an image for a UIButton in code

I was looking for a solution to add an UIImage to my UIButton. The problem was just it displays the image bigger than needed. Just helped me with this:

_imageViewBackground = [[UIImageView alloc] initWithFrame:rectImageView];
_imageViewBackground.image = [UIImage imageNamed:@"gradientBackgroundPlain"];
[self addSubview:_imageViewBackground];
[self insertSubview:_imageViewBackground belowSubview:self.label];
_imageViewBackground.hidden = YES;

Every time I want to display my UIImageView I just set the var hidden to YES or NO. There might be other solutions but I got confused so many times with this stuff and this solved it and I didn't need to deal with internal stuff UIButton is doing in background.

MVC pattern on Android

There is no universally unique MVC pattern. MVC is a concept rather than a solid programming framework. You can implement your own MVC on any platform. As long as you stick to the following basic idea, you are implementing MVC:

  • Model: What to render
  • View: How to render
  • Controller: Events, user input

Also think about it this way: When you program your model, the model should not need to worry about the rendering (or platform specific code). The model would say to the view, I don't care if your rendering is Android or iOS or Windows Phone, this is what I need you to render. The view would only handle the platform-specific rendering code.

This is particularly useful when you use Mono to share the model in order to develop cross-platform applications.

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

I had a similar issue, but it turns out I was just referencing a cell which was off the page {i.e. cells(i,1).cut cells (i-1,2)}

How to use underscore.js as a template engine?

I am giving a very simple example

1)

var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);
console.log(parsedTemplate); 

The result would be

Welcome you are at mysite.This has been created by john whose age is 25.

2) This is a template

   <script type="text/template" id="template_1">
       <% _.each(items,function(item,key,arr) { %>
          <li>
             <span><%= key %></span>
             <span><%= item.name %></span>
             <span><%= item.type %></span>
           </li>
       <% }); %>
   </script>

This is html

<div>
  <ul id="list_2"></ul>
</div>

This is the javascript code which contains json object and putting template into html

   var items = [
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       } 
   ];
  $(document).ready(function(){
      var template = $("#template_1").html();
      $("#list_2").html(_.template(template,{items:items}));
  });

What is causing "Unable to allocate memory for pool" in PHP?

Using a TTL of 0 means that APC will flush all the cache when it runs out of memory. The error don't appear anymore but it makes APC far less efficient. It's a no risk, no trouble, "I don't want to do my job" decision. APC is not meant to be used that way. You should choose a TTL high enough so the most accessed pages won't expire. The best is to give enough memory so APC doesn't need to flush cache.

Just read the manual to understand how ttl is used : http://www.php.net/manual/en/apc.configuration.php#ini.apc.ttl

The solution is to increase memory allocated to APC. Do this by increasing apc.shm_size.

If APC is compiled to use Shared Segment Memory you will be limited by your operating system. Type this command to see your system limit for each segment :

sysctl -a | grep -E "shmall|shmmax"

To alocate more memory you'll have to increase the number of segments with the parameter apc.shm_segments.

If APC is using mmap memory then you have no limit. The amount of memory is still defined by the same option apc.shm_size.

If there's not enough memory on the server, then use filters option to prevent less frequently accessed php files from being cached.

But never use a TTL of 0.

As c33s said, use apc.php to check your config. Copy the file from apc package to a webfolder and point browser to it. You'll see what is really allocated and how it is used. The graphs must remain stable after hours, if they are completly changing at each refresh, then it means that your setup is wrong (APC is flushing everything). Allocate 20% more ram than what APC really use as a security margin, and check it on a regular basis.

The default of allowing only 32MB is ridiculously low. PHP was designed when servers were 64MB and most scripts were using one php file per page. Nowadays solutions like Magento require more than 10k files (~60Mb in APC). You should allow enough memory so most of php files are always cached. It's not a waste, it's more efficient to keep opcode in ram rather than having the corresponding raw php in file cache. Nowadays we can find dedicated servers with 24Gb of memory for as low as $80/month, so don't hesitate to allow several GB to APC. I put 2GB out of 24GB on a server hosting 5Magento stores and ~40 wordpress website, APC uses 1.2GB. Count 64MB for Magento installation, 40MB for a Wordpress with some plugins.

Also, if you have developpment websites on the same server. Exclude them from cache.

gradient descent using python and numpy

I think your code is a bit too complicated and it needs more structure, because otherwise you'll be lost in all equations and operations. In the end this regression boils down to four operations:

  1. Calculate the hypothesis h = X * theta
  2. Calculate the loss = h - y and maybe the squared cost (loss^2)/2m
  3. Calculate the gradient = X' * loss / m
  4. Update the parameters theta = theta - alpha * gradient

In your case, I guess you have confused m with n. Here m denotes the number of examples in your training set, not the number of features.

Let's have a look at my variation of your code:

import numpy as np
import random

# m denotes the number of examples here, not the number of features
def gradientDescent(x, y, theta, alpha, m, numIterations):
    xTrans = x.transpose()
    for i in range(0, numIterations):
        hypothesis = np.dot(x, theta)
        loss = hypothesis - y
        # avg cost per example (the 2 in 2*m doesn't really matter here.
        # But to be consistent with the gradient, I include it)
        cost = np.sum(loss ** 2) / (2 * m)
        print("Iteration %d | Cost: %f" % (i, cost))
        # avg gradient per example
        gradient = np.dot(xTrans, loss) / m
        # update
        theta = theta - alpha * gradient
    return theta


def genData(numPoints, bias, variance):
    x = np.zeros(shape=(numPoints, 2))
    y = np.zeros(shape=numPoints)
    # basically a straight line
    for i in range(0, numPoints):
        # bias feature
        x[i][0] = 1
        x[i][1] = i
        # our target variable
        y[i] = (i + bias) + random.uniform(0, 1) * variance
    return x, y

# gen 100 points with a bias of 25 and 10 variance as a bit of noise
x, y = genData(100, 25, 10)
m, n = np.shape(x)
numIterations= 100000
alpha = 0.0005
theta = np.ones(n)
theta = gradientDescent(x, y, theta, alpha, m, numIterations)
print(theta)

At first I create a small random dataset which should look like this:

Linear Regression

As you can see I also added the generated regression line and formula that was calculated by excel.

You need to take care about the intuition of the regression using gradient descent. As you do a complete batch pass over your data X, you need to reduce the m-losses of every example to a single weight update. In this case, this is the average of the sum over the gradients, thus the division by m.

The next thing you need to take care about is to track the convergence and adjust the learning rate. For that matter you should always track your cost every iteration, maybe even plot it.

If you run my example, the theta returned will look like this:

Iteration 99997 | Cost: 47883.706462
Iteration 99998 | Cost: 47883.706462
Iteration 99999 | Cost: 47883.706462
[ 29.25567368   1.01108458]

Which is actually quite close to the equation that was calculated by excel (y = x + 30). Note that as we passed the bias into the first column, the first theta value denotes the bias weight.

How do I find out my root MySQL password?

MySQL 5.5 on Ubuntu 14.04 required slightly different commands as recommended here. In a nutshell:

sudo /etc/init.d/mysql stop
sudo /usr/sbin/mysqld --skip-grant-tables --skip-networking &
mysql -u root

And then from the MySQL prompt

FLUSH PRIVILEGES;
SET PASSWORD FOR root@'localhost' = PASSWORD('password');
UPDATE mysql.user SET Password=PASSWORD('newpwd') WHERE User='root';
FLUSH PRIVILEGES;

And the cited source offers an alternate method as well.

How to get javax.comm API?

Another Simple way i found in Netbeans right click on your project>libraris click add jar/folder add your comm.jar and you done.

if you dont have comm.jar download it from >>> http://llk.media.mit.edu/projects/picdev/software/javaxcomm.zip

Get Value of Row in Datatable c#

for (Int32 i = 1; i < dt_pattern.Rows.Count - 1; i++){ double yATmax = ToDouble(dt_pattern.Rows[i]["Ampl"].ToString()) + AT; }

if you want to get around the + 1 issue

Magento How to debug blank white screen

Same problem, I have just purged cache

rm -rf var/cache/* 

Et voila ! I don't understand what it was...

Twig: in_array or similar possible within if statement?

another example following @jake stayman:

{% for key, item in row.divs %}
    {% if (key not in [1,2,9]) %} // eliminate element 1,2,9
        <li>{{ item }}</li>
    {% endif %}
{% endfor %}

How to check if function exists in JavaScript?

I would suspect that me is not getting correctly assigned onload.

Moving the get_ID call into the onclick event should take care of it.

Obviously you can further trap as previously mentioned:

function js_to_as( str) {
  var me = get_ID('jsExample');
  if (me && me.onChange) {
    me.onChange(str);
  }
}

How to print strings with line breaks in java

private static final String mText = "SHOP MA" + "\n" +
        + "----------------------------" + "\n" +
        + "Pannampitiya" + newline +
        + "09-10-2012 harsha  no: 001" + "\n" +
        + "No  Item  Qty  Price  Amount" + "\n" +
        + "1 Bread 1 50.00  50.00" + "\n" +
        + "____________________________" + "\n";

This should work.

Highlighting Text Color using Html.fromHtml() in Android?

This can be achieved using a Spannable String. You will need to import the following

import android.text.SpannableString; 
import android.text.style.BackgroundColorSpan; 
import android.text.style.StyleSpan;

And then you can change the background of the text using something like the following:

TextView text = (TextView) findViewById(R.id.text_login);
text.setText("");
text.append("Add all your funky text in here");
Spannable sText = (Spannable) text.getText();
sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);

Where this will highlight the charecters at pos 1 - 4 with a red color. Hope this helps!

generating variable names on fly in python

Though I don't see much point, here it is:

for i in xrange(0, len(prices)):
    exec("price%d = %s" % (i + 1, repr(prices[i])));

Check if a string is a valid Windows directory (folder) path

Use this Code

string DirectoryName = "Sample Name For Directory Or File";
Path.GetInvalidFileNameChars()
  .Where(x => DirectoryName.Contains(x))
  .Count() > 0 || DirectoryName == "con"

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

Select the project. Properties->Configuration Properties->Linker->System.

My problem solved by setting below option. Under System: SubSystem = Console(/SUBSYSTEM:CONSOLE)

Or you can choose the last option as "inherite from the parent".

How to initialize a variable of date type in java?

tl;dr

Use Instant, replacement for java.util.Date.

Instant.now()  // Capture current moment as seen in UTC.

If you must have a Date, convert.

java.util.Date.from( Instant.now() ) 

java.time

The java.util.Date & .Calendar classes have been supplanted by the java.time framework built into Java 8 and later. The new classes are a tremendous improvement, inspired by the successful Joda-Time library.

The java.time classes tend to use static factory methods rather than constructors for instantiating objects.

To get the current moment in UTC time zone:

Instant instant = Instant.now();

To get the current moment in a particular time zone:

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );

If you must have a java.util.Date for use with other classes not yet updated for the java.time types, convert from Instant.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

Table of date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

self referential struct definition?

Lets go through basic definition of typedef. typedef use to define an alias to an existing data type either it is user defined or inbuilt.

typedef <data_type> <alias>;

for example

typedef int scores;

scores team1 = 99;

Confusion here is with the self referential structure, due to a member of same data type which is not define earlier. So In standard way you can write your code as :-

//View 1
typedef struct{ bool isParent; struct Cell* child;} Cell;

//View 2
typedef struct{
  bool isParent;
  struct Cell* child;
} Cell;

//Other Available ways, define stucture and create typedef
struct Cell {
  bool isParent;
  struct Cell* child;
};

typedef struct Cell Cell;

But last option increase some extra lines and words with usually we don't want to do (we are so lazy you know ;) ) . So prefer View 2.

changing iframe source with jquery

Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).

Example:

var divMapLoaded = false;
$("#container").scroll(function() {
    if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
    $("#map-iframe").html("<iframe id=\"map-iframe\" " +
        "width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
        "marginheight=\"0\" marginwidth=\"0\" " +
        "src=\"http://www.google.it/maps?t=m&amp;cid=0x3e589d98063177ab&amp;ie=UTF8&amp;iwloc=A&amp;brcurrent=5,0,1&amp;ll=41.123115,16.853177&amp;spn=0.005617,0.009943&amp;output=embed\"" +
        "></iframe>");
    divMapLoaded = true;
}

Reading/writing an INI file

Usually, when you create applications using C# and the .NET framework, you will not use INI files. It is more common to store settings in an XML-based configuration file or in the registry. However, if your software shares settings with a legacy application it may be easier to use its configuration file, rather than duplicating the information elsewhere.

The .NET framework does not support the use of INI files directly. However, you can use Windows API functions with Platform Invocation Services (P/Invoke) to write to and read from the files. In this link we create a class that represents INI files and uses Windows API functions to manipulate them. Please go through the following link.

Reading and Writing INI Files

jQuery add text to span within a div

You can use:

$("#tagscloud span").text("Your text here");

The same code will also work for the second case. You could also use:

$("#tagscloud #WebPartCaptionWPQ2").text("Your text here");

groovy: safely find a key in a map and return its value

In general, this depends what your map contains. If it has null values, things can get tricky and containsKey(key) or get(key, default) should be used to detect of the element really exists. In many cases the code can become simpler you can define a default value:

def mymap = [name:"Gromit", likes:"cheese", id:1234]
def x1 = mymap.get('likes', '[nothing specified]')
println "x value: ${x}" }

Note also that containsKey() or get() are much faster than setting up a closure to check the element mymap.find{ it.key == "likes" }. Using closure only makes sense if you really do something more complex in there. You could e.g. do this:

mymap.find{ // "it" is the default parameter
  if (it.key != "likes") return false
  println "x value: ${it.value}" 
  return true // stop searching
}

Or with explicit parameters:

mymap.find{ key,value ->
  (key != "likes")  return false
  println "x value: ${value}" 
  return true // stop searching
}

Forcing a postback

By using Server.Transfer("YourCurrentPage.aspx"); we can easily acheive this and it is better than Response.Redirect(); coz Server.Transfer() will save you the round trip.

How to convert the background to transparent?

I would recommend this (just found via search):

  1. http://lunapic.com/editor/?action=load
  2. Browse for image to upload OR enter URL of the file (below the image)
    http://i.stack.imgur.com/2gQWg.png
  3. Edit menu/Transparent (last one)
  4. Click on the red area
  5. Behold :) below is your image, it's just white triangle with transparency...
    [dragging the image around in your browser for visibility,
    the gray background and the border is not part of the image]
    your image made transparent
  6. File menu/Save Image
    GIF/PNG/ICO image file formats support transparency, JPG doesn't!

What's the difference between git clone --mirror and git clone --bare

My tests with git-2.0.0 today indicate that the --mirror option does not copy hooks, the config file, the description file, the info/exclude file, and at least in my test case a few refs (which I don't understand.) I would not call it a "functionally identical copy, interchangeable with the original."

-bash-3.2$ git --version
git version 2.0.0
-bash-3.2$ git clone --mirror /git/hooks
Cloning into bare repository 'hooks.git'...
done.

-bash-3.2$ diff --brief -r /git/hooks.git hooks.git
Files /git/hooks.git/config and hooks.git/config differ
Files /git/hooks.git/description and hooks.git/description differ
...
Only in hooks.git/hooks: applypatch-msg.sample
...
Only in /git/hooks.git/hooks: post-receive
...
Files /git/hooks.git/info/exclude and hooks.git/info/exclude differ
...
Files /git/hooks.git/packed-refs and hooks.git/packed-refs differ
Only in /git/hooks.git/refs/heads: fake_branch
Only in /git/hooks.git/refs/heads: master
Only in /git/hooks.git/refs: meta

How to check for empty array in vba macro

Personally, I think one of the answers above can be modified to check if the array has contents:

if UBound(ar) > LBound(ar) Then

This handles negative number references and takes less time than some of the other options.

release Selenium chromedriver.exe from memory

I came here initially thinking surely this would have been answered/resolved but after reading all the answers I was a bit surprised no one tried to call all three methods together:

try
{
    blah
}
catch
{
    blah
}
finally
{
    driver.Close(); // Close the chrome window
    driver.Quit(); // Close the console app that was used to kick off the chrome window
    driver.Dispose(); // Close the chromedriver.exe
}

I was only here to look for answers and didn't intend to provide one. So the above solution is based on my experience only. I was using chrome driver in a C# console app and I was able to clean up the lingering processes only after calling all three methods together.

How to select rows for a specific date, ignoring time in SQL Server

I know it's been a while on this question, but I was just looking for the same answer and found this seems to be the simplest solution:

select * from sales where datediff(dd, salesDate, '20101111') = 0

I actually use it more to find things within the last day or two, so my version looks like this:

select * from sales where datediff(dd, salesDate, getdate()) = 0

And by changing the 0 for today to a 1 I get yesterday's transactions, 2 is the day before that, and so on. And if you want everything for the last week, just change the equals to a less-than-or-equal-to:

select * from sales where datediff(dd, salesDate, getdate()) <= 7

Uploading a file in Rails

Sept 2018

For anyone checking this question recently, Rails 5.2+ now has ActiveStorage by default & I highly recommend checking it out.

Since it is part of the core Rails 5.2+ now, it is very well integrated & has excellent capabilities out of the box (still all other well-known gems like Carrierwave, Shrine, paperclip,... are great but this one offers very good features that we can consider for any new Rails project)

Paperclip team deprecated the gem in favor of the Rails ActiveStorage.

Here is the github page for the ActiveStorage & plenty of resources are available everywhere

Also I found this video to be very helpful to understand the features of Activestorage

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

Your main problem is thinking that the variable you declared outside of the template is the same variable being "set" inside the choose statement. This is not how XSLT works, the variable cannot be reassigned. This is something more like what you want:

<xsl:template match="class">
  <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
  <xsl:variable name="subexists">
    <xsl:choose>
      <xsl:when test="joined-subclass">true</xsl:when>
      <xsl:otherwise>false</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

And if you need the variable to have "global" scope then declare it outside of the template:

<xsl:variable name="subexists">
  <xsl:choose>
     <xsl:when test="/path/to/node/joined-subclass">true</xsl:when>
     <xsl:otherwise>false</xsl:otherwise>
  </xsl:choose>
</xsl:variable>

<xsl:template match="class">
   subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

Rename specific column(s) in pandas

A much faster implementation would be to use list-comprehension if you need to rename a single column.

df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]

If the need arises to rename multiple columns, either use conditional expressions like:

df.columns = ['log(gdp)' if x=='gdp' else 'cap_mod' if x=='cap' else x for x in df.columns]

Or, construct a mapping using a dictionary and perform the list-comprehension with it's get operation by setting default value as the old name:

col_dict = {'gdp': 'log(gdp)', 'cap': 'cap_mod'}   ## key?old name, value?new name

df.columns = [col_dict.get(x, x) for x in df.columns]

Timings:

%%timeit
df.rename(columns={'gdp':'log(gdp)'}, inplace=True)
10000 loops, best of 3: 168 µs per loop

%%timeit
df.columns = ['log(gdp)' if x=='gdp' else x for x in df.columns]
10000 loops, best of 3: 58.5 µs per loop

Padding is invalid and cannot be removed?

A serval times of fighting, I finally solved the problem.
(Note: I use standard AES as symmetric algorithm. This answer may not suitable for everyone.)

  1. Change the algorithm class. Replace the RijndaelManaged class to AESManaged one.
  2. Do not explicit set the KeySize of algorithm class, left them default.
    (This is the very important step. I think there is a bug in KeySize property.)

Here is a list you want to check which argument you might have missed:

  • Key
    (byte array, length must be exactly one of 16, 24, 32 byte for different key size.)
  • IV
    (byte array, 16 bytes)
  • CipherMode
    (One of CBC, CFB, CTS, ECB, OFB)
  • PaddingMode
    (One of ANSIX923, ISO10126, None, PKCS7, Zeros)

Forcing anti-aliasing using css: Is this a myth?

I doubt there is anyway to force a browser to do anything. It would depend on the system configuration, the font used, browser settings, etc. It sounds like BS to me too.

As a note, always use relative sizes not PX.

ETag vs Header Expires

They are slightly different - the ETag does not have any information that the client can use to determine whether or not to make a request for that file again in the future. If ETag is all it has, it will always have to make a request. However, when the server reads the ETag from the client request, the server can then determine whether to send the file (HTTP 200) or tell the client to just use their local copy (HTTP 304). An ETag is basically just a checksum for a file that semantically changes when the content of the file changes.

The Expires header is used by the client (and proxies/caches) to determine whether or not it even needs to make a request to the server at all. The closer you are to the Expires date, the more likely it is the client (or proxy) will make an HTTP request for that file from the server.

So really what you want to do is use BOTH headers - set the Expires header to a reasonable value based on how often the content changes. Then configure ETags to be sent so that when clients DO send a request to the server, it can more easily determine whether or not to send the file back.

One last note about ETag - if you are using a load-balanced server setup with multiple machines running Apache you will probably want to turn off ETag generation. This is because inodes are used as part of the ETag hash algorithm which will be different between the servers. You can configure Apache to not use inodes as part of the calculation but then you'd want to make sure the timestamps on the files are exactly the same, to ensure the same ETag gets generated for all servers.

How can I show/hide component with JSF?

check this below code. this is for dropdown menu. In this if we select others then the text box will show otherwise text box will hide.

function show_txt(arg,arg1)
{
if(document.getElementById(arg).value=='other')
{
document.getElementById(arg1).style.display="block";
document.getElementById(arg).style.display="none";
}
else
{
document.getElementById(arg).style.display="block";
document.getElementById(arg1).style.display="none";
}
}
The HTML code here :

<select id="arg" onChange="show_txt('arg','arg1');">
<option>yes</option>
<option>No</option>
<option>Other</option>
</select>
<input type="text" id="arg1" style="display:none;">

or you can check this link click here

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

it is wrong. correct will be

P3 P2 P4 P5 P1 0 3 4 6 10 as the correct difference are these

Waiting Time (0+3+4+6+10)/5 = 4.6

Ref: http://www.it.uu.se/edu/course/homepage/oskomp/vt07/lectures/scheduling_algorithms/handout.pdf

why is plotting with Matplotlib so slow?

Matplotlib makes great publication-quality graphics, but is not very well optimized for speed. There are a variety of python plotting packages that are designed with speed in mind:

SecurityException: Permission denied (missing INTERNET permission?)

remove this in your manifest file

 xmlns:tools="http://schemas.android.com/tools"

How to concatenate properties from multiple JavaScript objects

To merge a dynamic number of objects, we can use Object.assign with spread syntax.

const mergeObjs = (...objs) => Object.assign({}, ...objs);

The above function accepts any number of objects, merging all of their properties into a new object with properties from later objects overwriting those from previous objects.

Demo:

_x000D_
_x000D_
const mergeObjs = (...objs) => Object.assign({}, ...objs);
const a = {prop: 1, prop2: '2'},
      b = {prop3: 3, prop4: [1,2,3,4]}
      c = {prop5: 5},
      d = {prop6: true, prop7: -1},
      e = {prop1: 2};
const abcd = mergeObjs(a,b,c,d);
console.log("Merged a,b,c,d:", abcd);
const abd = mergeObjs(a,b,d);
console.log("Merged a,b,d:", abd);
const ae = mergeObjs(a,e);//prop1 from e will overwrite prop1 from a
console.log("Merged a,e:", ae);
_x000D_
_x000D_
_x000D_

To merge an array of objects, a similar method may be applied.

const mergeArrayOfObjs = arr => Object.assign({}, ...arr);

Demo:

_x000D_
_x000D_
const mergeArrayOfObjs = arr => Object.assign({}, ...arr);
const arr = [
  {a: 1, b: 2},
  {c:1, d:3},
  {abcd: [1,2,3,4], d: 4}
];
const merged = mergeArrayOfObjs(arr);
console.log(merged);
_x000D_
_x000D_
_x000D_

Best practice for storing and protecting private API keys in applications

Keep the secret in firebase database and get from it when app starts , It is far better than calling a web service .

Perform Button click event when user press Enter key in Textbox

You can do it with javascript/jquery:

<script>
    function runScript(e) {
        if (e.keyCode == 13) {
            $("#myButton").click(); //jquery
            document.getElementById("myButton").click(); //javascript
        }
    }
</script>

<asp:textbox id="txtUsername" runat="server" onkeypress="return runScript(event)" />

<asp:LinkButton id="myButton" text="Login" runat="server" />

Select Tag Helper in ASP.NET Core MVC

I created an Interface and a <options> tag helper for this. So I didn't have to convert the IEnumerable<T> items into IEnumerable<SelectListItem> every time I have to populate the <select> control.

And I think it works beautifully...

The usage is something like:

<select asp-for="EmployeeId">
    <option value="">Please select...</option>
    <options asp-items="@Model.EmployeesList" />
</select>

And to make it work with the tag helper you have to implement that interface in your class:

public class Employee : IIntegerListItem
{
   public int Id { get; set; }
   public string FullName { get; set; }

   public int Value { return Id; }
   public string Text{ return FullName ; }
}

These are the needed codes:

The interface:

public interface IIntegerListItem
{
    int Value { get; }
    string Text { get; }
}

The <options> tag helper:

[HtmlTargetElement("options", Attributes = "asp-items")]
public class OptionsTagHelper : TagHelper
{
    public OptionsTagHelper(IHtmlGenerator generator)
    {
        Generator = generator;
    }

    [HtmlAttributeNotBound]
    public IHtmlGenerator Generator { get; set; }

    [HtmlAttributeName("asp-items")]
    public object Items { get; set; }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.SuppressOutput();
        // Is this <options /> element a child of a <select/> element the SelectTagHelper targeted?
        object formDataEntry;
        context.Items.TryGetValue(typeof(SelectTagHelper), out formDataEntry);

        var selectedValues = formDataEntry as ICollection<string>;
        var encodedValues = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
        if (selectedValues != null && selectedValues.Count != 0)
        {
            foreach (var selectedValue in selectedValues)
            {
                encodedValues.Add(Generator.Encode(selectedValue));
            }
        }

        IEnumerable<SelectListItem> items = null;
        if (Items != null)
        {
            if (Items is IEnumerable)
            {
                var enumerable = Items as IEnumerable;
                if (Items is IEnumerable<SelectListItem>)
                    items = Items as IEnumerable<SelectListItem>;
                else if (Items is IEnumerable<IIntegerListItem>)
                    items = ((IEnumerable<IIntegerListItem>)Items).Select(x => new SelectListItem() { Selected = false, Value = ((IIntegerListItem)x).Value.ToString(), Text = ((IIntegerListItem)x).Text });
                else
                    throw new InvalidOperationException(string.Format("The {2} was unable to provide metadata about '{1}' expression value '{3}' for <options>.",
                        "<options>",
                        "ForAttributeName",
                        nameof(IModelMetadataProvider),
                        "For.Name"));
            }
            else
            {
                throw new InvalidOperationException("Invalid items for <options>");
            }

            foreach (var item in items)
            {
                bool selected = (selectedValues != null && selectedValues.Contains(item.Value)) || encodedValues.Contains(item.Value);
                var selectedAttr = selected ? "selected='selected'" : "";

                if (item.Value != null)
                    output.Content.AppendHtml($"<option value='{item.Value}' {selectedAttr}>{item.Text}</option>");
                else
                    output.Content.AppendHtml($"<option>{item.Text}</option>");
            }
        }
    }
}

There may be some typo but the aim is clear I think. I had to edit a little bit.

Convert integer value to matching Java Enum

There is no way to elegantly handle integer-based enumerated types. You might think of using a string-based enumeration instead of your solution. Not a preferred way all the times, but it still exists.

public enum Port {
  /**
   * The default port for the push server.
   */
  DEFAULT("443"),

  /**
   * The alternative port that can be used to bypass firewall checks
   * made to the default <i>HTTPS</i> port.
   */
  ALTERNATIVE("2197");

  private final String portString;

  Port(final String portString) {
    this.portString = portString;
  }

  /**
   * Returns the port for given {@link Port} enumeration value.
   * @return The port of the push server host.
   */
  public Integer toInteger() {
    return Integer.parseInt(portString);
  }
}

Export to xls using angularjs

If you load your data into ng-grid, you can use the CSV export plugin. The plugin creates a button with the grid data as csv inside an href tag.

http://angular-ui.github.io/ng-grid/

https://github.com/angular-ui/ng-grid/blob/2.x/plugins/ng-grid-csv-export.js

Updating links as the library got renamed:

Github link: https://github.com/angular-ui/ui-grid

Library page: http://ui-grid.info/

Documentation on csv export : http://ui-grid.info/docs/#/tutorial/206_exporting_data

Easy way to make a confirmation dialog in Angular?

Method 1

One simple way to confirm is to use the native browser confirm alert. The template can have a button or link.

<button type=button class="btn btn-primary"  (click)="clickMethod('name')">Delete me</button>

And the component method can be something like below.

clickMethod(name: string) {
  if(confirm("Are you sure to delete "+name)) {
    console.log("Implement delete functionality here");
  }
}

Method 2

Another way to get a simple confirmation dialog is to use the angular bootstrap components like ng-bootstrap or ngx-bootstrap. You can simply install the component and use the modal component.

  1. Examples of modals using ng-bootstrap
  2. Examples of modals using ngx-bootstrap.

Method 3

Provided below is another way to implement a simple confirmation popup using angular2/material that I implemented in my project.

app.module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';

@NgModule({
  imports: [
    ...
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    ...
    ConfirmationDialog
  ],
  providers: [ ... ],
  bootstrap: [ AppComponent ],
  entryComponents: [ConfirmationDialog]
})
export class AppModule { }

confirmation-dialog.ts

import { Component, Input } from '@angular/core';
import { MdDialog, MdDialogRef } from '@angular/material';

@Component({
  selector: 'confirm-dialog',
  templateUrl: '/app/confirm-dialog/confirmation-dialog.html',
})
export class ConfirmationDialog {
  constructor(public dialogRef: MdDialogRef<ConfirmationDialog>) {}

  public confirmMessage:string;
}

confirmation-dialog.html

<h1 md-dialog-title>Confirm</h1>
<div md-dialog-content>{{confirmMessage}}</div>
<div md-dialog-actions>
  <button md-button style="color: #fff;background-color: #153961;" (click)="dialogRef.close(true)">Confirm</button>
  <button md-button (click)="dialogRef.close(false)">Cancel</button>
</div>

app.component.html

<button (click)="openConfirmationDialog()">Delete me</button>

app.component.ts

import { MdDialog, MdDialogRef } from '@angular/material';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';

@Component({
  moduleId: module.id,
  templateUrl: '/app/app.component.html',
  styleUrls: ['/app/main.css']
})

export class AppComponent implements AfterViewInit {
  dialogRef: MdDialogRef<ConfirmationDialog>;

  constructor(public dialog: MdDialog) {}

  openConfirmationDialog() {
    this.dialogRef = this.dialog.open(ConfirmationDialog, {
      disableClose: false
    });
    this.dialogRef.componentInstance.confirmMessage = "Are you sure you want to delete?"

    this.dialogRef.afterClosed().subscribe(result => {
      if(result) {
        // do confirmation actions
      }
      this.dialogRef = null;
    });
  }
}

index.html => added following stylesheet

<link rel="stylesheet" href="node_modules/@angular/material/core/theming/prebuilt/indigo-pink.css">

How is a JavaScript hash map implemented?

Should you try this class Map:

_x000D_
_x000D_
var myMap = new Map();_x000D_
_x000D_
// setting the values_x000D_
myMap.set("1", 'value1');_x000D_
myMap.set("2", 'value2');_x000D_
myMap.set("3", 'value3');_x000D_
_x000D_
myMap.size; // 3_x000D_
_x000D_
// getting the values_x000D_
myMap.get("1");    // "value associated with "value1"_x000D_
myMap.get("2");       // "value associated with "value1"_x000D_
myMap.get("3");      // "value associated with "value3"
_x000D_
_x000D_
_x000D_

Notice: key and value can be any type.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

How to add jQuery in JS file

You can create a master page base without included js and jquery files. Put a content place holder in master page base in head section, then create a nested master page that inherits from this master page base. Now put your includes in a asp:content in nested master page, finally create a content page from this nested master page

Example:

//in master page base    

<%@  master language="C#" autoeventwireup="true" inherits="MasterPage" codebehind="MasterPage.master.cs" %>
<html>
<head id="Head1" runat="server">
    <asp:ContentPlaceHolder runat="server" ID="cphChildHead">
        <!-- Nested Master Page include Codes will sit Here -->
    </asp:ContentPlaceHolder>
</head>
<body>
    <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
    </asp:ContentPlaceHolder>
    <!-- some code here -->
</body>
</html>

//in nested master page :
<%@  master language="C#" masterpagefile="~/MasterPage.master" autoeventwireup="true"
    codebehind="MasterPageLib.master.cs" inherits="sampleNameSpace" %>
<asp:Content ID="headcontent" ContentPlaceHolderID="cphChildHead" runat="server">
    <!-- includes will set here a nested master page -->
    <link href="../CSS/pwt-datepicker.css" rel="stylesheet" type="text/css" />

    <script src="../js/jquery-1.9.0.min.js" type="text/javascript"></script>

    <!-- other includes ;) -->
</asp:Content>
<asp:Content ID="bodyContent" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
    <asp:ContentPlaceHolder ID="cphChildBody" runat="server" EnableViewState="true">
        <!-- Content page code will sit Here -->
    </asp:ContentPlaceHolder>
</asp:Content>

Enable/disable buttons with Angular

Set a property for the current lesson: currentLesson. It will hold, obviously, the 'number' of the choosen lesson. On each button click, set the currentLesson value to 'number'/ order of the button, i.e. for the first button, it will be '1', for the second '2' and so on. Each button now can be disabled with [disabled] attribute, if it the currentLesson is not the same as it's order.

HTML

  <button  (click)="currentLesson = '1'"
         [disabled]="currentLesson !== '1'" class="primair">
           Start lesson</button>
  <button (click)="currentLesson = '2'"
         [disabled]="currentLesson !== '2'" class="primair">
           Start lesson</button>
 .....//so on

Typescript

currentLesson:string;

  classes = [
{
  name: 'string',
  level: 'string',
  code: 'number',
  currentLesson: '1'
}]

constructor(){
  this.currentLesson=this.classes[0].currentLesson
}

DEMO

Putting everything in a loop:

HTML

<div *ngFor="let class of classes; let i = index">
   <button [disabled]="currentLesson !== i + 1" class="primair">
           Start lesson {{i +  1}}</button>
</div>

Typescript

currentLesson:string;

classes = [
{
  name: 'Lesson1',
  level: 1,
  code: 1,
},{
  name: 'Lesson2',
  level: 1,
  code: 2,
},
{
  name: 'Lesson3',
  level: 2,
  code: 3,
}]

DEMO

How to insert text in a td with id, using JavaScript

There are several options... assuming you found your TD by var td = document.getElementyById('myTD_ID'); you can do:

  • td.innerHTML = "mytext";

  • td.textContent= "mytext";

  • td.innerText= "mytext"; - this one may not work outside IE? Not sure

  • Use firstChild or children array as previous poster noted.

If it's just the text that needs to be changed, textContent is faster and less prone to XSS attacks (https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent)

How does createOrReplaceTempView work in Spark?

CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.

first we read data in csv format and then convert to data frame and create a temp view

Reading data in csv format

val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")

printing the schema

data.printSchema

SchemaOfTable

data.createOrReplaceTempView("Data")

Now we can run sql queries on top the table view we just created

  %sql select Week as Date,Campaign Type,Engagements,Country from Data order     by Date asc

enter image description here

Transport endpoint is not connected

So interestingly enough this error "Transport endpoint is not connected" was caused by my having more than one Veracrypt device mounted. I closed the extra device and suddenly I had access to the drive. Hmm..

How do I add an integer value with javascript (jquery) to a value that's returning a string?

var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );

I simply fixed your month issue, getMonth array start from 0 to 11.

How do you read a CSV file and display the results in a grid in Visual Basic 2010?

For Each line As String In System.IO.File.ReadAllLines("D:\abc.csv")
    DataGridView1.Rows.Add(line.Split(","))
Next

List all the files and folders in a Directory with PHP recursive function

Here's a modified version of Hors answer, works slightly better for my case, as it strips out the base directory that is passed as it goes, and has a recursive switch that can be set to false which is also handy. Plus to make the output more readable, I've separated the file and subdirectory files, so the files are added first then the subdirectory files (see result for what I mean.)

I tried a few other methods and suggestions around and this is what I ended up with. I had another working method already that was very similar, but seemed to fail where there was a subdirectory with no files but that subdirectory had a subsubdirectory with files, it didn't scan the subsubdirectory for files - so some answers may need to be tested for that case.)... anyways thought I'd post my version here too in case someone is looking...

function get_filelist_as_array($dir, $recursive = true, $basedir = '', $include_dirs = false) {
    if ($dir == '') {return array();} else {$results = array(); $subresults = array();}
    if (!is_dir($dir)) {$dir = dirname($dir);} // so a files path can be sent
    if ($basedir == '') {$basedir = realpath($dir).DIRECTORY_SEPARATOR;}

    $files = scandir($dir);
    foreach ($files as $key => $value){
        if ( ($value != '.') && ($value != '..') ) {
            $path = realpath($dir.DIRECTORY_SEPARATOR.$value);
            if (is_dir($path)) {
                // optionally include directories in file list
                if ($include_dirs) {$subresults[] = str_replace($basedir, '', $path);}
                // optionally get file list for all subdirectories
                if ($recursive) {
                    $subdirresults = get_filelist_as_array($path, $recursive, $basedir, $include_dirs);
                    $results = array_merge($results, $subdirresults);
                }
            } else {
                // strip basedir and add to subarray to separate file list
                $subresults[] = str_replace($basedir, '', $path);
            }
        }
    }
    // merge the subarray to give the list of files then subdirectory files
    if (count($subresults) > 0) {$results = array_merge($subresults, $results);}
    return $results;
}

I suppose one thing to be careful of it not to pass a $basedir value to this function when calling it... mostly just pass the $dir (or passing a filepath will work now too) and optionally $recursive as false if and as needed. The result:

[0] => demo-image.png
[1] => filelist.php
[2] => tile.png
[3] => 2015\header.png
[4] => 2015\08\background.jpg

Enjoy! Okay, back to the program I'm actually using this in...

UPDATE Added extra argument for including directories in the file list or not (remembering other arguments will need to be passed to use this.) eg.

$results = get_filelist_as_array($dir, true, '', true);

Shortcut to create properties in Visual Studio?

Start from:

private int myVar;

When you select "myVar" and right click then select "Refactor" and select "Encapsulate Field".

It will automatically create:

{
    get { return myVar; }
    set { myVar = value; }
}

Or you can shortcut it by pressing Ctrl + R + E.

How do I remove all non alphanumeric characters from a string except dash?

Want something quick?

public static class StringExtensions 
{
    public static string ToAlphaNumeric(this string self, params char[] allowedCharacters)
    {
        return new string(Array.FindAll(self.ToCharArray(), c => char.IsLetterOrDigit(c) || allowedCharacters.Contains(c)));
    }
}

This will allow you to specify which characters you want to allow as well.

insert vertical divider line between two nested divs, not full height

Use a div for your divider. It will always be centered vertically regardless to whether left and right divs are equal in height. You can reuse it anywhere on your site.

.divider{
    position:absolute;
    left:50%;
    top:10%;
    bottom:10%;
    border-left:1px solid white;
}

Check working example at http://jsfiddle.net/gtKBs/

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

This should solve your problem. session_start() should be called before any character is sent back to the browser. In your case, HTML and blank lines were sent before you called session_start(). Documentation here.

To further explain your question of why it works when you submit to a different page, that page either do not use session_start() or calls session_start() before sending any character back to the client! This page on the other hand was calling session_start() much later when a lot of HTML has been sent back to the client (browser).

The better way to code is to have a common header file that calls connects to MySQL database, calls session_start() and does other common things for all pages and include that file on top of each page like below:

include "header.php";

This will stop issues like you are having as also allow you to have a common set of code to manage across a project. Something definitely for you to think about I would suggest after looking at your code.

<?php
session_start();

                if (isset($_SESSION['error']))

                {

                    echo "<span id=\"error\"><p>" . $_SESSION['error'] . "</p></span>";

                    unset($_SESSION['error']);

                }

                ?>

                <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">

                <p>
                 <label class="style4">Category Name</label>

                   &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <input type="text" name="categoryname" /><br /><br />

                    <label class="style4">Category Image</label>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

                    <input type="file" name="image" /><br />

                    <input type="hidden" name="MAX_FILE_SIZE" value="100000" />

                   <br />
<br />
 <input type="submit" id="submit" value="UPLOAD" />

                </p>

                </form>




                             <?php



require("includes/conn.php");


function is_valid_type($file)

{

    $valid_types = array("image/jpg", "image/jpeg", "image/bmp", "image/gif", "image/png");



    if (in_array($file['type'], $valid_types))

        return 1;

    return 0;
}

function showContents($array)

{

    echo "<pre>";

    print_r($array);

    echo "</pre>";
}


$TARGET_PATH = "images/category";

$cname = $_POST['categoryname'];

$image = $_FILES['image'];

$cname = mysql_real_escape_string($cname);

$image['name'] = mysql_real_escape_string($image['name']);

$TARGET_PATH .= $image['name'];

if ( $cname == "" || $image['name'] == "" )

{

    $_SESSION['error'] = "All fields are required";

    header("Location: managecategories.php");

    exit;

}

if (!is_valid_type($image))

{

    $_SESSION['error'] = "You must upload a jpeg, gif, or bmp";

    header("Location: managecategories.php");

    exit;

}




if (file_exists($TARGET_PATH))

{

    $_SESSION['error'] = "A file with that name already exists";

    header("Location: managecategories.php");

    exit;

}


if (move_uploaded_file($image['tmp_name'], $TARGET_PATH))

{



    $sql = "insert into Categories (CategoryName, FileName) values ('$cname', '" . $image['name'] . "')";

    $result = mysql_query($sql) or die ("Could not insert data into DB: " . mysql_error());

  header("Location: mangaecategories.php");

    exit;

}

else

{





    $_SESSION['error'] = "Could not upload file.  Check read/write persmissions on the directory";

    header("Location: mangagecategories.php");

    exit;

}

?> 

Watermark / hint text / placeholder TextBox

If rather than having the watermark's visibility depend on the control's focus state, you want it to depend on whether the user has entered any text, you can update John Myczek's answer (from OnWatermarkChanged down) to

static void OnWatermarkChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
    var textbox = (TextBox)d;
    textbox.Loaded += UpdateWatermark;
    textbox.TextChanged += UpdateWatermark;
}

static void UpdateWatermark(object sender, RoutedEventArgs e) {
    var textbox = (TextBox)sender;
    var layer = AdornerLayer.GetAdornerLayer(textbox);
    if (layer != null) {
        if (textbox.Text == string.Empty) {
            layer.Add(new WatermarkAdorner(textbox, GetWatermark(textbox)));
        } else {
            var adorners = layer.GetAdorners(textbox);
            if (adorners == null) {
                return;
            }

            foreach (var adorner in adorners) {
                if (adorner is WatermarkAdorner) {
                    adorner.Visibility = Visibility.Hidden;
                    layer.Remove(adorner);
                }
            }
        }
    }
}

This makes more sense if your textbox gets focus automatically when displaying the form, or when databinding to the Text property.

Also if your watermark is always just a string, and you need the style of the watermark to match the style of the textbox, then in the Adorner do:

contentPresenter = new ContentPresenter {
    Content = new TextBlock {
        Text = (string)watermark,
        Foreground = Control.Foreground,
        Background = Control.Background,
        FontFamily = Control.FontFamily,
        FontSize = Control.FontSize,
        ...
    },
    ...
}

Can not get a simple bootstrap modal to work

<div class="modal fade bs-example-modal-lg" id="{{'modal'+ cartModal.index}}">
  <div class="modal-dialog modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"  aria-label="Close"><span aria-hidden="true">&times;</span></button>
      </div>
      <div class="modal-body">
          <div class="col-lg-6" >
            <p class="prodTitle" ng-bind="(cartModal.product.p_name|uppercase)"></p>
            <p class="price-para">
              <span class="currency-cls" ng-bind="cartModal.product.c_currency"></span>
              <span class="price-cls" ng-bind="cartModal.product.p_price"></span>
            </p>
            <p class="select-color">
              <span ng-repeat="color in cartModal.product.p_available_options.colors">
                <button id="color-style" ng-click="cartModal.saveColor(color)" ng-style="{'background-color':color.hexcode}"></button>
              </span>
            </p>
            <br>
            <p class="select-box">
              <span class="size-select-cls">
                SIZE:<select ng-init="items=cartModal.product.p_available_options.sizes" ng-model="cartModal.selectedSize" ng-options="item.code as
                item.name for item in items"></select>
              </span>
              <span class="qty">
                QTY:<input type="number"  min="1" ng-model="cartModal.selectedQty"/>
              </span>
            </p>
            <p class="edit-button">
              <button class="btn-primary btn-lg" data-dismiss="modal" ng-click="cartModal.save();cartModal.calculate()">EDIT</button>
            </p>
          </div>
          <div class="col-lg-6">
            <img ng-src="{{cartModal.product.imageSrc}}">
          </div>
      </div>
    </div>
  </div>
</div>

Why my $.ajax showing "preflight is invalid redirect error"?

I received the same error when I tried to call https web service as http webservice.

e.g when I call url 'http://api.example.com/users/get'
which should be 'https://api.example.com/users/get'

This error is produced because of redirection status 302 when you try to call http instead of https.

Implementing a HashMap in C

The best approach depends on the expected key distribution and number of collisions. If relatively few collisions are expected, it really doesn't matter which method is used. If lots of collisions are expected, then which to use depends on the cost of rehashing or probing vs. manipulating the extensible bucket data structure.

But here is source code example of An Hashmap Implementation in C

Can a table have two foreign keys?

Yes, MySQL allows this. You can have multiple foreign keys on the same table.

Get more details here FOREIGN KEY Constraints

Locate Git installation folder on Mac OS X

you can simply use this command on a terminal to find out git on unix platforms (mac/linux) -

whereis git

This command should return something like - /usr/bin/git or any other location where git is installed

User Control - Custom Properties

Just add public properties to the user control.

You can add [Category("MyCategory")] and [Description("A property that controls the wossname")] attributes to make it nicer, but as long as it's a public property it should show up in the property panel.

Open a facebook link by native Facebook app on iOS

This will open the URL in Safari:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.facebook.com/comments.php?href=http://wombeta.jiffysoftware.com/ViewWOMPrint.aspx?WPID=317"]];

For the iphone, you can launch the Facebook app if installed by using a url starting with fb://

More information can be found here: http://iphonedevtools.com/?p=302 also here: http://wiki.akosma.com/IPhone_URL_Schemes#Facebook

Stolen from the above site:

fb://profile – Open Facebook app to the user’s profile
fb://friends – Open Facebook app to the friends list
fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app)
fb://feed – Open Facebook app to the News Feed
fb://events – Open Facebook app to the Events page
fb://requests – Open Facebook app to the Requests list
fb://notes - Open Facebook app to the Notes page
fb://albums – Open Facebook app to Photo Albums list

To launch the above URLs:

NSURL *theURL = [NSURL URLWithString:@"fb://<insert function here>"];
[[UIApplication sharedApplication] openURL:theURL];

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

How to extract img src, title and alt from html using php?

Here's A PHP Function I hobbled together from all of the above info for a similar purpose, namely adjusting image tag width and length properties on the fly ... a bit clunky, perhaps, but seems to work dependably:

function ReSizeImagesInHTML($HTMLContent,$MaximumWidth,$MaximumHeight) {

// find image tags
preg_match_all('/<img[^>]+>/i',$HTMLContent, $rawimagearray,PREG_SET_ORDER); 

// put image tags in a simpler array
$imagearray = array();
for ($i = 0; $i < count($rawimagearray); $i++) {
    array_push($imagearray, $rawimagearray[$i][0]);
}

// put image attributes in another array
$imageinfo = array();
foreach($imagearray as $img_tag) {

    preg_match_all('/(src|width|height)=("[^"]*")/i',$img_tag, $imageinfo[$img_tag]);
}

// combine everything into one array
$AllImageInfo = array();
foreach($imagearray as $img_tag) {

    $ImageSource = str_replace('"', '', $imageinfo[$img_tag][2][0]);
    $OrignialWidth = str_replace('"', '', $imageinfo[$img_tag][2][1]);
    $OrignialHeight = str_replace('"', '', $imageinfo[$img_tag][2][2]);

    $NewWidth = $OrignialWidth; 
    $NewHeight = $OrignialHeight;
    $AdjustDimensions = "F";

    if($OrignialWidth > $MaximumWidth) { 
        $diff = $OrignialWidth-$MaximumHeight; 
        $percnt_reduced = (($diff/$OrignialWidth)*100); 
        $NewHeight = floor($OrignialHeight-(($percnt_reduced*$OrignialHeight)/100)); 
        $NewWidth = floor($OrignialWidth-$diff); 
        $AdjustDimensions = "T";
    }

    if($OrignialHeight > $MaximumHeight) { 
        $diff = $OrignialHeight-$MaximumWidth; 
        $percnt_reduced = (($diff/$OrignialHeight)*100); 
        $NewWidth = floor($OrignialWidth-(($percnt_reduced*$OrignialWidth)/100)); 
        $NewHeight= floor($OrignialHeight-$diff); 
        $AdjustDimensions = "T";
    } 

    $thisImageInfo = array('OriginalImageTag' => $img_tag , 'ImageSource' => $ImageSource , 'OrignialWidth' => $OrignialWidth , 'OrignialHeight' => $OrignialHeight , 'NewWidth' => $NewWidth , 'NewHeight' => $NewHeight, 'AdjustDimensions' => $AdjustDimensions);
    array_push($AllImageInfo, $thisImageInfo);
}

// build array of before and after tags
$ImageBeforeAndAfter = array();
for ($i = 0; $i < count($AllImageInfo); $i++) {

    if($AllImageInfo[$i]['AdjustDimensions'] == "T") {
        $NewImageTag = str_ireplace('width="' . $AllImageInfo[$i]['OrignialWidth'] . '"', 'width="' . $AllImageInfo[$i]['NewWidth'] . '"', $AllImageInfo[$i]['OriginalImageTag']);
        $NewImageTag = str_ireplace('height="' . $AllImageInfo[$i]['OrignialHeight'] . '"', 'height="' . $AllImageInfo[$i]['NewHeight'] . '"', $NewImageTag);

        $thisImageBeforeAndAfter = array('OriginalImageTag' => $AllImageInfo[$i]['OriginalImageTag'] , 'NewImageTag' => $NewImageTag);
        array_push($ImageBeforeAndAfter, $thisImageBeforeAndAfter);
    }
}

// execute search and replace
for ($i = 0; $i < count($ImageBeforeAndAfter); $i++) {
    $HTMLContent = str_ireplace($ImageBeforeAndAfter[$i]['OriginalImageTag'],$ImageBeforeAndAfter[$i]['NewImageTag'], $HTMLContent);
}

return $HTMLContent;

}

How to run Java program in terminal with external library JAR

  1. you can set your classpath in the in the environment variabl CLASSPATH. in linux, you can add like CLASSPATH=.:/full/path/to/the/Jars, for example ..........src/external and just run in side ......src/Report/

Javac Reporter.java

java Reporter

Similarily, you can set it in windows environment variables. for example, in Win7

Right click Start-->Computer then Properties-->Advanced System Setting --> Advanced -->Environment Variables in the user variables, click classPath, and Edit and add the full path of jars at the end. voila

Get the Last Inserted Id Using Laravel Eloquent

Here's an example:

public static function saveTutorial(){

    $data = Input::all();

    $Tut = new Tutorial;
    $Tut->title = $data['title'];
    $Tut->tutorial = $data['tutorial'];   
    $Tut->save();
    $LastInsertId = $Tut->id;

    return Response::json(array('success' => true,'last_id'=>$LastInsertId), 200);
}

How do I pipe a subprocess call to a text file?

If you want to write the output to a file you can use the stdout-argument of subprocess.call.

It takes None, subprocess.PIPE, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.

You need to open a file with something like open and pass the object or file descriptor integer to call:

f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=f)

I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.

As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT. Any of the above mentioned values works as well, you can redirect to different places.

CodeIgniter : Unable to load the requested file:

An Error Was Encountered Unable to load the requested file:

Sometimes we face this error because the requested file doesn't exist in that directory.

Suppose we have a folder home in views directory and trying to load home_view.php file as:

$this->load->view('home/home_view', $data);// $data is array

If home_view.php file doesn't exist in views/home directory then it will raise an error.

An Error Was Encountered Unable to load the requested file: home\home_view.php

So how to fix this error go to views/home and check the home_view.php file exist if not then create it.

How can I get the IP address from NIC in Python?

Two methods:

Method #1 (use external package)

You need to ask for the IP address that is bound to your eth0 interface. This is available from the netifaces package

import netifaces as ni
ni.ifaddresses('eth0')
ip = ni.ifaddresses('eth0')[ni.AF_INET][0]['addr']
print ip  # should print "192.168.100.37"

You can also get a list of all available interfaces via

ni.interfaces()

Method #2 (no external package)

Here's a way to get the IP address without using a python package:

import socket
import fcntl
import struct

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

get_ip_address('eth0')  # '192.168.0.110'

Note: detecting the IP address to determine what environment you are using is quite a hack. Almost all frameworks provide a very simple way to set/modify an environment variable to indicate the current environment. Try and take a look at your documentation for this. It should be as simple as doing

if app.config['ENV'] == 'production':
  #send production email
else:
  #send development email

how to run the command mvn eclipse:eclipse

Besides the powerful options on the "Run Configurations.." on a well configured project you'll see the maven tasks on the Run As as well.

enter image description here

failed to find target with hash string android-23

There are 2 solutions to this issue:

1) Download the relevant Android SDK via Tools -> Android -> SDK Manager -> SDK Tools (ensure you have 'Show Package Details') checked. Your case would be Android 6.0 (Marshmallow / API level 21)

2) Alternatively, open your build.gradle file and update the following attributes :

  • compileSdkVersion
  • buildToolsVersion
  • targetSdkVersion

either to the most recent version of the Android API that you have installed / another installed version you'd like to use (although I'd always recommend going with the latest version for the usual reasons: bug fixes etc.)

If you're following step 2 it's also important that you remember to update the Android support library version if your app is using it. This can be found in the dependencies section of your build file and looks something like this:

compile 'com.android.support:appcompat-v7:27.0.2'

(replace 27.0.2 with the most recent support library version for the API level you intend to use with your app)

Send Email Intent

A late answer, although I figured out a solution which could help others:

Java version

Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
emailIntent.setData(Uri.parse("mailto:[email protected]"));
startActivity(Intent.createChooser(emailIntent, "Send feedback"));

Kotlin version

val emailIntent = Intent(Intent.ACTION_SENDTO).apply { 
    data = Uri.parse("mailto:[email protected]")
}
startActivity(Intent.createChooser(emailIntent, "Send feedback"))

This was my output (only Gmail + Inbox suggested):

my output

I got this solution from the Android Developers site.

! [rejected] master -> master (fetch first)

It's likely that someone else (e.g. your colleague) has put commits onto origin/master that aren't in your local master branch, and you are trying to push some commits from your local branch to the server. In 99% of cases, assuming you don't want to erase their work from origin, you have two options:

2) Merge their changes into your local branch, and then push the merged result. git checkout master git pull # resolve conflicts here git push

(Note that git pull is essentially just a git fetch and a git merge in this case.)

1) Rebase your local branch, so that it looks like your colleague made their commits first, and then you made your commits. This keeps the commit history nice and linear - and avoids a "merge commit". However, if you have conflicts with your colleague's changes, you may have to resolve those conflicts for each of your commits (rather than just once) in the worst case. Essentially this is nicer for everyone else but more effort for you. git pull --rebase # resolve conflicts here git push

(Note that git pull --rebase is essentially a git fetch and a git rebase origin/master.)

You have not concluded your merge (MERGE_HEAD exists)

In my case I had a cherry pick that produce a number of Merge Conflicts, so I decide to not complete the cherry pick. I discarded all my changes. Doing so put me into a state where I received the following error:

You have not concluded your merge (MERGE_HEAD exists

To fix the issue I performed the following git command which fixed the problem.

git cherry-pick --abort

How to add a new line of text to an existing file in Java?

In case you are looking for a cut and paste method that creates and writes to a file, here's one I wrote that just takes a String input. Remove 'true' from PrintWriter if you want to overwrite the file each time.

private static final String newLine = System.getProperty("line.separator");

private synchronized void writeToFile(String msg)  {
    String fileName = "c:\\TEMP\\runOutput.txt";
    PrintWriter printWriter = null;
    File file = new File(fileName);
    try {
        if (!file.exists()) file.createNewFile();
        printWriter = new PrintWriter(new FileOutputStream(fileName, true));
        printWriter.write(newLine + msg);
    } catch (IOException ioex) {
        ioex.printStackTrace();
    } finally {
        if (printWriter != null) {
            printWriter.flush();
            printWriter.close();
        }
    }
}

Why does ANT tell me that JAVA_HOME is wrong when it is not?

I was also facing the same problem. I am using Windows 7 and I had two versions of java installed. First I have installed latest version java 7 and then version 5.

Contents of my java installation directory:

C:\Program Files\Java>
jdk1.5.0_14
jdk1.7.0_17
jre1.5.0_14
jre7

and my JAVA_HOME was set to the correct value, which was:

C:\>set ja
JAVA_HOME=C:\Program Files\Java\jdk1.5.0_14

But still I was getting the same problem:

XXXXXXX\build.xml:478: The following error occurred while
executing this line:
XXXXXXX\build.xml:477: Unable to find a javac compiler;
com.sun.tools.javac.Main is not on the classpath.
Perhaps JAVA_HOME does not point to the JDK.
It is currently set to "C:\Program Files\Java\jre7"

After trying out all the suggestion in this thread I realized my mistake. I was trying to set the environment variable in "User variables" instead of "System Variables" section. After setting it in "System Variables" it worked fine. I am facing another problem though.

The default version of java it points to is still 7.

C:\>java -version
java version "1.7.0_17"
Java(TM) SE Runtime Environment (build 1.7.0_17-b02)
Java HotSpot(TM) Client VM (build 23.7-b01, mixed mode, sharing)

I am not sure how to make it point to version 5.

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Read the message:

Only one <configSections> element allowed per config file and if present must be the first child of the root <configuration> element.

Move the configSections element to the top - just above where system.data is currently.

SQL comment header examples

We use something like this and very useful for me .

/*  
Description:   
Author:   
Create Date: 
Param:   
Return:   
Modified Date:  
Modification:   
*/  

Get checkbox list values with jQuery

You can try this...

$(document).ready(function() {
        $("button").click(function(){
            var checkBoxValues = [];
            $.each($("input[name='check_name']:checked"), function(){
                checkBoxValues.push($(this).val());
            });

            console.log(checkBoxValues);

        });
    });

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

Now Gapps provide way to install gapps package thorough apk.

Download APK and installation instruction from below link:

http://opengapps.org/app/

You can download current APK from below link:

Play store link: https://play.google.com/store/apps/details?id=org.opengapps.app

Current version Website Link (7/22/2017): http://opengapps.org/app/opengapps-app-v16.apk

enter image description here

What is the difference between ng-if and ng-show/ng-hide

The ng-if directive removes the content from the page and ng-show/ng-hide uses the CSS display property to hide content.

This is useful in case you want to use :first-child and :last-child pseudo selectors to style.

Accessing an array out of bounds gives no error, why?

Welcome to every C/C++ programmer's bestest friend: Undefined Behavior.

There is a lot that is not specified by the language standard, for a variety of reasons. This is one of them.

In general, whenever you encounter undefined behavior, anything might happen. The application may crash, it may freeze, it may eject your CD-ROM drive or make demons come out of your nose. It may format your harddrive or email all your porn to your grandmother.

It may even, if you are really unlucky, appear to work correctly.

The language simply says what should happen if you access the elements within the bounds of an array. It is left undefined what happens if you go out of bounds. It might seem to work today, on your compiler, but it is not legal C or C++, and there is no guarantee that it'll still work the next time you run the program. Or that it hasn't overwritten essential data even now, and you just haven't encountered the problems, that it is going to cause — yet.

As for why there is no bounds checking, there are a couple aspects to the answer:

  • An array is a leftover from C. C arrays are about as primitive as you can get. Just a sequence of elements with contiguous addresses. There is no bounds checking because it is simply exposing raw memory. Implementing a robust bounds-checking mechanism would have been almost impossible in C.
  • In C++, bounds-checking is possible on class types. But an array is still the plain old C-compatible one. It is not a class. Further, C++ is also built on another rule which makes bounds-checking non-ideal. The C++ guiding principle is "you don't pay for what you don't use". If your code is correct, you don't need bounds-checking, and you shouldn't be forced to pay for the overhead of runtime bounds-checking.
  • So C++ offers the std::vector class template, which allows both. operator[] is designed to be efficient. The language standard does not require that it performs bounds checking (although it does not forbid it either). A vector also has the at() member function which is guaranteed to perform bounds-checking. So in C++, you get the best of both worlds if you use a vector. You get array-like performance without bounds-checking, and you get the ability to use bounds-checked access when you want it.

how to use LIKE with column name

declare @LkeVal as Varchar(100)
declare @LkeSelect Varchar(100)

Set @LkeSelect = (select top 1 <column> from <table> where <column> = 'value')
Set @LkeVal = '%' + @LkeSelect

select * from <table2> where <column2> like(''+@LkeVal+'');

Node: log in a file instead of the console

Straight from nodejs's API docs on Console

const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
const count = 5;
logger.log('count: %d', count);
// in stdout.log: count 5

How to get the mysql table columns data type?

SHOW COLUMNS FROM mytable

Self contained complete examples are often useful.

<?php
  // The server where your database is hosted                 localhost
  // The name of your database                                mydatabase
  // The user name of the database user                       databaseuser
  // The password of the database user                        thesecretpassword
  // Most web pages are in utf-8 so should be the database    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")
  try
  {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "databaseuser", "thesecretpassword", array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));  
  }
    catch(PDOException $e)
  {
    die('Could not connect: ' . $e->getMessage());
  }

  $sql   = "SHOW COLUMNS FROM mytable";
  $query = $pdo->prepare($sql);
  $query->execute();

  $err = $query->errorInfo();
  $bug = $err[2];

  if ($bug != "") { echo "<p>$bug</p>"; }

  while ($row = $query->fetch(PDO::FETCH_ASSOC))
  {
    echo "<pre>" . print_r($row, true) . "</pre>";
  }

  /* OUTPUT SAMPLE  
  Array
  (
      [Field] => page_id
      [Type] => char(40)
      [Null] => NO
      [Key] => 
      [Default] => 
      [Extra] => 
  )

  Array
  (  
      [Field] => last_name
      [Type] => char(50)
      More ...
  */
?>

How do I implement __getattribute__ without an infinite recursion error?

Actually, I believe you want to use the __getattr__ special method instead.

Quote from the Python docs:

__getattr__( self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.

Note: for this to work, the instance should not have a test attribute, so the line self.test=20 should be removed.

How to send string from one activity to another?

TWO CASES

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

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

Now let's see the two cases

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

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

It is very straightforward.

In Activity A.

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

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

In Activity B

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

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

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

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

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

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

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

Again in Activity A
1) Override onActivityResult method

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

Further understanding of Case 2

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

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

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

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

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

Relevant Links

Read more on Getting result

How to use global variable in node.js?

you can define it with using global or GLOBAL, nodejs supports both.

for e.g

global.underscore = require("underscore");

or

GLOBAL.underscore = require("underscore");

Javascript - get array of dates between 2 dates

I use moment.js and Twix.js they provide a very great support for date and time manpulation

var itr = moment.twix(new Date('2012-01-15'),new Date('2012-01-20')).iterate("days");
var range=[];
while(itr.hasNext()){
    range.push(itr.next().toDate())
}
console.log(range);

I have this running on http://jsfiddle.net/Lkzg1bxb/

How to make <a href=""> link look like a button?

  1. Try this:

    _x000D_
    _x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    _x000D_
    <div class="container">_x000D_
      <h2>Button Tags</h2>_x000D_
      <a href="#" class="btn btn-info" role="button">Link Button</a>_x000D_
      <button type="button" class="btn btn-info">Button</button>_x000D_
      <input type="button" class="btn btn-info" value="Input Button">_x000D_
      <input type="submit" class="btn btn-info" value="Submit Button">_x000D_
    </div>
    _x000D_
    _x000D_
    _x000D_

  2. You can use the a href tag line from there.

    <a href="URL" class="btn btn-info" role="button">Button Text</a>
    

Standardize data columns in R

When I used the solution stated by Dason, instead of getting a data frame as a result, I got a vector of numbers (the scaled values of my df).

In case someone is having the same trouble, you have to add as.data.frame() to the code, like this:

df.scaled <- as.data.frame(scale(df))

I hope this is will be useful for ppl having the same issue!

Rounded corner for textview in android

create an xml gradient.xml file under drawable folder

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle"  >
            <corners android:radius="50dip" />
            <stroke android:width="1dip" android:color="#667162" />
            <gradient android:angle="-90" android:startColor="#ffffff" android:endColor="#ffffff" />
        </shape>
    </item>
</selector>

then add this to your TextView

android:background="@drawable/gradient"

fatal: does not appear to be a git repository

This is typically because you have not set the origin alias on your Git repository.

Try

git remote add origin URL_TO_YOUR_REPO

This will add an alias in your .git/config file for the remote clone/push/pull site URL. This URL can be found on your repository Overview page.

Pure css close button

My attempt at a close icon, no text

_x000D_
_x000D_
.close-icon_x000D_
{_x000D_
  display:block;_x000D_
  box-sizing:border-box;_x000D_
  width:20px;_x000D_
  height:20px;_x000D_
  border-width:3px;_x000D_
  border-style: solid;_x000D_
  border-color:red;_x000D_
  border-radius:100%;_x000D_
  background: -webkit-linear-gradient(-45deg, transparent 0%, transparent 46%, white 46%,  white 56%,transparent 56%, transparent 100%), -webkit-linear-gradient(45deg, transparent 0%, transparent 46%, white 46%,  white 56%,transparent 56%, transparent 100%);_x000D_
  background-color:red;_x000D_
  box-shadow:0px 0px 5px 2px rgba(0,0,0,0.5);_x000D_
  transition: all 0.3s ease;_x000D_
}
_x000D_
<a href="#" class="close-icon"></a>
_x000D_
_x000D_
_x000D_

MemoryStream - Cannot access a closed Stream

The problem is this block:

using (var sr = new StreamReader(ms))
{
    Console.WriteLine(sr.ReadToEnd());                        
}

When the StreamReader is closed (after leaving the using), it closes it's underlying stream as well, so now the MemoryStream is closed. When the StreamWriter gets closed, it tries to flush everything to the MemoryStream, but it is closed.

You should consider not putting the StreamReader in a using block.

Listing only directories using ls in Bash?

Using Perl:

ls | perl -nle 'print if -d;'

Centering a canvas

Looking at the current answers I feel that one easy and clean fix is missing. Just in case someone passes by and looks for the right solution. I am quite successful with some simple CSS and javascript.

Center canvas to middle of the screen or parent element. No wrapping.

HTML:

<canvas id="canvas" width="400" height="300">No canvas support</canvas>

CSS:

#canvas {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin:auto;
}

Javascript:

window.onload = window.onresize = function() {
    var canvas = document.getElementById('canvas');
    canvas.width = window.innerWidth * 0.8;
    canvas.height = window.innerHeight * 0.8;
}

Works like a charm - tested: firefox, chrome

fiddle: http://jsfiddle.net/djwave28/j6cffppa/3/

No Title Bar Android Theme

Why are you changing android os inbuilt theme.

As per your activity Require You have to implements this way

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

as per @arianoo says you have to used this feature.

I think this is better way to hide titlebar theme.

Lists in ConfigParser

I completed similar task in my project with section with keys without values:

import configparser

# allow_no_value param says that no value keys are ok
config = configparser.ConfigParser(allow_no_value=True)

# overwrite optionxform method for overriding default behaviour (I didn't want lowercased keys)
config.optionxform = lambda optionstr: optionstr

config.read('./app.config')

features = list(config['FEATURES'].keys())

print(features)

Output:

['BIOtag', 'TextPosition', 'IsNoun', 'IsNomn']

app.config:

[FEATURES]
BIOtag
TextPosition
IsNoun
IsNomn

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

UPDATE: Turned my solution into a stand-alone python script.

This solution has saved me more than once. Hopefully others find it useful. This python script will find any jupyter kernel using more than cpu_threshold CPU and prompts the user to send a SIGINT to the kernel (KeyboardInterrupt). It will keep sending SIGINT until the kernel's cpu usage goes below cpu_threshold. If there are multiple misbehaving kernels it will prompt the user to interrupt each of them (ordered by highest CPU usage to lowest). A big thanks goes to gcbeltramini for writing code to find the name of a jupyter kernel using the jupyter api. This script was tested on MACOS with python3 and requires jupyter notebook, requests, json and psutil.

Put the script in your home directory and then usage looks like:

python ~/interrupt_bad_kernels.py
Interrupt kernel chews cpu.ipynb; PID: 57588; CPU: 2.3%? (y/n) y

Script code below:

from os import getpid, kill
from time import sleep
import re
import signal

from notebook.notebookapp import list_running_servers
from requests import get
from requests.compat import urljoin
import ipykernel
import json
import psutil


def get_active_kernels(cpu_threshold):
    """Get a list of active jupyter kernels."""
    active_kernels = []
    pids = psutil.pids()
    my_pid = getpid()

    for pid in pids:
        if pid == my_pid:
            continue
        try:
            p = psutil.Process(pid)
            cmd = p.cmdline()
            for arg in cmd:
                if arg.count('ipykernel'):
                    cpu = p.cpu_percent(interval=0.1)
                    if cpu > cpu_threshold:
                        active_kernels.append((cpu, pid, cmd))
        except psutil.AccessDenied:
            continue
    return active_kernels


def interrupt_bad_notebooks(cpu_threshold=0.2):
    """Interrupt active jupyter kernels. Prompts the user for each kernel."""

    active_kernels = sorted(get_active_kernels(cpu_threshold), reverse=True)

    servers = list_running_servers()
    for ss in servers:
        response = get(urljoin(ss['url'].replace('localhost', '127.0.0.1'), 'api/sessions'),
                       params={'token': ss.get('token', '')})
        for nn in json.loads(response.text):
            for kernel in active_kernels:
                for arg in kernel[-1]:
                    if arg.count(nn['kernel']['id']):
                        pid = kernel[1]
                        cpu = kernel[0]
                        interrupt = input(
                            'Interrupt kernel {}; PID: {}; CPU: {}%? (y/n) '.format(nn['notebook']['path'], pid, cpu))
                        if interrupt.lower() == 'y':
                            p = psutil.Process(pid)
                            while p.cpu_percent(interval=0.1) > cpu_threshold:
                                kill(pid, signal.SIGINT)
                                sleep(0.5)

if __name__ == '__main__':
    interrupt_bad_notebooks()

Codeigniter - multiple database connections

If you need to connect to more than one database simultaneously you can do so as follows:

$DB1 = $this->load->database('group_one', TRUE);
$DB2 = $this->load->database('group_two', TRUE);

Note: Change the words “group_one” and “group_two” to the specific group names you are connecting to (or you can pass the connection values as indicated above).

By setting the second parameter to TRUE (boolean) the function will return the database object.

Visit https://www.codeigniter.com/userguide3/database/connecting.html for further information.

How to mention C:\Program Files in batchfile

use this as somethink

"C:/Program Files (x86)/Nox/bin/nox_adb" install -r app.apk

where

"path_to_executable" commands_argument

Javascript: console.log to html

Slight improvement on @arun-p-johny answer:

In html,

<pre id="log"></pre>

In js,

(function () {
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function () {
      for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '<br />';
        } else {
            logger.innerHTML += arguments[i] + '<br />';
        }
      }
    }
})();

Start using:

console.log('How', true, new Date());

Register DLL file on Windows Server 2008 R2

You might need to register this DLL using the 32 bit version of regsvr32.exe:

c:\windows\syswow64\regsvr32 c:\tempdl\temp12.dll

How to redirect 404 errors to a page in ExpressJS?

The answer to your question is:

app.use(function(req, res) {
    res.status(404).end('error');
});

And there is a great article about why it is the best way here.

Best way to structure a tkinter application?

I personally do not use the objected oriented approach, mostly because it a) only get in the way; b) you will never reuse that as a module.

but something that is not discussed here, is that you must use threading or multiprocessing. Always. otherwise your application will be awful.

just do a simple test: start a window, and then fetch some URL or anything else. changes are your UI will not be updated while the network request is happening. Meaning, your application window will be broken. depend on the OS you are on, but most times, it will not redraw, anything you drag over the window will be plastered on it, until the process is back to the TK mainloop.

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

I had a similar problem when posting to the WebAPI endpoint. By turning the CustomErrors=Off, i was able to see the actual error which is one of the dlls was missing.

Is it possible to capture the stdout from the sh DSL command in the pipeline

I had the same issue and tried almost everything then found after I came to know I was trying it in the wrong block. I was trying it in steps block whereas it needs to be in the environment block.

        stage('Release') {
                    environment {
                            my_var = sh(script: "/bin/bash ${assign_version} || ls ", , returnStdout: true).trim()
                                }
                    steps {                                 
                            println my_var
                            }
                }

Scala check if element is present in a list

Even easier!

strings contains myString

Fixing Segmentation faults in C++

I don't know of any methodology to use to fix things like this. I don't think it would be possible to come up with one either for the very issue at hand is that your program's behavior is undefined (I don't know of any case when SEGFAULT hasn't been caused by some sort of UB).

There are all kinds of "methodologies" to avoid the issue before it arises. One important one is RAII.

Besides that, you just have to throw your best psychic energies at it.

What is the Python equivalent of Matlab's tic and toc functions?

You can use tic and toc from ttictoc. Install it with

pip install ttictoc

And just import them in your script as follow

from ttictoc import tic,toc
tic()
# Some code
print(toc())

When do you use POST and when do you use GET?

Gorgapor, mod_rewrite still often utilizes GET. It just allows to translate a friendlier URL into a URL with a GET query string.

Set bootstrap modal body height by percentage

Instead of using a %, the units vh set it to a percent of the viewport (browser window) size.

I was able to set a modal with an image and text beneath to be responsive to the browser window size using vh.

If you just want the content to scroll, you could leave out the part that limits the size of the modal body.

/*When the modal fills the screen it has an even 2.5% on top and bottom*/
/*Centers the modal*/
.modal-dialog {
  margin: 2.5vh auto;
}

/*Sets the maximum height of the entire modal to 95% of the screen height*/
.modal-content {
  max-height: 95vh;
  overflow: scroll;
}

/*Sets the maximum height of the modal body to 90% of the screen height*/
.modal-body {
  max-height: 90vh;
}
/*Sets the maximum height of the modal image to 69% of the screen height*/
.modal-body img {
  max-height: 69vh;
}

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

Add System.Web.Extensions as a reference to your project

enter image description here

For Ref.

Declare a constant array

As others have mentioned, there is no official Go construct for this. The closest I can imagine would be a function that returns a slice. In this way, you can guarantee that no one will manipulate the elements of the original slice (as it is "hard-coded" into the array).

I have shortened your slice to make it...shorter...:

func GetLetterGoodness() []float32 {
    return []float32 { .0817,.0149,.0278,.0425,.1270,.0223 }
}

How do I perform an insert and return inserted identity with Dapper?

The InvalidCastException you are getting is due to SCOPE_IDENTITY being a Decimal(38,0).

You can return it as an int by casting it as follows:

string sql = @"
INSERT INTO [MyTable] ([Stuff]) VALUES (@Stuff);
SELECT CAST(SCOPE_IDENTITY() AS INT)";

int id = connection.Query<int>(sql, new { Stuff = mystuff}).Single();

Remove all occurrences of char from string

I like using RegEx in this occasion:

str = str.replace(/X/g, '');

where g means global so it will go through your whole string and replace all X with ''; if you want to replace both X and x, you simply say:

str = str.replace(/X|x/g, '');

(see my fiddle here: fiddle)

EF 5 Enable-Migrations : No context type was found in the assembly

Adding a class which inherits DbContext resolved my problem:

public class MyDbContext : DbContext { public MyDbContext() { } }

MD5 hashing in Android

Useful Kotlin Extension Function Example

fun String.toMD5(): String {
    val bytes = MessageDigest.getInstance("MD5").digest(this.toByteArray())
    return bytes.toHex()
}

fun ByteArray.toHex(): String {
    return joinToString("") { "%02x".format(it) }
}

Is it possible to delete an object's property in PHP?

This code is working fine for me in a loop

$remove = array(
    "market_value",
    "sector_id"
);

foreach($remove as $key){
    unset($obj_name->$key);
}

Invalid length for a Base-64 char array

My initial guess without knowing the data would be that the UserNameToVerify is not a multiple of 4 in length. Check out the FromBase64String on msdn.

// Ok
byte[] b1 = Convert.FromBase64String("CoolDude");
// Exception
byte[] b2 = Convert.FromBase64String("MyMan");

What are the differences between Visual Studio Code and Visual Studio?

Visual Studio (full version) is a "full-featured" and "convenient" development environment.

Visual Studio (free "Express" versions - only until 2017) are feature-centered and simplified versions of the full version. Feature-centered meaning that there are different versions (Visual Studio Web Developer, Visual Studio C#, etc.) depending on your goal.

Visual Studio (free Community edition - since 2015) is a simplified version of the full version and replaces the separated express editions used before 2015.

Visual Studio Code (VSCode) is a cross-platform (Linux, Mac OS, Windows) editor that can be extended with plugins to your needs.

For example, if you want to create an ASP.NET application using Visual Studio Code you need to perform several steps on your own to setup the project. There is a separate tutorial for each OS.

How to configure static content cache per folder and extension in IIS7?

You can set specific cache-headers for a whole folder in either your root web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- Note the use of the 'location' tag to specify which 
       folder this applies to-->
  <location path="images">
    <system.webServer>
      <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
      </staticContent>
    </system.webServer>
  </location>
</configuration>

Or you can specify these in a web.config file in the content folder:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
    </staticContent>
  </system.webServer>
</configuration>

I'm not aware of a built in mechanism to target specific file types.

How can I hide the Adobe Reader toolbar when displaying a PDF in the .NET WebBrowser control?

It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.

The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:

   Adobe Reader Preferences dialog

You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:

   Adobe Reader Read Mode toolbar button

Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:

#toolbar=0&navpanes=0

So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.

string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);

You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.

URL to load resources from the classpath in Java

I've created a class which helps to reduce errors in setting up custom handlers and takes advantage of the system property so there are no issues with calling a method first or not being in the right container. There's also an exception class if you get things wrong:

CustomURLScheme.java:
/*
 * The CustomURLScheme class has a static method for adding cutom protocol
 * handlers without getting bogged down with other class loaders and having to
 * call setURLStreamHandlerFactory before the next guy...
 */
package com.cybernostics.lib.net.customurl;

import java.net.URLStreamHandler;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Allows you to add your own URL handler without running into problems
 * of race conditions with setURLStream handler.
 * 
 * To add your custom protocol eg myprot://blahblah:
 * 
 * 1) Create a new protocol package which ends in myprot eg com.myfirm.protocols.myprot
 * 2) Create a subclass of URLStreamHandler called Handler in this package
 * 3) Before you use the protocol, call CustomURLScheme.add(com.myfirm.protocols.myprot.Handler.class);
 * @author jasonw
 */
public class CustomURLScheme
{

    // this is the package name required to implelent a Handler class
    private static Pattern packagePattern = Pattern.compile( "(.+\\.protocols)\\.[^\\.]+" );

    /**
     * Call this method with your handlerclass
     * @param handlerClass
     * @throws Exception 
     */
    public static void add( Class<? extends URLStreamHandler> handlerClass ) throws Exception
    {
        if ( handlerClass.getSimpleName().equals( "Handler" ) )
        {
            String pkgName = handlerClass.getPackage().getName();
            Matcher m = packagePattern.matcher( pkgName );

            if ( m.matches() )
            {
                String protocolPackage = m.group( 1 );
                add( protocolPackage );
            }
            else
            {
                throw new CustomURLHandlerException( "Your Handler class package must end in 'protocols.yourprotocolname' eg com.somefirm.blah.protocols.yourprotocol" );
            }

        }
        else
        {
            throw new CustomURLHandlerException( "Your handler class must be called 'Handler'" );
        }
    }

    private static void add( String handlerPackage )
    {
        // this property controls where java looks for
        // stream handlers - always uses current value.
        final String key = "java.protocol.handler.pkgs";

        String newValue = handlerPackage;
        if ( System.getProperty( key ) != null )
        {
            final String previousValue = System.getProperty( key );
            newValue += "|" + previousValue;
        }
        System.setProperty( key, newValue );
    }
}


CustomURLHandlerException.java:
/*
 * Exception if you get things mixed up creating a custom url protocol
 */
package com.cybernostics.lib.net.customurl;

/**
 *
 * @author jasonw
 */
public class CustomURLHandlerException extends Exception
{

    public CustomURLHandlerException(String msg )
    {
        super( msg );
    }

}

Inserting data into a MySQL table using VB.NET

your str_carSql should be exactly like this:

str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (@id,@m_id,@model,@color,@ch_id,@pt_num,@code)"

Good Luck

What is Domain Driven Design?

Here is another good article that you may check out on Domain Driven Design. if your application is anything serious than college assignment. The basic premise is structure everything around your entities and have a strong domain model. Differentiate between services that provide infrastructure related things (like sending email, persisting data) and services that actually do things that are your core business requirments.

Hope that helps.

How do I indent multiple lines at once in Notepad++?

If you're using QuickText and like pressing Tab for it, you can otherwise change the indentation key.

Go Settings > Shortcup Mapper > Scintilla Command. Look at the number 10.

  • I changed 10 to : CTRL + ALT + RIGHT and
  • 11 to : CTRL+ ALT+ LEFT.

Now I think it's even better than the TABL / SHIFT + TAB as default.

Cannot import XSSF in Apache POI

If you use Maven:

poi => poi-ooxml in artifactId

    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi-ooxml</artifactId>
        <version>3.12</version>
    </dependency>

"Cannot allocate an object of abstract type" error

In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.

If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.

From your snippet Your class AliceUniversity seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate and UniversityGraduate.

Pure virtual functions are the ones with = 0; at the end of declaration.

Example: virtual void doSomething() = 0;

For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

I created a script to ignore differences in line endings:

It will display the files which are not added to the commit list and were modified (after ignoring differences in line endings). You can add the argument "add" to add those files to your commit.

#!/usr/bin/perl

# Usage: ./gitdiff.pl [add]
#    add : add modified files to git

use warnings;
use strict;

my ($auto_add) = @ARGV;
if(!defined $auto_add) {
    $auto_add = "";
}

my @mods = `git status --porcelain 2>/dev/null | grep '^ M ' | cut -c4-`;
chomp(@mods);
for my $mod (@mods) {
    my $diff = `git diff -b $mod 2>/dev/null`;
    if($diff) {
        print $mod."\n";
        if($auto_add eq "add") {
            `git add $mod 2>/dev/null`;
        }
    }
}

Source code: https://github.com/lepe/scripts/blob/master/gitdiff.pl

Updates:

  • fix by evandro777 : When the file has space in filename or directory

MySQL user DB does not have password columns - Installing MySQL on OSX

Use the ALTER USER command rather than trying to update a USER row. Keep in mind that there may be more than one 'root' user, because user entities are qualified also by the machine from which they connect

https://dev.mysql.com/doc/refman/5.7/en/alter-user.html

For example.

ALTER USER 'root'@'localhost' IDENTIFIED BY 'new-password' 
ALTER USER 'root'@'*' IDENTIFIED BY 'new-password' 

Regex to match only letters

Use a character set: [a-zA-Z] matches one letter from A–Z in lowercase and uppercase. [a-zA-Z]+ matches one or more letters and ^[a-zA-Z]+$ matches only strings that consist of one or more letters only (^ and $ mark the begin and end of a string respectively).

If you want to match other letters than A–Z, you can either add them to the character set: [a-zA-ZäöüßÄÖÜ]. Or you use predefined character classes like the Unicode character property class \p{L} that describes the Unicode characters that are letters.

How do I activate a specific workbook and a specific sheet?

You have to set a reference to the workbook you're opening. Then you can do anything you want with that workbook by using its reference.

Dim wkb As Workbook
Set wkb = Workbooks.Open("Tire.xls") ' open workbook and set reference!

wkb.Sheets("Sheet1").Activate
wkb.Sheets("Sheet1").Cells(2, 1).Value = 123

Could even set a reference to the sheet, which will make life easier later:

Dim wkb As Workbook
Dim sht As Worksheet

Set wkb = Workbooks.Open("Tire.xls")
Set sht = wkb.Sheets("Sheet2")

sht.Activate
sht.Cells(2, 1) = 123

Others have pointed out that .Activate may be superfluous in your case. You don't strictly need to activate a sheet before editing its cells. But, if that's what you want to do, it does no harm to activate -- except for a small hit to performance which should not be noticeable as long as you do it only once or a few times. However, if you activate many times e.g. in a loop, it will slow things down significantly, so activate should be avoided.

How do I define global variables in CoffeeScript?

You can pass -b option when you compile code via coffee-script under node.js. The compiled code will be the same as on coffeescript.org.

Transform char array into String

Visit https://www.arduino.cc/en/Reference/StringConstructor to solve the problem easily.

This worked for me:

char yyy[6];

String xxx;

yyy[0]='h';

yyy[1]='e';

yyy[2]='l';

yyy[3]='l';

yyy[4]='o';

yyy[5]='\0';

xxx=String(yyy);

How can I plot a histogram such that the heights of the bars sum to 1 in matplotlib?

I know this answer is too late considering the question is dated 2010 but I came across this question as I was facing a similar problem myself. As already stated in the answer, normed=True means that the total area under the histogram is equal to 1 but the sum of heights is not equal to 1. However, I wanted to, for convenience of physical interpretation of a histogram, make one with sum of heights equal to 1.

I found a hint in the following question - Python: Histogram with area normalized to something other than 1

But I was not able to find a way of making bars mimic the histtype="step" feature hist(). This diverted me to : Matplotlib - Stepped histogram with already binned data

If the community finds it acceptable I should like to put forth a solution which synthesises ideas from both the above posts.

import matplotlib.pyplot as plt

# Let X be the array whose histogram needs to be plotted.
nx, xbins, ptchs = plt.hist(X, bins=20)
plt.clf() # Get rid of this histogram since not the one we want.

nx_frac = nx/float(len(nx)) # Each bin divided by total number of objects.
width = xbins[1] - xbins[0] # Width of each bin.
x = np.ravel(zip(xbins[:-1], xbins[:-1]+width))
y = np.ravel(zip(nx_frac,nx_frac))

plt.plot(x,y,linestyle="dashed",label="MyLabel")
#... Further formatting.

This has worked wonderfully for me though in some cases I have noticed that the left most "bar" or the right most "bar" of the histogram does not close down by touching the lowest point of the Y-axis. In such a case adding an element 0 at the begging or the end of y achieved the necessary result.

Just thought I'd share my experience. Thank you.

There can be only one auto column

My MySQL says "Incorrect table definition; there can be only one auto column and it must be defined as a key" So when I added primary key as below it started working:

CREATE TABLE book (
   id INT AUTO_INCREMENT NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL,
   primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Comparing two files in linux terminal

Also, do not forget about mcdiff - Internal diff viewer of GNU Midnight Commander.

For example:

mcdiff file1 file2

Enjoy!

AngularJS access parent scope from child controller

I believe I had a similar quandary recently

function parentCtrl() {
   var pc = this; // pc stands for parent control
   pc.foobar = 'SomeVal';
}

function childCtrl($scope) {

   // now how do I get the parent control 'foobar' variable?
   // I used $scope.$parent

   var parentFoobarVariableValue = $scope.$parent.pc.foobar;

   // that did it
}

My setup was a little different, but the same thing should probably still work

HTTP Error 503. The service is unavailable. App pool stops on accessing website

When I first time add the service and created the app pool for it. I did "iisreset" from command prompt, and it worked.

PHP - Check if two arrays are equal

if (array_diff($a,$b) == array_diff($b,$a)) {
  // Equals
}

if (array_diff($a,$b) != array_diff($b,$a)) {
  // Not Equals
}

From my pov it's better to use array_diff than array_intersect because with checks of this nature the differences returned commonly are less than the similarities, this way the bool conversion is less memory hungry.

Edit Note that this solution is for plain arrays and complements the == and === one posted above that is only valid for dictionaries.

Is it possible to set UIView border properties from interface builder?

For Swift 3 and 4, if you're willing to use IBInspectables, there's this:

@IBDesignable extension UIView {
    @IBInspectable var borderColor:UIColor? {
        set {
            layer.borderColor = newValue!.cgColor
        }
        get {
            if let color = layer.borderColor {
                return UIColor(cgColor: color)
            }
            else {
                return nil
            }
        }
    }
    @IBInspectable var borderWidth:CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }
    @IBInspectable var cornerRadius:CGFloat {
        set {
            layer.cornerRadius = newValue
            clipsToBounds = newValue > 0
        }
        get {
            return layer.cornerRadius
        }
    }
}

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 can I check if character in a string is a letter? (Python)

This works:

any(c.isalpha() for c in 'string')

Transpose a matrix in Python

Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)

import numpy as np

a = np.array([(1,2,3), (4,5,6)])

b = a.transpose()

How to delete all rows from all tables in a SQL Server database?

Here is a solution that:

  1. Drops constraints (thanks to this post)
  2. Iterates through INFORMATION_SCHEMA.TABLES for a particular database
  3. SELECTS tables based on some search criteria
  4. Deletes all the data from those tables
  5. Re-adds constraints
  6. Allows for ignoring of certain tables such as sysdiagrams and __RefactorLog

I initially tried EXECUTE sp_MSforeachtable 'TRUNCATE TABLE ?', but that deleted my diagrams.

USE <DB name>;
GO

-- Disable all constraints in the database
EXEC sp_msforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

declare @catalog nvarchar(250);
declare @schema nvarchar(250);
declare @tbl nvarchar(250);
DECLARE i CURSOR LOCAL FAST_FORWARD FOR select
                                        TABLE_CATALOG,
                                        TABLE_SCHEMA,
                                        TABLE_NAME
                                        from INFORMATION_SCHEMA.TABLES
                                        where
                                        TABLE_TYPE = 'BASE TABLE'
                                        AND TABLE_NAME != 'sysdiagrams'
                                        AND TABLE_NAME != '__RefactorLog'

OPEN i;
FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
WHILE @@FETCH_STATUS = 0
    BEGIN
        DECLARE @sql NVARCHAR(MAX) = N'DELETE FROM [' + @catalog + '].[' + @schema + '].[' + @tbl + '];'
        /* Make sure these are the commands you want to execute before executing */
        PRINT 'Executing statement: ' + @sql
        -- EXECUTE sp_executesql @sql
        FETCH NEXT FROM i INTO @catalog, @schema, @tbl;
    END
CLOSE i;
DEALLOCATE i;

-- Re-enable all constraints again
EXEC sp_msforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"