Programs & Examples On #Navigation style

What is for Python what 'explode' is for PHP?

Choose one you need:

>>> s = "Rajasekar SP  def"
>>> s.split(' ')
['Rajasekar', 'SP', '', 'def']
>>> s.split()
['Rajasekar', 'SP', 'def']
>>> s.partition(' ')
('Rajasekar', ' ', 'SP  def')

str.split and str.partition

How to get the absolute path to the public_html folder?

Out of curiosity, why don't you just use the url for the said folder?

http://www.mysite.com/images

Assuming that the folder never changes location, that would be the easiest way to do it.

How to check if a double is null?

I believe Double.NaN might be able to cover this. That is the only 'null' value double contains.

Bash function to find newest file matching pattern

There is a much more efficient way of achieving this. Consider the following command:

find . -cmin 1 -name "b2*"

This command finds the latest file produced exactly one minute ago with the wildcard search on "b2*". If you want files from the last two days then you'll be better off using the command below:

find . -mtime 2 -name "b2*"

The "." represents the current directory. Hope this helps.

The developers of this app have not set up this app properly for Facebook Login?

Now, You need to add a "Privacy Policy URL" in the App Details tab (developers.facebook.com). This is a new Policy of Facebook.

Can't ignore UserInterfaceState.xcuserstate

Just "git clean -f -d" worked for me!

How to draw a filled triangle in android canvas?

Ok I've done it. I'm sharing this code in case someone else will need it:

super.draw(canvas, mapView, true);

Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

paint.setStrokeWidth(2);
paint.setColor(android.graphics.Color.RED);     
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setAntiAlias(true);

Point point1_draw = new Point();        
Point point2_draw = new Point();    
Point point3_draw = new Point();

mapView.getProjection().toPixels(point1, point1_draw);
mapView.getProjection().toPixels(point2, point2_draw);
mapView.getProjection().toPixels(point3, point3_draw);

Path path = new Path();
path.setFillType(Path.FillType.EVEN_ODD);
path.moveTo(point1_draw.x,point1_draw.y);
path.lineTo(point2_draw.x,point2_draw.y);
path.lineTo(point3_draw.x,point3_draw.y);
path.lineTo(point1_draw.x,point1_draw.y);
path.close();

canvas.drawPath(path, paint);

//canvas.drawLine(point1_draw.x,point1_draw.y,point2_draw.x,point2_draw.y, paint);

return true;

Thanks for the hint Nicolas!

How to exit a function in bash

Use return operator:

function FUNCT {
  if [ blah is false ]; then
    return 1 # or return 0, or even you can omit the argument.
  else
    keep running the function
  fi
}

Which @NotNull Java annotation should I use?

For Android projects you should use android.support.annotation.NonNull and android.support.annotation.Nullable. These and other helpful Android-specific annotations are available in the Support Library.

From http://tools.android.com/tech-docs/support-annotations:

The support library itself has also been annotated with these annotations, so as a user of the support library, Android Studio will already check your code and flag potential problems based on these annotations.

Adding a y-axis label to secondary y-axis in matplotlib

For everyone stumbling upon this post because pandas gets mentioned, you now have the very elegant and straighforward option of directly accessing the secondary_y axis in pandas with ax.right_ax

So paraphrasing the example initially posted, you would write:

table = sql.read_frame(query,connection)

ax = table[[0, 1]].plot(ylim=(0,100), secondary_y=table[1])
ax.set_ylabel('$')
ax.right_ax.set_ylabel('Your second Y-Axis Label goes here!')

(this is already mentioned in these posts as well: 1 2)

Spring 3 MVC accessing HttpRequest from controller

I know that is a old question, but...

You can also use this in your class:

@Autowired
private HttpServletRequest context;

And this will provide the current instance of HttpServletRequest for you use on your method.

How can I pass a parameter in Action?

If you know what parameter you want to pass, take a Action<T> for the type. Example:

void LoopMethod (Action<int> code, int count) {
     for (int i = 0; i < count; i++) {
         code(i);
     }
}

If you want the parameter to be passed to your method, make the method generic:

void LoopMethod<T> (Action<T> code, int count, T paramater) {
     for (int i = 0; i < count; i++) {
         code(paramater);
     }
}

And the caller code:

Action<string> s = Console.WriteLine;
LoopMethod(s, 10, "Hello World");

Update. Your code should look like:

private void Include(IList<string> includes, Action<string> action)
{
    if (includes != null)
    {
         foreach (var include in includes)
             action(include);
    }
}

public void test()
{
    Action<string> dg = (s) => {
        _context.Cars.Include(s);
    };
    this.Include(includes, dg);
}

How to read pickle file?

I developed a software tool that opens (most) Pickle files directly in your browser (nothing is transferred so it's 100% private):

https://pickleviewer.com/

How do I upgrade the Python installation in Windows 10?

In 2019, you can install using chocolatey. Open your cmd or powershell, type "choco install python".

How to generate random colors in matplotlib?

Here is a more concise version of Ali's answer giving one distinct color per plot :

import matplotlib.pyplot as plt

N = len(data)
cmap = plt.cm.get_cmap("hsv", N+1)
for i in range(N):
    X,Y = data[i]
    plt.scatter(X, Y, c=cmap(i))

How do I force Postgres to use a particular index?

Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.

As a very blunt hammer, useful for testing, you can use the enable_seqscan and enable_indexscan parameters. See:

These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_ params and walk away.

Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?

  • For small tables, it's faster to do sequential scans.
  • Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
  • Your planner settings might be causing problems.

See also this old newsgroup post.

Count records for every month in a year

SELECT    COUNT(*) 
FROM      table_emp 
WHERE     YEAR(ARR_DATE) = '2012' 
GROUP BY  MONTH(ARR_DATE)

What is the effect of encoding an image in base64?

The answer is: It depends.

Although base64-images are larger, there a few conditions where base64 is the better choice.

Size of base64-images

Base64 uses 64 different characters and this is 2^6. So base64 stores 6bit per 8bit character. So the proportion is 6/8 from unconverted data to base64 data. This is no exact calculation, but a rough estimate.

Example:

An 48kb image needs around 64kb as base64 converted image.

Calculation: (48 / 6) * 8 = 64

Simple CLI calculator on Linux systems:

$ cat /dev/urandom|head -c 48000|base64|wc -c
64843

Or using an image:

$ cat my.png|base64|wc -c

Base64-images and websites

This question is much more difficult to answer. Generally speaking, as larger the image as less sense using base64. But consider the following points:

  • A lot of embedded images in an HTML-File or CSS-File can have similar strings. For PNGs you often find repeated "A" chars. Using gzip (sometimes called "deflate"), there might be even a win on size. But it depends on image content.
  • Request overhead of HTTP1.1: Especially with a lot of cookies you can easily have a few kilobytes overhead per request. Embedding base64 images might save bandwith.
  • Do not base64 encode SVG images, because gzip is more effective on XML than on base64.
  • Programming: On dynamically generated images it is easier to deliver them in one request as to coordinate two dependent requests.
  • Deeplinks: If you want to prevent downloading the image, it is a little bit trickier to extract an image from an HTML page.

How to uninstall with msiexec using product id guid without .msi file present

Thanks all for the help - turns out it was a WiX issue.

When the Product ID GUID was left explicit & hardcoded as in the question, the resulting .msi had no ProductCode property but a Product ID property instead when inspected with orca.

Once I changed the GUID to '*' to auto-generate, the ProductCode showed up and all works fine with syntax confirmed by the other answers.

Find nearest value in numpy array

All the answers are beneficial to gather the information to write efficient code. However, I have written a small Python script to optimize for various cases. It will be the best case if the provided array is sorted. If one searches the index of the nearest point of a specified value, then bisect module is the most time efficient. When one search the indices correspond to an array, the numpy searchsorted is most efficient.

import numpy as np
import bisect
xarr = np.random.rand(int(1e7))

srt_ind = xarr.argsort()
xar = xarr.copy()[srt_ind]
xlist = xar.tolist()
bisect.bisect_left(xlist, 0.3)

In [63]: %time bisect.bisect_left(xlist, 0.3) CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 22.2 µs

np.searchsorted(xar, 0.3, side="left")

In [64]: %time np.searchsorted(xar, 0.3, side="left") CPU times: user 0 ns, sys: 0 ns, total: 0 ns Wall time: 98.9 µs

randpts = np.random.rand(1000)
np.searchsorted(xar, randpts, side="left")

%time np.searchsorted(xar, randpts, side="left") CPU times: user 4 ms, sys: 0 ns, total: 4 ms Wall time: 1.2 ms

If we follow the multiplicative rule, then numpy should take ~100 ms which implies ~83X faster.

Hashing a dictionary?

Here is a clearer solution.

def freeze(o):
  if isinstance(o,dict):
    return frozenset({ k:freeze(v) for k,v in o.items()}.items())

  if isinstance(o,list):
    return tuple([freeze(v) for v in o])

  return o


def make_hash(o):
    """
    makes a hash out of anything that contains only list,dict and hashable types including string and numeric types
    """
    return hash(freeze(o))  

Visual Studio Post Build Event - Copy to Relative Directory Location

Here is what you want to put in the project's Post-build event command line:

copy /Y "$(TargetDir)$(ProjectName).dll" "$(SolutionDir)lib\$(ProjectName).dll"

EDIT: Or if your target name is different than the Project Name.

copy /Y "$(TargetDir)$(TargetName).dll" "$(SolutionDir)lib\$(TargetName).dll"

Run an Ansible task only when the variable contains a specific string

From Ansible 2.5

when: variable1 is search("value")

How to output an Excel *.xls file from classic ASP

It's AddHeader, not AppendHeader.

<%@ Language=VBScript %>
<%  Option Explicit

Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "Content-Disposition", "attachment; filename=excelTest.xls"
%>
<table>
    <tr>
        <td>Test</td>
    </tr>
</table>

Update: I've written a blog post about how to generate Excel files in ASP Classic. It contains a rather useful piece of code to generate both xls and csv files.

How to pass 2D array (matrix) in a function in C?

2D array:

int sum(int array[][COLS], int rows)
{

}

3D array:

int sum(int array[][B][C], int A)
{

}

4D array:

int sum(int array[][B][C][D], int A)
{

}

and nD array:

int sum(int ar[][B][C][D][E][F].....[N], int A)
{

}

Connect Device to Mac localhost Server?

I suggest to use the name of the computer, e.g.http://mymac:1337/. Works for me perfect without any configuration required and I don't have to care about changing IP addresses due DHCP.

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

I found a new error code which is not documented above: CFNetworkErrorCode -1022

Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection."

How to filter input type="file" dialog by specific file type?

Add a custom attribute to <input type="file" file-accept="jpg gif jpeg png bmp"> and read the filenames within javascript that matches the extension provided by the attribute file-accept. This will be kind of bogus, as a text file with any of the above extension will erroneously deteted as image.

Android: Force EditText to remove focus?

Add to your parent layout where did you put your EditText this android:focusableInTouchMode="true"

Pointers in JavaScript?

JavaScript doesn't support passing primitive types by reference. There is a workaround, though.

Put all the variables you need to pass in an object. In this case, there's only one variable, x. Instead of passing the variable, pass the variable name as a string, which is "x".

_x000D_
_x000D_
var variables = {x:0};_x000D_
function a(x)_x000D_
{_x000D_
    variables[x]++;_x000D_
}_x000D_
a("x");_x000D_
alert(variables.x);
_x000D_
_x000D_
_x000D_

matplotlib: Group boxplots

A simple way would be to use pandas. I adapted an example from the plotting documentation:

In [1]: import pandas as pd, numpy as np

In [2]: df = pd.DataFrame(np.random.rand(12,2), columns=['Apples', 'Oranges'] )

In [3]: df['Categories'] = pd.Series(list('AAAABBBBCCCC'))

In [4]: pd.options.display.mpl_style = 'default'

In [5]: df.boxplot(by='Categories')
Out[5]: 
array([<matplotlib.axes.AxesSubplot object at 0x51a5190>,
       <matplotlib.axes.AxesSubplot object at 0x53fddd0>], dtype=object)

pandas boxplot

SimpleDateFormat parsing date with 'Z' literal

Java doesn't parse ISO dates correctly.

Similar to McKenzie's answer.

Just fix the Z before parsing.

Code

String string = "2013-03-05T18:05:05.000Z";
String defaultTimezone = TimeZone.getDefault().getID();
Date date = (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")).parse(string.replaceAll("Z$", "+0000"));

System.out.println("string: " + string);
System.out.println("defaultTimezone: " + defaultTimezone);
System.out.println("date: " + (new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")).format(date));

Result

string: 2013-03-05T18:05:05.000Z
defaultTimezone: America/New_York
date: 2013-03-05T13:05:05.000-0500

MVC [HttpPost/HttpGet] for Action

Let's say you have a Login action which provides the user with a login screen, then receives the user name and password back after the user submits the form:

public ActionResult Login() {
    return View();
}

public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

MVC isn't being given clear instructions on which action is which, even though we can tell by looking at it. If you add [HttpGet] to the first action and [HttpPost] to the section action, MVC clearly knows which action is which.

Why? See Request Methods. Long and short: When a user views a page, that's a GET request and when a user submits a form, that's usually a POST request. HttpGet and HttpPost just restrict the action to the applicable request type.

[HttpGet]
public ActionResult Login() {
    return View();
}

[HttpPost]
public ActionResult Login(string userName, string password) {
    // do login stuff
    return View();
}

You can also combine the request method attributes if your action serves requests from multiple verbs:

[AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)].

How do I generate a stream from a string?

A good combination of String extensions:

public static byte[] GetBytes(this string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

public static Stream ToStream(this string str)
{
    Stream StringStream = new MemoryStream();
    StringStream.Read(str.GetBytes(), 0, str.Length);
    return StringStream;
}

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

I had this in a new project on Windows. npm install had created a node_modules folder for me, but it had somehow created the folder without giving me full control over it. I gave myself full control over node_modules and node_modules\.staging and it worked after that.

Referring to a Column Alias in a WHERE Clause

If you don't want to list all your columns in CTE, another way to do this would be to use outer apply:

select
    s.logcount, s.logUserID, s.maxlogtm,
    a.daysdiff
from statslogsummary as s
    outer apply (select datediff(day, s.maxlogtm, getdate()) as daysdiff) as a
where a.daysdiff > 120

Hyphen, underscore, or camelCase as word delimiter in URIs?

It is recommended to use the spinal-case (which is highlighted by RFC3986), this case is used by Google, PayPal, and other big companies.

source:- https://blog.restcase.com/5-basic-rest-api-design-guidelines/

Copy a file list as text from Windows Explorer

In Windows 7 and later, this will do the trick for you

  • Select the file/files.
  • Hold the shift key and then right-click on the selected file/files.
  • You will see Copy as Path. Click that.
  • Open a Notepad file and paste and you will be good to go.

The menu item Copy as Path is not available in Windows XP.

What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I in no way want to compete with Mark's answer, but just wanted to highlight the piece that finally made everything click as someone new to Javascript inheritance and its prototype chain.

Only property reads search the prototype chain, not writes. So when you set

myObject.prop = '123';

It doesn't look up the chain, but when you set

myObject.myThing.prop = '123';

there's a subtle read going on within that write operation that tries to look up myThing before writing to its prop. So that's why writing to object.properties from the child gets at the parent's objects.

Neither BindingResult nor plain target object for bean name available as request attribute

the first time when you are returning your form make sure you pass the model attribute the form requires which can be done by adding the below code

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(Login login)
    return "test";
}

By default the model attribute name is taken as Bean class's name with first lowercase letter

By doing this the form which expects a backing object naming "login" will be made available to it

after the form is submitted you can do the validation by passing your bean object and bindingresult as the method parameters as shown below

@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(    @ModelAttribute("login") Login login,
                        BindingResult result) 

Logging in Scala

Don't use Logula

I've actually followed the recommendation of Eugene and tried it and found out that it has a clumsy configuration and is subjected to bugs, which don't get fixed (such as this one). It doesn't look to be well maintained and it doesn't support Scala 2.10.

Use slf4s + slf4j-simple

Key benefits:

  • Supports latest Scala 2.10 (to date it's M7)
  • Configuration is versatile but couldn't be simpler. It's done with system properties, which you can set either by appending something like -Dorg.slf4j.simplelogger.defaultlog=trace to execution command or hardcode in your script: System.setProperty("org.slf4j.simplelogger.defaultlog", "trace"). No need to manage trashy config files!
  • Fits nicely with IDEs. For instance to set the logging level to "trace" in a specific run configuration in IDEA just go to Run/Debug Configurations and add -Dorg.slf4j.simplelogger.defaultlog=trace to VM options.
  • Easy setup: just drop in the dependencies from the bottom of this answer

Here's what you need to be running it with Maven:

<dependency>
  <groupId>com.weiglewilczek.slf4s</groupId>
  <artifactId>slf4s_2.9.1</artifactId>
  <version>1.0.7</version>
</dependency>
<dependency>
  <groupId>org.slf4j</groupId>
  <artifactId>slf4j-simple</artifactId>
  <version>1.6.6</version>
</dependency>

Installing Python 3 on RHEL

I was having the same issue using the python 2.7. Follow the below steps to upgrade successfully to 3.6. You can also try this one-

  1. See before upgrading version is 2.x

    python --version
    Python 2.7.5
    
  2. Use below command to upgrade your python to 3.x version-

    yum install python3x

    replace x with the version number you want.

    i.e. for installing python 3.6 execute

    yum install python36
    
  3. After that if you want to set this python for your default version then in bashrc file add

    vi ~/.bashrc

    alias python='python3.6'
    
  4. execute bash command to apply the settings

    bash 
    
  5. Now you can see the version below

    python --version
    Python 3.6.3
    

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I had a similar problem when I deployed my Flask app in the IIS. Apparently, IIS does not accept route that include an underline ("_"). When I removed the underline, problem was resolved.

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

How do I change the ID of a HTML element with JavaScript?

That seems to work for me:

<html>
<head><style>
#monkey {color:blue}
#ape {color:purple}
</style></head>
<body>
<span id="monkey" onclick="changeid()">
fruit
</span>
<script>
function changeid ()
{
var e = document.getElementById("monkey");
e.id = "ape";
}
</script>
</body>
</html>

The expected behaviour is to change the colour of the word "fruit".

Perhaps your document was not fully loaded when you called the routine?

C# - How to get Program Files (x86) on Windows 64 bit

One way would be to look for the "ProgramFiles(x86)" environment variable:

String x86folder = Environment.GetEnvironmentVariable("ProgramFiles(x86)");

How to replace text in a column of a Pandas dataframe?

Use the vectorised str method replace:

In [30]:

df['range'] = df['range'].str.replace(',','-')
df
Out[30]:
      range
0    (2-30)
1  (50-290)

EDIT

So if we look at what you tried and why it didn't work:

df['range'].replace(',','-',inplace=True)

from the docs we see this desc:

str or regex: str: string exactly matching to_replace will be replaced with value

So because the str values do not match, no replacement occurs, compare with the following:

In [43]:

df = pd.DataFrame({'range':['(2,30)',',']})
df['range'].replace(',','-', inplace=True)
df['range']
Out[43]:
0    (2,30)
1         -
Name: range, dtype: object

here we get an exact match on the second row and the replacement occurs.

Can I make a function available in every controller in angular?

I'm a bit newer to Angular but what I found useful to do (and pretty simple) is I made a global script that I load onto my page before the local script with global variables that I need to access on all pages anyway. In that script, I created an object called "globalFunctions" and added the functions that I need to access globally as properties. e.g. globalFunctions.foo = myFunc();. Then, in each local script, I wrote $scope.globalFunctions = globalFunctions; and I instantly have access to any function I added to the globalFunctions object in the global script.

This is a bit of a workaround and I'm not sure it helps you but it definitely helped me as I had many functions and it was a pain adding all of them to each page.

'int' object has no attribute '__getitem__'

I had a similar issue recently while working on recursion and nested lists. I declared:

print(r_sum([1,2,3[1,2,3],]))

instead of

print(r_sum([1,2,3,[1,2,3],]))

Note the comma after the number 3

What is a stack trace, and how can I use it to debug my application errors?

To add on to what Rob has mentioned. Setting break points in your application allows for the step-by-step processing of the stack. This enables the developer to use the debugger to see at what exact point the method is doing something that was unanticipated.

Since Rob has used the NullPointerException (NPE) to illustrate something common, we can help to remove this issue in the following manner:

if we have a method that takes parameters such as: void (String firstName)

In our code we would want to evaluate that firstName contains a value, we would do this like so: if(firstName == null || firstName.equals("")) return;

The above prevents us from using firstName as an unsafe parameter. Therefore by doing null checks before processing we can help to ensure that our code will run properly. To expand on an example that utilizes an object with methods we can look here:

if(dog == null || dog.firstName == null) return;

The above is the proper order to check for nulls, we start with the base object, dog in this case, and then begin walking down the tree of possibilities to make sure everything is valid before processing. If the order were reversed a NPE could potentially be thrown and our program would crash.

How do I close a tkinter window?

You should use destroy() to close a tkinter window.

from Tkinter import *

root = Tk()
Button(root, text="Quit", command=root.destroy).pack()
root.mainloop()

Explanation:

root.quit()

The above line just Bypasses the root.mainloop() i.e root.mainloop() will still be running in background if quit() command is executed.

root.destroy()

While destroy() command vanish out root.mainloop() i.e root.mainloop() stops.

So as you just want to quit the program so you should use root.destroy() as it will it stop the mainloop().

But if you want to run some infinite loop and you don't want to destroy your Tk window and want to execute some code after root.mainloop() line then you should use root.quit(). Ex:

from Tkinter import *
def quit():
    global root
    root.quit()

root = Tk()
while True:
    Button(root, text="Quit", command=quit).pack()
    root.mainloop()
    #do something

Create table (structure) from existing table

Try:

Select * Into <DestinationTableName> From <SourceTableName> Where 1 = 2

Note that this will not copy indexes, keys, etc.

If you want to copy the entire structure, you need to generate a Create Script of the table. You can use that script to create a new table with the same structure. You can then also dump the data into the new table if you need to.

If you are using Enterprise Manager, just right-click the table and select copy to generate a Create Script.

How to trigger a file download when clicking an HTML button or JavaScript

The solution I have come up with is that you can use download attribute in anchor tag but it will only work if your html file is on the server. but you may have a question like while designing a simple html page how can we check that for that you can use VS code live server or bracket live server and you will see your download attribute will work but if you will try to open it simply by just double clicking html page it open the file instead of downloading it. conclusion: attribute download in anchor tag only works if your html file is no server.

How to copy from CSV file to PostgreSQL table with headers in CSV file?

With the Python library pandas, you can easily create column names and infer data types from a csv file.

from sqlalchemy import create_engine
import pandas as pd

engine = create_engine('postgresql://user:pass@localhost/db_name')
df = pd.read_csv('/path/to/csv_file')
df.to_sql('pandas_db', engine)

The if_exists parameter can be set to replace or append to an existing table, e.g. df.to_sql('pandas_db', engine, if_exists='replace'). This works for additional input file types as well, docs here and here.

Interface extends another interface but implements its methods

Why does it implement its methods? How can it implement its methods when an interface can't contain method body? How can it implement the methods when it extends the other interface and not implement it? What is the purpose of an interface implementing another interface?

Interface does not implement the methods of another interface but just extends them. One example where the interface extension is needed is: consider that you have a vehicle interface with two methods moveForward and moveBack but also you need to incorporate the Aircraft which is a vehicle but with some addition methods like moveUp, moveDown so in the end you have:

public interface IVehicle {
  bool moveForward(int x);
  bool moveBack(int x);
};

and airplane:

public interface IAirplane extends IVehicle {
  bool moveDown(int x);
  bool moveUp(int x);
};

Not Able To Debug App In Android Studio

One case where you can be unable to debug an application in Android Studio is when you have the "release" build variant selected. Happened to me - Gradle builds a release version of the app (which is not debuggable) and then Android Studio fails at trying to connect the debugger.

What is the difference between precision and scale?

Scale is the number of digit after the decimal point (or colon depending your locale)

Precision is the total number of significant digits

scale VS precision

Liquibase lock - reasons?

It is not mentioned which environment is used for executing Liquibase. In case it is Spring Boot 2 it is possible to extend liquibase.lockservice.StandardLockService without the need to run direct SQL statements which is much cleaner. E.g.:

/**
 * This class is enforcing to release the lock from the database.
 *
 */
 public class ForceReleaseLockService extends StandardLockService {

    @Override
    public int getPriority() {
        return super.getPriority()+1;
    }

    @Override
    public void waitForLock() throws LockException {
        try {
            super.forceReleaseLock();
        } catch (DatabaseException e) {
            throw new LockException("Could not enforce getting the lock.", e);
        }
        super.waitForLock();
    }
}

The code is enforcing the release of the lock. This can be useful in test set-ups where the release call might not get called in case of errors or when the debugging is aborted.

The class must be placed in the liquibase.ext package and will be picked up by the Spring Boot 2 auto configuration.

Input and Output binary streams using JERSEY?

I have been composing my Jersey 1.17 services the following way:

FileStreamingOutput

public class FileStreamingOutput implements StreamingOutput {

    private File file;

    public FileStreamingOutput(File file) {
        this.file = file;
    }

    @Override
    public void write(OutputStream output)
            throws IOException, WebApplicationException {
        FileInputStream input = new FileInputStream(file);
        try {
            int bytes;
            while ((bytes = input.read()) != -1) {
                output.write(bytes);
            }
        } catch (Exception e) {
            throw new WebApplicationException(e);
        } finally {
            if (output != null) output.close();
            if (input != null) input.close();
        }
    }

}

GET

@GET
@Produces("application/pdf")
public StreamingOutput getPdf(@QueryParam(value="name") String pdfFileName) {
    if (pdfFileName == null)
        throw new WebApplicationException(Response.Status.BAD_REQUEST);
    if (!pdfFileName.endsWith(".pdf")) pdfFileName = pdfFileName + ".pdf";

    File pdf = new File(Settings.basePath, pdfFileName);
    if (!pdf.exists())
        throw new WebApplicationException(Response.Status.NOT_FOUND);

    return new FileStreamingOutput(pdf);
}

And the client, if you need it:

Client

private WebResource resource;

public InputStream getPDFStream(String filename) throws IOException {
    ClientResponse response = resource.path("pdf").queryParam("name", filename)
        .type("application/pdf").get(ClientResponse.class);
    return response.getEntityInputStream();
}

How to check if internet connection is present in Java?

The code you basically provided, plus a call to connect should be sufficient. So yeah, it could be that just Google's not available but some other site you need to contact is on but how likely is that? Also, this code should only execute when you actually fail to access your external resource (in a catch block to try and figure out what the cause of the failure was) so I'd say that if both your external resource of interest and Google are not available chances are you have a net connectivity problem.

private static boolean netIsAvailable() {
    try {
        final URL url = new URL("http://www.google.com");
        final URLConnection conn = url.openConnection();
        conn.connect();
        conn.getInputStream().close();
        return true;
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        return false;
    }
}

Java correct way convert/cast object to Double

Tried all these methods for conversion ->

obj2Double

    public static void main(String[] args) {

    Object myObj = 10.101;
    System.out.println("Cast to Double: "+((Double)myObj)+10.99);   //concates

    Double d1 = new Double(myObj.toString());
    System.out.println("new Object String - Cast to Double: "+(d1+10.99));  //works

    double d3 = (double) myObj;
    System.out.println("new Object - Cast to Double: "+(d3+10.99));     //works

    double d4 = Double.valueOf((Double)myObj);
    System.out.println("Double.valueOf(): "+(d4+10.99));        //works

    double d5 = ((Number) myObj).doubleValue();
    System.out.println("Cast to Number and call doubleValue(): "+(d5+10.99));       //works

    double d2= Double.parseDouble((String) myObj);
    System.out.println("Cast to String to cast to Double: "+(d2+10));       //works
}

MongoDB vs Firebase

Firebase provides some good features like real time change reflection , easy integration of authentication mechanism , and lots of other built-in features for rapid web development. Firebase, really makes Web development so simple that never exists. Firebase database is a fork of MongoDB.

What's the advantage of using Firebase over MongoDB?

You can take advantage of all built-in features of Firebase over MongoDB.

How to create a signed APK file using Cordova command line interface?

##Generated signed apk from commandline
#variables
APP_NAME=THE_APP_NAME
APK_LOCATION=./
APP_HOME=/path/to/THE_APP
APP_KEY=/path/to/Android_key
APP_KEY_ALIAS=the_alias
APP_KEY_PASSWORD=123456789
zipalign=$ANDROID_HOME/build-tools/28.0.3/zipalign

#the logic
cd $APP_HOME
cordova build --release android
cd platforms/android/app/build/outputs/apk/release
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore $APP_KEY ./app-release-unsigned.apk $APP_KEY_ALIAS <<< $APP_KEY_PASSWORD
rm -rf "$APK_LOCATION/$APP_NAME.apk"
$zipalign -v 4 ./app-release-unsigned.apk "$APK_LOCATION/$APP_NAME.apk"
open $APK_LOCATION
#the end

IOError: [Errno 32] Broken pipe: Python

Closes should be done in reverse order of the opens.

"Insert if not exists" statement in SQLite

insert into bookmarks (users_id, lessoninfo_id)

select 1, 167
EXCEPT
select user_id, lessoninfo_id
from bookmarks
where user_id=1
and lessoninfo_id=167;

This is the fastest way.

For some other SQL engines, you can use a Dummy table containing 1 record. e.g:

select 1, 167 from ONE_RECORD_DUMMY_TABLE

AngularJS : Factory and Service?

Factory and Service is a just wrapper of a provider.

Factory

Factory can return anything which can be a class(constructor function), instance of class, string, number or boolean. If you return a constructor function, you can instantiate in your controller.

 myApp.factory('myFactory', function () {

  // any logic here..

  // Return any thing. Here it is object
  return {
    name: 'Joe'
  }
}

Service

Service does not need to return anything. But you have to assign everything in this variable. Because service will create instance by default and use that as a base object.

myApp.service('myService', function () {

  // any logic here..

  this.name = 'Joe';
}

Actual angularjs code behind the service

function service(name, constructor) {
    return factory(name, ['$injector', function($injector) {
        return $injector.instantiate(constructor);
    }]);
}

It just a wrapper around the factory. If you return something from service, then it will behave like Factory.

IMPORTANT: The return result from Factory and Service will be cache and same will be returned for all controllers.

When should i use them?

Factory is mostly preferable in all cases. It can be used when you have constructor function which needs to be instantiated in different controllers.

Service is a kind of Singleton Object. The Object return from Service will be same for all controller. It can be used when you want to have single object for entire application. Eg: Authenticated user details.

For further understanding, read

http://iffycan.blogspot.in/2013/05/angular-service-or-factory.html

http://viralpatel.net/blogs/angularjs-service-factory-tutorial/

How to pass a list from Python, by Jinja2 to JavaScript

I had a similar problem using Flask, but I did not have to resort to JSON. I just passed a list letters = ['a','b','c'] with render_template('show_entries.html', letters=letters), and set

var letters = {{ letters|safe }}

in my javascript code. Jinja2 replaced {{ letters }} with ['a','b','c'], which javascript interpreted as an array of strings.

Select unique values with 'select' function in 'dplyr' library

The dplyr select function selects specific columns from a data frame. To return unique values in a particular column of data, you can use the group_by function. For example:

library(dplyr)

# Fake data
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE))

# Return the distinct values of x
dat %>%
  group_by(x) %>%
  summarise() 

    x
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

If you want to change the column name you can add the following:

dat %>%
  group_by(x) %>%
  summarise() %>%
  select(unique.x=x)

This both selects column x from among all the columns in the data frame that dplyr returns (and of course there's only one column in this case) and changes its name to unique.x.

You can also get the unique values directly in base R with unique(dat$x).

If you have multiple variables and want all unique combinations that appear in the data, you can generalize the above code as follows:

set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE), 
                 y=sample(letters[1:5], 100, replace=TRUE))

dat %>% 
  group_by(x,y) %>%
  summarise() %>%
  select(unique.x=x, unique.y=y)

Create hive table using "as select" or "like" and also specify delimiter

Create Table as select (CTAS) is possible in Hive.

You can try out below command:

CREATE TABLE new_test 
    row format delimited 
    fields terminated by '|' 
    STORED AS RCFile 
AS select * from source where col=1
  1. Target cannot be partitioned table.
  2. Target cannot be external table.
  3. It copies the structure as well as the data

Create table like is also possible in Hive.

  1. It just copies the source table definition.

How can I pass a parameter to a Java Thread?

When you create a thread, you need an instance of Runnable. The easiest way to pass in a parameter would be to pass it in as an argument to the constructor:

public class MyRunnable implements Runnable {

    private volatile String myParam;

    public MyRunnable(String myParam){
        this.myParam = myParam;
        ...
    }

    public void run(){
        // do something with myParam here
        ...
    }

}

MyRunnable myRunnable = new myRunnable("Hello World");
new Thread(myRunnable).start();

If you then want to change the parameter while the thread is running, you can simply add a setter method to your runnable class:

public void setMyParam(String value){
    this.myParam = value;
}

Once you have this, you can change the value of the parameter by calling like this:

myRunnable.setMyParam("Goodbye World");

Of course, if you want to trigger an action when the parameter is changed, you will have to use locks, which makes things considerably more complex.

Android ViewPager with bottom dots

My handmade solution:

In the layout:

<LinearLayout
        android:orientation="horizontal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dots"
        />

And in the Activity

private final static int NUM_PAGES = 5;
private ViewPager mViewPager;
private List<ImageView> dots;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // ...
    addDots();
}

public void addDots() {
    dots = new ArrayList<>();
    LinearLayout dotsLayout = (LinearLayout)findViewById(R.id.dots);

    for(int i = 0; i < NUM_PAGES; i++) {
        ImageView dot = new ImageView(this);
        dot.setImageDrawable(getResources().getDrawable(R.drawable.pager_dot_not_selected));

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        );
        dotsLayout.addView(dot, params);

        dots.add(dot);
    }

    mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            selectDot(position);
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });
}

public void selectDot(int idx) {
    Resources res = getResources();
    for(int i = 0; i < NUM_PAGES; i++) {
        int drawableId = (i==idx)?(R.drawable.pager_dot_selected):(R.drawable.pager_dot_not_selected);
        Drawable drawable = res.getDrawable(drawableId);
        dots.get(i).setImageDrawable(drawable);
    }
}

How to put a delay on AngularJS instant search?

Angular 1.3 will have ng-model-options debounce, but until then, you have to use a timer like Josue Ibarra said. However, in his code he launches a timer on every key press. Also, he is using setTimeout, when in Angular one has to use $timeout or use $apply at the end of setTimeout.

I can't find my git.exe file in my Github folder

The path for the latest version of Git is changed, In my laptop, I found it in

C:\Users\Anum Sheraz\AppData\Local\Programs\Git\bin\git.exe

This resolved my issue of path. Hope that helps to someone :)

Error - Unable to access the IIS metabase

On Windows 8 Pro:

%systemroot%\inetsrv\config

On Windows 7 and 8.1 and 10

%systemroot%\System32\inetsrv\config 

(Where %systemroot% is usually C:\Windows)

Navigate to the appropriate location above in Windows Explorer. You will be blocked access with a popup which says:

"You don't have access to this folder - Click continue to permanently get access to this folder"

Click 'continue' for this folder, and with the Export folder underneath. I changed the shortcut back to "Run as me" (a member of the domain and local administrators ) and was able to open and deploy the solution.

Vector of Vectors to create matrix

As it is, both dimensions of your vector are 0.

Instead, initialize the vector as this:

vector<vector<int> > matrix(RR);
for ( int i = 0 ; i < RR ; i++ )
   matrix[i].resize(CC);

This will give you a matrix of dimensions RR * CC with all elements set to 0.

Performing user authentication in Java EE / JSF using j_security_check

After searching the Web and trying many different ways, here's what I'd suggest for Java EE 6 authentication:

Set up the security realm:

In my case, I had the users in the database. So I followed this blog post to create a JDBC Realm that could authenticate users based on username and MD5-hashed passwords in my database table:

http://blog.gamatam.com/2009/11/jdbc-realm-setup-with-glassfish-v3.html

Note: the post talks about a user and a group table in the database. I had a User class with a UserType enum attribute mapped via javax.persistence annotations to the database. I configured the realm with the same table for users and groups, using the userType column as the group column and it worked fine.

Use form authentication:

Still following the above blog post, configure your web.xml and sun-web.xml, but instead of using BASIC authentication, use FORM (actually, it doesn't matter which one you use, but I ended up using FORM). Use the standard HTML , not the JSF .

Then use BalusC's tip above on lazy initializing the user information from the database. He suggested doing it in a managed bean getting the principal from the faces context. I used, instead, a stateful session bean to store session information for each user, so I injected the session context:

 @Resource
 private SessionContext sessionContext;

With the principal, I can check the username and, using the EJB Entity Manager, get the User information from the database and store in my SessionInformation EJB.

Logout:

I also looked around for the best way to logout. The best one that I've found is using a Servlet:

 @WebServlet(name = "LogoutServlet", urlPatterns = {"/logout"})
 public class LogoutServlet extends HttpServlet {
  @Override
  protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   HttpSession session = request.getSession(false);

   // Destroys the session for this user.
   if (session != null)
        session.invalidate();

   // Redirects back to the initial page.
   response.sendRedirect(request.getContextPath());
  }
 }

Although my answer is really late considering the date of the question, I hope this helps other people that end up here from Google, just like I did.

Ciao,

Vítor Souza

What's the difference between deadlock and livelock?

I just planned to share some knowledge.

Deadlocks A set of threads/processes is deadlocked, if each thread/process in the set is waiting for an event that only another process in the set can cause.

The important thing here is another process is also in the same set. that means another process also blocked and no one can proceed.

Deadlocks occur when processes are granted exclusive access to resources.

These four conditions should be satisfied to have a deadlock.

  1. Mutual exclusion condition (Each resource is assigned to 1 process)
  2. Hold and wait condition (Process holding resources and at the same time it can ask other resources).
  3. No preemption condition (Previously granted resources can not forcibly be taken away) #This condition depends on the application
  4. Circular wait condition (Must be a circular chain of 2 or more processes and each is waiting for resource held by the next member of the chain) # It will happen dynamically

If we found these conditions then we can say there may be occurred a situation like a deadlock.

LiveLock

Each thread/process is repeating the same state again and again but doesn't progress further. Something similar to a deadlock since the process can not enter the critical section. However in a deadlock, processes are wait without doing anything but in livelock, the processes are trying to proceed but processes are repeated to the same state again and again.

(In a deadlocked computation there is no possible execution sequence which succeeds. but In a livelocked computation, there are successful computations, but there are one or more execution sequences in which no process enters its critical section.)

Difference from deadlock and livelock

When deadlock happens, No execution will happen. but in livelock, some executions will happen but those executions are not enough to enter the critical section.

How to check if a string is a number?

I need to do the same thing for a project I am currently working on. Here is how I solved things:

/* Prompt user for input */
printf("Enter a number: ");

/* Read user input */
char input[255]; //Of course, you can choose a different input size
fgets(input, sizeof(input), stdin);

/* Strip trailing newline */
size_t ln = strlen(input) - 1;
if( input[ln] == '\n' ) input[ln] = '\0';

/* Ensure that input is a number */
for( size_t i = 0; i < ln; i++){
    if( !isdigit(input[i]) ){
        fprintf(stderr, "%c is not a number. Try again.\n", input[i]);
        getInput(); //Assuming this is the name of the function you are using
        return;
    }
}

Testing pointers for validity (C/C++)

It is not a very good policy to accept arbitrary pointers as input parameters in a public API. It's better to have "plain data" types like an integer, a string or a struct (I mean a classical struct with plain data inside, of course; officially anything can be a struct).

Why? Well because as others say there is no standard way to know whether you've been given a valid pointer or one that points to junk.

But sometimes you don't have the choice - your API must accept a pointer.

In these cases, it is the duty of the caller to pass a good pointer. NULL may be accepted as a value, but not a pointer to junk.

Can you double-check in any way? Well, what I did in a case like that was to define an invariant for the type the pointer points to, and call it when you get it (in debug mode). At least if the invariant fails (or crashes) you know that you were passed a bad value.

// API that does not allow NULL
void PublicApiFunction1(Person* in_person)
{
  assert(in_person != NULL);
  assert(in_person->Invariant());

  // Actual code...
}

// API that allows NULL
void PublicApiFunction2(Person* in_person)
{
  assert(in_person == NULL || in_person->Invariant());

  // Actual code (must keep in mind that in_person may be NULL)
}

Rebuild all indexes in a Database

Daniel's script appears to be a good all encompassing solution, but even he admitted that his laptop ran out of memory. Here is an option I came up with. I based my procedure off of Mohammad Nizamuddin's post on TechNet. I added an initial cursor loop that pulls all the database names into a temporary table and then uses that to pull all the base table names from each of those databases.

You can optionally pass the fill factor you would prefer and specify a target database if you do not want to re-index all databases.


--===============================================================
-- Name:  sp_RebuildAllIndexes
-- Arguements:  [Fill Factor], [Target Database name]
-- Purpose:  Loop through all the databases on a server and
--           compile a list of all the table within them.
--           This list is then used to rebuild indexes for
--           all the tables in all the database.  Optionally,
--           you may pass a specific database name if you only
--           want to reindex that target database.
--================================================================
CREATE PROCEDURE sp_RebuildAllIndexes(
    @FillFactor     INT = 90,
    @TargetDatabase NVARCHAR(100) = NULL)
AS
    BEGIN
        DECLARE @TablesToReIndex TABLE (
            TableName VARCHAR(200)
        );
        DECLARE @DbName VARCHAR(50);
        DECLARE @TableSelect VARCHAR(MAX);
        DECLARE @DatabasesToIndex CURSOR;

        IF ISNULL( @TargetDatabase, '' ) = ''
          SET @DatabasesToIndex = CURSOR
          FOR SELECT NAME
              FROM   master..sysdatabases
        ELSE
          SET @DatabasesToIndex = CURSOR
          FOR SELECT NAME
              FROM   master..sysdatabases
              WHERE  NAME = @TargetDatabase

        OPEN DatabasesToIndex

        FETCH NEXT FROM DatabasesToIndex INTO @DbName

        WHILE @@FETCH_STATUS = 0
            BEGIN
                SET @TableSelect = 'INSERT INTO @TablesToReIndex SELECT CONCAT(TABLE_CATALOG, ''.'', TABLE_SCHEMA, ''.'', TABLE_NAME) AS TableName FROM '
                                   + @DbName
                                   + '.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''base table''';

                EXEC sp_executesql
                    @TableSelect;

                FETCH NEXT FROM DatabasesToIndex INTO @DbName
            END

        CLOSE DatabasesToIndex

        DEALLOCATE DatabasesToIndex

        DECLARE @TableName VARCHAR(255)
        DECLARE TableCursor CURSOR FOR
            SELECT TableName
            FROM   @TablesToReIndex

        OPEN TableCursor

        FETCH NEXT FROM TableCursor INTO @TableName

        WHILE @@FETCH_STATUS = 0
            BEGIN
                DBCC DBREINDEX(@TableName, ' ', @FillFactor)

                FETCH NEXT FROM TableCursor INTO @TableName
            END

        CLOSE TableCursor

        DEALLOCATE TableCursor
    END 

How to redirect on another page and pass parameter in url from table?

Do this :

<script type="text/javascript">
function showDetails(username)
{
   window.location = '/player_detail?username='+username;
}
</script>

<input type="button" name="theButton" value="Detail" onclick="showDetails('username');">

PHP how to get value from array if key is in a variable

As others stated, it's likely failing because the requested key doesn't exist in the array. I have a helper function here that takes the array, the suspected key, as well as a default return in the event the key does not exist.

    protected function _getArrayValue($array, $key, $default = null)
    {
        if (isset($array[$key])) return $array[$key];
        return $default;
    }

hope it helps.

PDF Blob - Pop up window not showing content

I have been struggling for days finally the solution which worked for me is given below. I had to make the window.print() for PDF in new window needs to work.

 var xhr = new XMLHttpRequest();
      xhr.open('GET', pdfUrl, true);
      xhr.responseType = 'blob';

      xhr.onload = function(e) {
        if (this['status'] == 200) {          
          var blob = new Blob([this['response']], {type: 'application/pdf'});
          var url = URL.createObjectURL(blob);
          var printWindow = window.open(url, '', 'width=800,height=500');
          printWindow.print()
        }
      };

      xhr.send();

Some notes on loading PDF & printing in a new window.

  • Loading pdf in a new window via an iframe will work, but the print will not work if url is an external url.
  • Browser pop ups must be allowed, then only it will work.
  • If you try to load iframe from external url and try window.print() you will get empty print or elements which excludes iframe. But you can trigger print manually, which will work.

JList add/remove Item

The problem is

listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());

you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.

Try

private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       

    DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
    DefaultListModel lm1  = (DefaultListModel) listaRosa.getModel();
    if(lm2 == null)
    {
        lm2 = new DefaultListModel();
        listaTitolari.setModel(lm2);
    }
    lm2.addElement(listaTitolari.getSelectedValue());
    lm1.removeElement(listaTitolari.getSelectedValue());        
} 

Easiest way to pass an AngularJS scope variable from directive to controller?

Edited on 2014/8/25: Here was where I forked it.

Thanks @anvarik.

Here is the JSFiddle. I forgot where I forked this. But this is a good example showing you the difference between = and @

<div ng-controller="MyCtrl">
    <h2>Parent Scope</h2>
    <input ng-model="foo"> <i>// Update to see how parent scope interacts with component scope</i>    
    <br><br>
    <!-- attribute-foo binds to a DOM attribute which is always
    a string. That is why we are wrapping it in curly braces so
    that it can be interpolated. -->
    <my-component attribute-foo="{{foo}}" binding-foo="foo"
        isolated-expression-foo="updateFoo(newFoo)" >
        <h2>Attribute</h2>
        <div>
            <strong>get:</strong> {{isolatedAttributeFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedAttributeFoo">
            <i>// This does not update the parent scope.</i>
        </div>
        <h2>Binding</h2>
        <div>
            <strong>get:</strong> {{isolatedBindingFoo}}
        </div>
        <div>
            <strong>set:</strong> <input ng-model="isolatedBindingFoo">
            <i>// This does update the parent scope.</i>
        </div>
        <h2>Expression</h2>    
        <div>
            <input ng-model="isolatedFoo">
            <button class="btn" ng-click="isolatedExpressionFoo({newFoo:isolatedFoo})">Submit</button>
            <i>// And this calls a function on the parent scope.</i>
        </div>
    </my-component>
</div>
var myModule = angular.module('myModule', [])
    .directive('myComponent', function () {
        return {
            restrict:'E',
            scope:{
                /* NOTE: Normally I would set my attributes and bindings
                to be the same name but I wanted to delineate between
                parent and isolated scope. */                
                isolatedAttributeFoo:'@attributeFoo',
                isolatedBindingFoo:'=bindingFoo',
                isolatedExpressionFoo:'&'
            }        
        };
    })
    .controller('MyCtrl', ['$scope', function ($scope) {
        $scope.foo = 'Hello!';
        $scope.updateFoo = function (newFoo) {
            $scope.foo = newFoo;
        }
    }]);

ImportError: No module named - Python

Make sure if root project directory is coming up in sys.path output. If not, please add path of root project directory to sys.path.

Rails 3 check if attribute changed

For rails 5.1+ callbacks

As of Ruby on Rails 5.1, the attribute_changed? and attribute_was ActiveRecord methods will be deprecated

Use saved_change_to_attribute? instead of attribute_changed?

@user.saved_change_to_street1? # => true/false

More examples here

Is there a minlength validation attribute in HTML5?

I wrote this JavaScript code, [minlength.js]:

window.onload = function() {
    function testaFunction(evt) {
        var elementos = this.elements;
        for (var j = 0; j < elementos.length; j++) {
            if (elementos[j].tagName == "TEXTAREA" && elementos[j].hasAttribute("minlength")) {
                if (elementos[j].value.length < elementos[j].getAttribute("minlength")) {
                    alert("The textarea control must be at least " + elementos[j].getAttribute("minlength") + " characters.");
                    evt.preventDefault();
                };
            }
        }
    }
    var forms = document.getElementsByTagName("form");
    for(var i = 0; i < forms.length; i++) {
        forms[i].addEventListener('submit', testaFunction, true);
    }
}

How to create a density plot in matplotlib?

Five years later, when I Google "how to create a kernel density plot using python", this thread still shows up at the top!

Today, a much easier way to do this is to use seaborn, a package that provides many convenient plotting functions and good style management.

import numpy as np
import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.set_style('whitegrid')
sns.kdeplot(np.array(data), bw=0.5)

enter image description here

How to get a list of all valid IP addresses in a local network?

Install nmap,

sudo apt-get install nmap

then

nmap -sP 192.168.1.*

or more commonly

nmap -sn 192.168.1.0/24

will scan the entire .1 to .254 range

This does a simple ping scan in the entire subnet to see which hosts are online.

How to force two figures to stay on the same page in LaTeX?

You can put two figures inside one figure environment. For example:

\begin{figure}[p]
\centering
\includegraphics{fig1}
\caption{Caption 1}
\includegraphics{fig2}
\caption{Caption 2}
\end{figure}

Each caption will generate a separate figure number.

How to import multiple .csv files at once?

Here are some options to convert the .csv files into one data.frame using R base and some of the available packages for reading files in R.

This is slower than the options below.

# Get the files names
files = list.files(pattern="*.csv")
# First apply read.csv, then rbind
myfiles = do.call(rbind, lapply(files, function(x) read.csv(x, stringsAsFactors = FALSE)))

Edit: - A few more extra choices using data.table and readr

A fread() version, which is a function of the data.table package. This is by far the fastest option in R.

library(data.table)
DT = do.call(rbind, lapply(files, fread))
# The same using `rbindlist`
DT = rbindlist(lapply(files, fread))

Using readr, which is another package for reading csv files. It's slower than fread, faster than base R but has different functionalities.

library(readr)
library(dplyr)
tbl = lapply(files, read_csv) %>% bind_rows()

In where shall I use isset() and !empty()

isset() tests if a variable is set and not null:

http://us.php.net/manual/en/function.isset.php

empty() can return true when the variable is set to certain values:

http://us.php.net/manual/en/function.empty.php

<?php

$the_var = 0;

if (isset($the_var)) {
  echo "set";
} else {
  echo "not set";
}

echo "\n";

if (empty($the_var)) {
  echo "empty";
} else {
  echo "not empty";
}
?>

Is it possible to make input fields read-only through CSS?

You don't set the behavior of controls via CSS, only their styling.You can use jquery or simple javascript to change the property of the fields.

Setting Inheritance and Propagation flags with set-acl and powershell

Here's some succinct Powershell code to apply new permissions to a folder by modifying it's existing ACL (Access Control List).

# Get the ACL for an existing folder
$existingAcl = Get-Acl -Path 'C:\DemoFolder'

# Set the permissions that you want to apply to the folder
$permissions = $env:username, 'Read,Modify', 'ContainerInherit,ObjectInherit', 'None', 'Allow'

# Create a new FileSystemAccessRule object
$rule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $permissions

# Modify the existing ACL to include the new rule
$existingAcl.SetAccessRule($rule)

# Apply the modified access rule to the folder
$existingAcl | Set-Acl -Path 'C:\DemoFolder'

Each of the values in the $permissions variable list pertain to the parameters of this constructor for the FileSystemAccessRule class.

Courtesy of this page.

Working with select using AngularJS's ng-options

I'm learning AngularJS and was struggling with selection as well. I know this question is already answered, but I wanted to share some more code nevertheless.

In my test I have two listboxes: car makes and car models. The models list is disabled until some make is selected. If selection in makes listbox is later reset (set to 'Select Make') then the models listbox becomes disabled again AND its selection is reset as well (to 'Select Model'). Makes are retrieved as a resource while models are just hard-coded.

Makes JSON:

[
{"code": "0", "name": "Select Make"},
{"code": "1", "name": "Acura"},
{"code": "2", "name": "Audi"}
]

services.js:

angular.module('makeServices', ['ngResource']).
factory('Make', function($resource){
    return $resource('makes.json', {}, {
        query: {method:'GET', isArray:true}
    });
});

HTML file:

<div ng:controller="MakeModelCtrl">
  <div>Make</div>
  <select id="makeListBox"
      ng-model="make.selected"
      ng-options="make.code as make.name for make in makes"
      ng-change="makeChanged(make.selected)">
  </select>

  <div>Model</div>
  <select id="modelListBox"
     ng-disabled="makeNotSelected"
     ng-model="model.selected"
     ng-options="model.code as model.name for model in models">
  </select>
</div>

controllers.js:

function MakeModelCtrl($scope)
{
    $scope.makeNotSelected = true;
    $scope.make = {selected: "0"};
    $scope.makes = Make.query({}, function (makes) {
         $scope.make = {selected: makes[0].code};
    });

    $scope.makeChanged = function(selectedMakeCode) {
        $scope.makeNotSelected = !selectedMakeCode;
        if ($scope.makeNotSelected)
        {
            $scope.model = {selected: "0"};
        }
    };

    $scope.models = [
      {code:"0", name:"Select Model"},
      {code:"1", name:"Model1"},
      {code:"2", name:"Model2"}
    ];
    $scope.model = {selected: "0"};
}

How to check if ZooKeeper is running or up from command prompt?

echo stat | nc localhost 2181 | grep Mode
echo srvr | nc localhost 2181 | grep Mode #(From 3.3.0 onwards)

Above will work in whichever modes Zookeeper is running (standalone or embedded).

Another way

If zookeeper is running in standalone mode, its a JVM process. so -

jps | grep Quorum

will display list of jvm processes; something like this for zookeeper with process ID

HQuorumPeer

How do I copy SQL Azure database to my local development server?

You can use the new Azure Mobile Services to do a nightly backup export from SQL Azure to a .bacpac file hosted in Azure Storage. This solution is 100% cloud, doesn't require a 3rd party tool and doesn't require a local hosted SQL Server instance to download/copy/backup anything.

There's about 8 different steps, but they're all easy: http://geekswithblogs.net/BenBarreth/archive/2013/04/15/how-to-create-a-nightly-backup-of-your-sql-azure.aspx

How to disable keypad popup when on edittext?

Try this answer,

editText.setRawInputType(InputType.TYPE_CLASS_TEXT);
editText.setTextIsSelectable(true);

Note: only for API 11+

How to change UIPickerView height

Embed in a stack view. Stack view is a component recently added by Apple in their iOS SDK to reflect grid based implementations in java script web based front end libraries such as bootstrap.

How to downgrade or install an older version of Cocoapods

PROMPT> gem uninstall cocoapods

Select gem to uninstall:
 1. cocoapods-0.32.1
 2. cocoapods-0.33.1
 3. cocoapods-0.36.0.beta.2
 4. cocoapods-0.38.2
 5. cocoapods-0.39.0
 6. cocoapods-1.0.0
 7. All versions
> 6
Successfully uninstalled cocoapods-1.0.0
PROMPT> gem install cocoapods -v 0.39.0
Successfully installed cocoapods-0.39.0
Parsing documentation for cocoapods-0.39.0
Done installing documentation for cocoapods after 1 seconds
1 gem installed
PROMPT> pod --version
0.39.0
PROMPT>

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

None of the aforementioned solutions worked for me. What I had to do was use a nullable int (int?) on the foreign key that was not required (or not a not null column key) and then delete some of my migrations.

Start by deleting the migrations, then try the nullable int.

Problem was both a modification and model design. No code change was necessary.

Why is document.write considered a "bad practice"?

Pro:

  • It's the easiest way to embed inline content from an external (to your host/domain) script.
  • You can overwrite the entire content in a frame/iframe. I used to use this technique a lot for menu/navigation pieces before more modern Ajax techniques were widely available (1998-2002).

Con:

  • It serializes the rendering engine to pause until said external script is loaded, which could take much longer than an internal script.
  • It is usually used in such a way that the script is placed within the content, which is considered bad-form.

What causes: "Notice: Uninitialized string offset" to appear?

This error would occur if any of the following variables were actually strings or null instead of arrays, in which case accessing them with an array syntax $var[$i] would be like trying to access a specific character in a string:

$catagory
$task
$fullText
$dueDate
$empId

In short, everything in your insert query.

Perhaps the $catagory variable is misspelled?

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

To demonstrate how this works--

CREATE TABLE T1 (ID INT NOT NULL, SomeVal CHAR(1));
ALTER TABLE T1 ADD CONSTRAINT [PK_ID] PRIMARY KEY CLUSTERED (ID);

CREATE TABLE T2 (FKID INT, SomeOtherVal CHAR(2));

INSERT T1 (ID, SomeVal) SELECT 1, 'A';
INSERT T1 (ID, SomeVal) SELECT 2, 'B';

INSERT T2 (FKID, SomeOtherVal) SELECT 1, 'A1';
INSERT T2 (FKID, SomeOtherVal) SELECT 1, 'A2';
INSERT T2 (FKID, SomeOtherVal) SELECT 2, 'B1';
INSERT T2 (FKID, SomeOtherVal) SELECT 2, 'B2';
INSERT T2 (FKID, SomeOtherVal) SELECT 3, 'C1';  --orphan
INSERT T2 (FKID, SomeOtherVal) SELECT 3, 'C2';  --orphan

--Add the FK CONSTRAINT will fail because of existing orphaned records
ALTER TABLE T2 ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID);   --fails

--Same as ADD above, but explicitly states the intent to CHECK the FK values before creating the CONSTRAINT
ALTER TABLE T2 WITH CHECK ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID);    --fails

--Add the CONSTRAINT without checking existing values
ALTER TABLE T2 WITH NOCHECK ADD CONSTRAINT FK_T2_T1 FOREIGN KEY (FKID) REFERENCES T1 (ID);  --succeeds
ALTER TABLE T2 CHECK CONSTRAINT FK_T2_T1;   --succeeds since the CONSTRAINT is attributed as NOCHECK

--Attempt to enable CONSTRAINT fails due to orphans
ALTER TABLE T2 WITH CHECK CHECK CONSTRAINT FK_T2_T1;    --fails

--Remove orphans
DELETE FROM T2 WHERE FKID NOT IN (SELECT ID FROM T1);

--Enabling the CONSTRAINT succeeds
ALTER TABLE T2 WITH CHECK CHECK CONSTRAINT FK_T2_T1;    --succeeds; orphans removed

--Clean up
DROP TABLE T2;
DROP TABLE T1;

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

Could not find or load main class

Sometimes what might be causing the issue has nothing to do with the main class. I had to find this out the hard way, it was a referenced library that I moved and it gave me the:

Could not find or load main class xxx Linux

I just delete that reference and added again and it worked fine again.

Macro to Auto Fill Down to last adjacent cell

ActiveCell.Offset(0, -1).Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
Selection.FillDown

Fragment Inside Fragment

Since Android 4.2 (API 17) nested fragments become available http://developer.android.com/about/versions/android-4.2.html#NestedFragments

To place fragment inside other fragment use getChildFragmentManager()

It also available in support library!

Dynamically load a function from a DLL

LoadLibrary does not do what you think it does. It loads the DLL into the memory of the current process, but it does not magically import functions defined in it! This wouldn't be possible, as function calls are resolved by the linker at compile time while LoadLibrary is called at runtime (remember that C++ is a statically typed language).

You need a separate WinAPI function to get the address of dynamically loaded functions: GetProcAddress.

Example

#include <windows.h>
#include <iostream>

/* Define a function pointer for our imported
 * function.
 * This reads as "introduce the new type f_funci as the type: 
 *                pointer to a function returning an int and 
 *                taking no arguments.
 *
 * Make sure to use matching calling convention (__cdecl, __stdcall, ...)
 * with the exported function. __stdcall is the convention used by the WinAPI
 */
typedef int (__stdcall *f_funci)();

int main()
{
  HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop\\test.dll");

  if (!hGetProcIDDLL) {
    std::cout << "could not load the dynamic library" << std::endl;
    return EXIT_FAILURE;
  }

  // resolve function address here
  f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
  if (!funci) {
    std::cout << "could not locate the function" << std::endl;
    return EXIT_FAILURE;
  }

  std::cout << "funci() returned " << funci() << std::endl;

  return EXIT_SUCCESS;
}

Also, you should export your function from the DLL correctly. This can be done like this:

int __declspec(dllexport) __stdcall funci() {
   // ...
}

As Lundin notes, it's good practice to free the handle to the library if you don't need them it longer. This will cause it to get unloaded if no other process still holds a handle to the same DLL.

How to retrieve inserted id after inserting row in SQLite using Python?

You could use cursor.lastrowid (see "Optional DB API Extensions"):

connection=sqlite3.connect(':memory:')
cursor=connection.cursor()
cursor.execute('''CREATE TABLE foo (id integer primary key autoincrement ,
                                    username varchar(50),
                                    password varchar(50))''')
cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('test','test'))
print(cursor.lastrowid)
# 1

If two people are inserting at the same time, as long as they are using different cursors, cursor.lastrowid will return the id for the last row that cursor inserted:

cursor.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

cursor2=connection.cursor()
cursor2.execute('INSERT INTO foo (username,password) VALUES (?,?)',
               ('blah','blah'))

print(cursor2.lastrowid)        
# 3
print(cursor.lastrowid)
# 2

cursor.execute('INSERT INTO foo (id,username,password) VALUES (?,?,?)',
               (100,'blah','blah'))
print(cursor.lastrowid)
# 100

Note that lastrowid returns None when you insert more than one row at a time with executemany:

cursor.executemany('INSERT INTO foo (username,password) VALUES (?,?)',
               (('baz','bar'),('bing','bop')))
print(cursor.lastrowid)
# None

How can I force browsers to print background images in CSS?

You can do some tricks like that:

<style>
    @page {
        size: 21cm 29.7cm;
        size: landscape
        /*margin: 30mm 45mm 30mm 45mm;*/

    }
    .whater{
        opacity: 0.05;
        height: 100%;
        width: 100%;
        position: absolute;
        z-index: 9999;
    }
</style>

In body tag:

<img src="YOUR IMAGE URL" class="whater"/>

How to start Spyder IDE on Windows

If you are using Anaconda execute the following commands and your life will be saved!

conda update qt pyqt
conda update spyder

Print all day-dates between two dates

import datetime

begin = datetime.date(2008, 8, 15)
end = datetime.date(2008, 9, 15)

next_day = begin
while True:
    if next_day > end:
        break
    print next_day
    next_day += datetime.timedelta(days=1)

Microsoft Visual C++ Compiler for Python 3.4

Visual Studio Community 2015 suffices to build extensions for Python 3.5. It's free but a 6 GB download (overkill). On my computer it installed vcvarsall at C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat

For Python 3.4 you'd need Visual Studio 2010. I don't think there's any free edition. See https://matthew-brett.github.io/pydagogue/python_msvc.html

How to access array elements in a Django template?

You can access sequence elements with arr.0 arr.1 and so on. See The Django template system chapter of the django book for more information.

What is the difference between SessionState and ViewState?

Session is used mainly for storing user specific data [ session specific data ]. In the case of session you can use the value for the whole session until the session expires or the user abandons the session. Viewstate is the type of data that has scope only in the page in which it is used. You canot have viewstate values accesible to other pages unless you transfer those values to the desired page. Also in the case of viewstate all the server side control datas are transferred to the server as key value pair in __Viewstate and transferred back and rendered to the appropriate control in client when postback occurs.

Python 2.7: %d, %s, and float()

Try the following:

print "First is: %f" % (first)
print "Second is: %f" % (second)

I am unsure what answer is. But apart from that, this will be:

print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)

There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:

If you try this:

print "First is: %s" % (first)

It converts the float value in first to a string. So that would work as well.

Git will not init/sync/update new submodules

I had a similar problem with a submodule. It just didn't want to be cloned/pulled/updated/whatever.

When trying to re-add the submodule using git submodule add [email protected] destination I got the following output:

A git directory for 'destination' is found locally with remote(s):
  origin        [email protected]
If you want to reuse this local git directory instead of cloning again from
  [email protected]
use the '--force' option. If the local git directory is not the correct repo
or you are unsure what this means choose another name with the '--name' option.

So, I tried to enforce the add command:
git submodule add --force [email protected] destination

That worked in my case.

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

If you could somehow locate mongod.log and the do a grep over it

grep dbpath mongod.log

The value for dbpath is the data location for mongodb!! All the best :)

How to edit default.aspx on SharePoint site without SharePoint Designer

I was able to accomplish editing the default.aspx page by:

  • Opening the site in SharePoint Designer 2013
  • Then clicking 'All Files' to view all of the files,
  • Then right-click -> Edit file in Advanced Mode.

By doing that I was able to remove the tagprefix causing a problem on my page.

How to create exe of a console application

For .NET Core 2.2 you can publish the application and set the target to be a self-contained executable.

In Visual Studio right click your console application project. Select publish to folder and set the profile settings like so:

Visual Studio Publish Menu

You'll find your compiled code with the .exe in the publish folder.

MySQL Creating tables with Foreign Keys giving errno: 150

This is usually happening when you try to source file into existing database. Drop all the tables first (or the DB itself). And then source file with SET foreign_key_checks = 0; at the beginning and SET foreign_key_checks = 1; at the end.

Error ITMS-90717: "Invalid App Store Icon"

If showing this error for ionic3 project when you upload to iTunes Connect, please check this ANSWER

This is my project error when I try to vilidated. enter image description here

Finally follow this ANSWER, error solved. enter image description here

OSX - How to auto Close Terminal window after the "exit" command executed.

Actually, you should set a config on your Terminal, when your Terminal is up press ?+, then you will see below screen:

enter image description here

Then press shell tab and you will see below screen:

enter image description here

Now select Close if the shell exited cleanly for When the shell exits.

By the above config each time with exit command the Terminal will close but won't quit.

How do you round a float to 2 decimal places in JRuby?

to truncate a decimal I've used the follow code:

<th><%#= sprintf("%0.01f",prom/total) %><!--1dec,aprox-->
    <% if prom == 0 or total == 0 %>
        N.E.
    <% else %>
        <%= Integer((prom/total).to_d*10)*0.1 %><!--1decimal,truncado-->
    <% end %>
        <%#= prom/total %>
</th>

If you want to truncate to 2 decimals, you should use Integr(a*100)*0.01

How do you do Impersonation in .NET?

Here's my vb.net port of Matt Johnson's answer. I added an enum for the logon types. LOGON32_LOGON_INTERACTIVE was the first enum value that worked for sql server. My connection string was just trusted. No user name / password in the connection string.

  <PermissionSet(SecurityAction.Demand, Name:="FullTrust")> _
  Public Class Impersonation
    Implements IDisposable

    Public Enum LogonTypes
      ''' <summary>
      ''' This logon type is intended for users who will be interactively using the computer, such as a user being logged on  
      ''' by a terminal server, remote shell, or similar process.
      ''' This logon type has the additional expense of caching logon information for disconnected operations; 
      ''' therefore, it is inappropriate for some client/server applications,
      ''' such as a mail server.
      ''' </summary>
      LOGON32_LOGON_INTERACTIVE = 2

      ''' <summary>
      ''' This logon type is intended for high performance servers to authenticate plaintext passwords.
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_NETWORK = 3

      ''' <summary>
      ''' This logon type is intended for batch servers, where processes may be executing on behalf of a user without 
      ''' their direct intervention. This type is also for higher performance servers that process many plaintext
      ''' authentication attempts at a time, such as mail or Web servers. 
      ''' The LogonUser function does not cache credentials for this logon type.
      ''' </summary>
      LOGON32_LOGON_BATCH = 4

      ''' <summary>
      ''' Indicates a service-type logon. The account provided must have the service privilege enabled. 
      ''' </summary>
      LOGON32_LOGON_SERVICE = 5

      ''' <summary>
      ''' This logon type is for GINA DLLs that log on users who will be interactively using the computer. 
      ''' This logon type can generate a unique audit record that shows when the workstation was unlocked. 
      ''' </summary>
      LOGON32_LOGON_UNLOCK = 7

      ''' <summary>
      ''' This logon type preserves the name and password in the authentication package, which allows the server to make 
      ''' connections to other network servers while impersonating the client. A server can accept plaintext credentials 
      ''' from a client, call LogonUser, verify that the user can access the system across the network, and still 
      ''' communicate with other servers.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NETWORK_CLEARTEXT = 8

      ''' <summary>
      ''' This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
      ''' The new logon session has the same local identifier but uses different credentials for other network connections. 
      ''' NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
      ''' NOTE: Windows NT:  This value is not supported. 
      ''' </summary>
      LOGON32_LOGON_NEW_CREDENTIALS = 9
    End Enum

    <DllImport("advapi32.dll", SetLastError:=True, CharSet:=CharSet.Unicode)> _
    Private Shared Function LogonUser(lpszUsername As [String], lpszDomain As [String], lpszPassword As [String], dwLogonType As Integer, dwLogonProvider As Integer, ByRef phToken As SafeTokenHandle) As Boolean
    End Function

    Public Sub New(Domain As String, UserName As String, Password As String, Optional LogonType As LogonTypes = LogonTypes.LOGON32_LOGON_INTERACTIVE)
      Dim ok = LogonUser(UserName, Domain, Password, LogonType, 0, _SafeTokenHandle)
      If Not ok Then
        Dim errorCode = Marshal.GetLastWin32Error()
        Throw New ApplicationException(String.Format("Could not impersonate the elevated user.  LogonUser returned error code {0}.", errorCode))
      End If

      WindowsImpersonationContext = WindowsIdentity.Impersonate(_SafeTokenHandle.DangerousGetHandle())
    End Sub

    Private ReadOnly _SafeTokenHandle As New SafeTokenHandle
    Private ReadOnly WindowsImpersonationContext As WindowsImpersonationContext

    Public Sub Dispose() Implements System.IDisposable.Dispose
      Me.WindowsImpersonationContext.Dispose()
      Me._SafeTokenHandle.Dispose()
    End Sub

    Public NotInheritable Class SafeTokenHandle
      Inherits SafeHandleZeroOrMinusOneIsInvalid

      <DllImport("kernel32.dll")> _
      <ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)> _
      <SuppressUnmanagedCodeSecurity()> _
      Private Shared Function CloseHandle(handle As IntPtr) As <MarshalAs(UnmanagedType.Bool)> Boolean
      End Function

      Public Sub New()
        MyBase.New(True)
      End Sub

      Protected Overrides Function ReleaseHandle() As Boolean
        Return CloseHandle(handle)
      End Function
    End Class

  End Class

You need to Use with a Using statement to contain some code to run impersonated.

JPA EntityManager: Why use persist() over merge()?

The JPA specification says the following about persist().

If X is a detached object, the EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time.

So using persist() would be suitable when the object ought not to be a detached object. You might prefer to have the code throw the PersistenceException so it fails fast.

Although the specification is unclear, persist() might set the @GeneratedValue @Id for an object. merge() however must have an object with the @Id already generated.

Checking if a list of objects contains a property with a specific value

You can use the Enumerable.Where extension method:

var matches = myList.Where(p => p.Name == nameToExtract);

Returns an IEnumerable<SampleClass>. Assuming you want a filtered List, simply call .ToList() on the above.


By the way, if I were writing the code above today, I'd do the equality check differently, given the complexities of Unicode string handling:

var matches = myList.Where(p => String.Equals(p.Name, nameToExtract, StringComparison.CurrentCulture));

See also

Marker in leaflet, click event

Here's a jsfiddle with a function call: https://jsfiddle.net/8282emwn/

var marker = new L.Marker([46.947, 7.4448]).on('click', markerOnClick).addTo(map);

function markerOnClick(e)
{
  alert("hi. you clicked the marker at " + e.latlng);
}

How to find the users list in oracle 11g db?

select * from all_users

This will work for sure

How can I de-install a Perl module installed via `cpan`?

  1. Install App::cpanminus from CPAN (use: cpan App::cpanminus for this).
  2. Type cpanm --uninstall Module::Name (note the "m") to uninstall the module with cpanminus.

This should work.

How to make HTML open a hyperlink in another window or tab?

Since web is evolving quickly, some things changes with time. For security issues, you might want to use the rel="noopener" attribute in conjuncture with your target="_blank".

Like stated in Google Dev Documentation, the other page can access your window object with the window.opener property. Your external link should looks like this now:

<a href="http://www.starfall.com/" target="_blank" rel="noopener">Starfall</a>

Print time in a batch file (milliseconds)

Below batch "program" should do what you want. Please note that it outputs the data in centiseconds instead of milliseconds. The precision of the used commands is only centiseconds.

Here is an example output:

STARTTIME: 13:42:52,25
ENDTIME: 13:42:56,51
STARTTIME: 4937225 centiseconds
ENDTIME: 4937651 centiseconds
DURATION: 426 in centiseconds
00:00:04,26

Here is the batch script:

@echo off
setlocal

rem The format of %TIME% is HH:MM:SS,CS for example 23:59:59,99
set STARTTIME=%TIME%

rem here begins the command you want to measure
dir /s > nul
rem here ends the command you want to measure

set ENDTIME=%TIME%

rem output as time
echo STARTTIME: %STARTTIME%
echo ENDTIME: %ENDTIME%

rem convert STARTTIME and ENDTIME to centiseconds
set /A STARTTIME=(1%STARTTIME:~0,2%-100)*360000 + (1%STARTTIME:~3,2%-100)*6000 + (1%STARTTIME:~6,2%-100)*100 + (1%STARTTIME:~9,2%-100)
set /A ENDTIME=(1%ENDTIME:~0,2%-100)*360000 + (1%ENDTIME:~3,2%-100)*6000 + (1%ENDTIME:~6,2%-100)*100 + (1%ENDTIME:~9,2%-100)

rem calculating the duratyion is easy
set /A DURATION=%ENDTIME%-%STARTTIME%

rem we might have measured the time inbetween days
if %ENDTIME% LSS %STARTTIME% set set /A DURATION=%STARTTIME%-%ENDTIME%

rem now break the centiseconds down to hors, minutes, seconds and the remaining centiseconds
set /A DURATIONH=%DURATION% / 360000
set /A DURATIONM=(%DURATION% - %DURATIONH%*360000) / 6000
set /A DURATIONS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000) / 100
set /A DURATIONHS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000 - %DURATIONS%*100)

rem some formatting
if %DURATIONH% LSS 10 set DURATIONH=0%DURATIONH%
if %DURATIONM% LSS 10 set DURATIONM=0%DURATIONM%
if %DURATIONS% LSS 10 set DURATIONS=0%DURATIONS%
if %DURATIONHS% LSS 10 set DURATIONHS=0%DURATIONHS%

rem outputing
echo STARTTIME: %STARTTIME% centiseconds
echo ENDTIME: %ENDTIME% centiseconds
echo DURATION: %DURATION% in centiseconds
echo %DURATIONH%:%DURATIONM%:%DURATIONS%,%DURATIONHS%

endlocal
goto :EOF

XSLT equivalent for JSON

To say lack of tools suggest lack of need is just begging the question. The same could be applied to support for X or Y in Linux (Why bother developing quality drivers and/or games for such a minority OS? And why pay attention to an OS that big game and hardware companies don't develop for?). Probably the people who would need to use XSLT and JSON end up using a somewhat trivial workaround: Transforming JSON into XML. But that's not the optimal solution, is it?

When you have a native JSON format and you want to edit it "wysywyg" in the browser, XSLT would be a more than adequate solution for the problem. Doing that with traditional javascript programming can become a pain in the arse.

In fact, I have implemented a "stone-age" approach to XSLT, using substring parsing to interpret some basic commands for javascript, like calling a template, process children, etc. Certainly implementing a transformation engine with a JSON object is much easier than implementing a full-fledged XML parser to parse the XSLT. Problem is, that to use XML templates to transform a JSON object you need to parse the XML of the templates.

To tranform a JSON object with XML (or HTML, or text or whatever) you need to think carefully about the syntax and what special characters you need to use to identify the transformation commands. Otherwise you'll end up having to design a parser for your own custom templating language. Having walked through that path, I can tell you that it's not pretty.

Update (Nov 12, 2010): After a couple of weeks working on my parser, I've been able to optimize it. Templates are parsed beforehand and commands are stored as JSON objects. Transformation rules are also JSON objects, while the template code is a mix of HTML and a homebrew syntax similar to shell code. I've been able to transform a complex JSON document into HTML to make a document editor. The code is around 1K lines for the editor (it's for a private project so I can't share it) and around 990 lines for the JSON transformation code (includes iteration commands, simple comparisons, template calling, variable saving and evaluation). I plan to release it under a MIT license. Drop me a mail if you want to get involved.

Calculating distance between two geographic locations

http://developer.android.com/reference/android/location/Location.html

Look into distanceTo

Returns the approximate distance in meters between this location and the given location. Distance is defined using the WGS84 ellipsoid.

or distanceBetween

Computes the approximate distance in meters between two locations, and optionally the initial and final bearings of the shortest path between them. Distance and bearing are defined using the WGS84 ellipsoid.

You can create a Location object from a latitude and longitude:

Location locationA = new Location("point A");

locationA.setLatitude(latA);
locationA.setLongitude(lngA);

Location locationB = new Location("point B");

locationB.setLatitude(latB);
locationB.setLongitude(lngB);

float distance = locationA.distanceTo(locationB);

or

private double meterDistanceBetweenPoints(float lat_a, float lng_a, float lat_b, float lng_b) {
    float pk = (float) (180.f/Math.PI);

    float a1 = lat_a / pk;
    float a2 = lng_a / pk;
    float b1 = lat_b / pk;
    float b2 = lng_b / pk;

    double t1 = Math.cos(a1) * Math.cos(a2) * Math.cos(b1) * Math.cos(b2);
    double t2 = Math.cos(a1) * Math.sin(a2) * Math.cos(b1) * Math.sin(b2);
    double t3 = Math.sin(a1) * Math.sin(b1);
    double tt = Math.acos(t1 + t2 + t3);
   
    return 6366000 * tt;
}

CURRENT_DATE/CURDATE() not working as default DATE value

I have the current latest version of MySQL: 8.0.20

So my table name is visit, my column name is curdate.

alter table visit modify curdate date not null default (current_date);

This writes the default date value with no timestamp.

Group by with multiple columns using lambda

Further to aduchis answer above - if you then need to filter based on those group by keys, you can define a class to wrap the many keys.

return customers.GroupBy(a => new CustomerGroupingKey(a.Country, a.Gender))
                .Where(a => a.Key.Country == "Ireland" && a.Key.Gender == "M")
                .SelectMany(a => a)
                .ToList();

Where CustomerGroupingKey takes the group keys:

    private class CustomerGroupingKey
    {
        public CustomerGroupingKey(string country, string gender)
        {
            Country = country;
            Gender = gender;
        }

        public string Country { get; }

        public string Gender { get; }
    }

Server.Transfer Vs. Response.Redirect

To be Short: Response.Redirect simply tells the browser to visit another page. Server.Transfer helps reduce server requests, keeps the URL the same and, with a little bug-bashing, allows you to transfer the query string and form variables.

Something I found and agree with (source):

Server.Transfer is similar in that it sends the user to another page with a statement such as Server.Transfer("WebForm2.aspx"). However, the statement has a number of distinct advantages and disadvantages.

Firstly, transferring to another page using Server.Transfer conserves server resources. Instead of telling the browser to redirect, it simply changes the "focus" on the Web server and transfers the request. This means you don't get quite as many HTTP requests coming through, which therefore eases the pressure on your Web server and makes your applications run faster.

But watch out: because the "transfer" process can work on only those sites running on the server; you can't use Server.Transfer to send the user to an external site. Only Response.Redirect can do that.

Secondly, Server.Transfer maintains the original URL in the browser. This can really help streamline data entry techniques, although it may make for confusion when debugging.

That's not all: The Server.Transfer method also has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.

For example, if your WebForm1.aspx has a TextBox control called TextBox1 and you transferred to WebForm2.aspx with the preserveForm parameter set to True, you'd be able to retrieve the value of the original page TextBox control by referencing Request.Form("TextBox1").

assignment operator overloading in c++

Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
    return *this;
}

I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).

As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.

Create a new database with MySQL Workbench

How to create database in MySQL Workbench 6.3

  1. In tab home (1) -> Right click on Local instance banner (2) -> Open Connection (3) enter image description here
  2. Right click on the empty space in schema window (1) -> Create schema (2) enter image description here
  3. Type name of database (1) -> Apply (2) enter image description here

Sqlite or MySql? How to decide?

My few cents to previous excellent replies. the site www.sqlite.org works on a sqlite database. Here is the link when the author (Richard Hipp) replies to a similar question.

Oracle Add 1 hour in SQL

select sysdate + 1/24 from dual;

sysdate is a function without arguments which returns DATE type
+ 1/24 adds 1 hour to a date

select to_char(to_date('2014-10-15 03:30:00 pm', 'YYYY-MM-DD HH:MI:SS pm') + 1/24, 'YYYY-MM-DD HH:MI:SS pm') from dual;

How to make HTML Text unselectable

The full modern solution to your problem is purely CSS-based, but note that older browsers won't support it, in which cases you'd need to fallback to solutions such as the others have provided.

So in pure CSS:

-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
-o-user-select: none;
user-select: none;

However the mouse cursor will still change to a caret when over the element's text, so you add to that:

cursor: default;

Modern CSS is pretty elegant.

how to access downloads folder in android?

If you are using Marshmallow, you have to either:

  1. Request permissions at runtime (the user will get to allow or deny the request) or:
  2. The user must go into Settings -> Apps -> {Your App} -> Permissions and grant storage access.

This is because in Marshmallow, Google completely revamped how permissions work.

Mockito : doAnswer Vs thenReturn

You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.

thenReturn(T value) Sets a return value to be returned when the method is called.

@Test
public void test_return() throws Exception {
    Dummy dummy = mock(Dummy.class);
    int returnValue = 5;

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenReturn(returnValue);
    doReturn(returnValue).when(dummy).stringLength("dummy");
}

Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.

Use doAnswer() when you want to stub a void method with generic Answer.

Answer specifies an action that is executed and a return value that is returned when you interact with the mock.

@Test
public void test_answer() throws Exception {
    Dummy dummy = mock(Dummy.class);
    Answer<Integer> answer = new Answer<Integer>() {
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            String string = invocation.getArgumentAt(0, String.class);
            return string.length() * 2;
        }
    };

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenAnswer(answer);
    doAnswer(answer).when(dummy).stringLength("dummy");
}

How to provide password to a command that prompts for one in bash?

Programs that prompt for passwords usually set the tty into "raw" mode, and read input directly from the tty. If you spawn the subprocess in a pty you can make that work. That is what Expect does...

How to add element in List while iterating in java?

Just iterate the old-fashion way, because you need explicit index handling:

List myList = ...
...
int length = myList.size();
for(int i = 0; i < length; i++) {
   String s = myList.get(i);
   // add items here, if you want to
}

Creating a simple configuration file and parser in C++

In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one.
In C++, lines can be read from a stream using std::getline(). While by default it will read up to the next '\n' (which it will consume, but not return), you can pass it some other delimiter, too, which makes it a good candidate for reading up-to-some-char, like = in your example.

For simplicity, the following presumes that the = are not surrounded by whitespace. If you want to allow whitespaces at these positions, you will have to strategically place is >> std::ws before reading the value and remove trailing whitespaces from the keys. However, IMO the little added flexibility in the syntax is not worth the hassle for a config file reader.

const char config[] = "url=http://example.com\n"
                      "file=main.exe\n"
                      "true=0";

std::istringstream is_file(config);

std::string line;
while( std::getline(is_file, line) )
{
  std::istringstream is_line(line);
  std::string key;
  if( std::getline(is_line, key, '=') )
  {
    std::string value;
    if( std::getline(is_line, value) ) 
      store_line(key, value);
  }
}

(Adding error handling is left as an exercise to the reader.)

How do I create a master branch in a bare Git repository?

A branch is just a reference to a commit. Until you commit anything to the repository, you don't have any branches. You can see this in a non-bare repository as well.

$ mkdir repo
$ cd repo
$ git init
Initialized empty Git repository in /home/me/repo/.git/
$ git branch
$ touch foo
$ git add foo
$ git commit -m "new file"
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 foo
$ git branch
* master

Scroll Element into View with Selenium

In Java we can scroll by using JavaScript, like in the following code:

driver.getEval("var elm = window.document.getElementById('scrollDiv'); if (elm.scrollHeight > elm.clientHeight){elm.scrollTop = elm.scrollHeight;}");

You can assign a desired value to the "elm.scrollTop" variable.

HTML5 Video tag not working in Safari , iPhone and iPad

I've seen weird issues with a non trusted 'development' SSL certificates where mobile Safari will quite happily serve your page but refuses to serve a video to a 'fake' SSL certificate even if you've accepted the certificate.

To test you can deploy the video elsewhere - or switch to http (for the whole page) and it should play.

How can you tell if a value is not numeric in Oracle?

You can use the following regular expression which will match integers (e.g., 123), floating-point numbers (12.3), and numbers with exponents (1.2e3):

^-?\d*\.?\d+([eE]-?\d+)?$

If you want to accept + signs as well as - signs (as Oracle does with TO_NUMBER()), you can change each occurrence of - above to [+-]. So you might rewrite your block of code above as follows:

IF (option_id = 0021) THEN 
    IF NOT REGEXP_LIKE(value, '^[+-]?\d*\.?\d+([eE][+-]?\d+)?$') OR TO_NUMBER(value) < 10000 OR TO_NUMBER(value) > 7200000 THEN
        ip_msg(6214,option_name);
        RETURN;
    END IF;
END IF;

I am not altogether certain that would handle all values so you may want to add an EXCEPTION block or write a custom to_number() function as @JustinCave suggests.

Copy files without overwrite

Robocopy, or "Robust File Copy", is a command-line directory replication command. It has been available as part of the Windows Resource Kit starting with Windows NT 4.0, and was introduced as a standard feature of Windows Vista, Windows 7 and Windows Server 2008.

   robocopy c:\Sourcepath c:\Destpath /E /XC /XN /XO

To elaborate (using Hydrargyrum, HailGallaxar and Andy Schmidt answers):

  • /E makes Robocopy recursively copy subdirectories, including empty ones.
  • /XC excludes existing files with the same timestamp, but different file sizes. Robocopy normally overwrites those.
  • /XN excludes existing files newer than the copy in the destination directory. Robocopy normally overwrites those.
  • /XO excludes existing files older than the copy in the destination directory. Robocopy normally overwrites those.

With the Changed, Older, and Newer classes excluded, Robocopy does exactly what the original poster wants - without needing to load a scripting environment.

References: Technet, Wikipedia
Download from: Microsoft Download Link (Link last verified on Mar 30, 2016)

What's the UIScrollView contentInset property for?

It's used to add padding in UIScrollView

Without contentInset, a table view is like this:

enter image description here

Then set contentInset:

tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)

The effect is as below:

enter image description here

Seems to be better, right?

And I write a blog to study the contentInset, criticism is welcome.

How do I get first element rather than using [0] in jQuery?

You can try like this:
yourArray.shift()

HTML5 iFrame Seamless Attribute

Still at 2014 seamless iframe is not fully supported by all of the major browsers, so you should look for an alternative solution.

By January 2014 seamless iframe is still not supported for Firefox neither IE 11, and it's supported by Chrome, Safari and Opera (the webkit version)

If you wanna check this and more supported options in detail, the HTML5 test site would be a good option:

http://html5test.com/results/desktop.html

You can check different platforms, at the score section you can click every browser and see what's supported and what's not.

How to specify HTTP error code?

Express deprecated res.send(body, status).

Use res.status(status).send(body) instead

Received fatal alert: handshake_failure through SSLHandshakeException

I found an HTTPS server which failed in this way if my Java client process was configured with

-Djsse.enableSNIExtension=false

The connection failed with handshake_failure after the ServerHello had finished successfully but before the data stream started.

There was no clear error message that identified the problem, the error just looked like

main, READ: TLSv1.2 Alert, length = 2
main, RECV TLSv1.2 ALERT:  fatal, handshake_failure
%% Invalidated:  [Session-3, TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384]
main, called closeSocket()
main, handling exception: javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I isolated the issue by trying with and without the "-Djsse.enableSNIExtension=false" option

Select elements by attribute

To select elements having a certain attribute, see the answers above.

To determine if a given jQuery element has a specific attribute I'm using a small plugin that returns true if the first element in ajQuery collection has this attribute:

/** hasAttr
 ** helper plugin returning boolean if the first element of the collection has a certain attribute
 **/
$.fn.hasAttr = function(attr) {
   return 0 < this.length
       && 'undefined' !== typeof attr
       && undefined !== attr
       && this[0].hasAttribute(attr)
}

How do I set bold and italic on UILabel of iPhone/iPad?

With iOS 7 system default font, you'll be using helvetica neue bold if you are looking to keep system default font.

    [titleText setFont:[UIFont fontWithName:@"HelveticaNeue-Bold" size:16.0]];

Or you can simply call it:

    [titleText setFont:[UIFont boldSystemFontOfSize:16.0]];

How to position the Button exactly in CSS

Try using absolute positioning, rather than relative positioning

this should get you close - you can adjust by tweaking margins or top/left positions

#play_button {
    position:absolute;
    transition: .5s ease;
    top: 50%;
    left: 50%;
}

http://jsfiddle.net/rolfsf/9pNqS/

How do I enable EF migrations for multiple contexts to separate databases?

EF 4.7 actually gives a hint when you run Enable-migrations at multiple context.

More than one context type was found in the assembly 'Service.Domain'.

To enable migrations for 'Service.Domain.DatabaseContext.Context1', 
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context1.
To enable migrations for 'Service.Domain.DatabaseContext.Context2',
use Enable-Migrations -ContextTypeName Service.Domain.DatabaseContext.Context2.

How can you undo the last git add?

  • Remove the file from the index, but keep it versioned and left with uncommitted changes in working copy:

    git reset head <file>
    
  • Reset the file to the last state from HEAD, undoing changes and removing them from the index:

    git reset HEAD <file>
    git checkout <file>
    
    # If you have a `<branch>` named like `<file>`, use:
    git checkout -- <file>
    

    This is needed since git reset --hard HEAD won't work with single files.

  • Remove <file> from index and versioning, keeping the un-versioned file with changes in working copy:

    git rm --cached <file>
    
  • Remove <file> from working copy and versioning completely:

    git rm <file>
    

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". in a Maven Project

I ran into this in IntelliJ and fixed it by adding the following to my pom:

<!-- logging dependencies -->
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>${logback.version}</version>
        <exclusions>
            <exclusion>
                <!-- Defined below -->
                <artifactId>slf4j-api</artifactId>
                <groupId>org.slf4j</groupId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>

Viewing full output of PS command

If none of the solutions above work, the output of ps isn't your problem. Maybe you need to set putty to wrap long lines?

Otherwise, we need more information.

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

Open the htdocs folder there will be index.php file. In that file script is written to go in dashboard folder and show dashboard. So you just have to comment it or delete that script and write any code save it and run http://localhost now dashboard screen will not open and you will see what you have written in that file.

C# 30 Days From Todays Date

@Ed courtenay, @James, I have one stupid question. How to keep user away from this file?(File containing expiry date). If the user has installation rights, then obviously user has access to view files also. Changing the extension of file wont help. So, how to keep this file safe and away from users hands?

img src SVG changing the styles with CSS

for that matters you have to use your SVG as an inline HTML.

say here's your logo.svg code (when you open it on textEditor):

Logo.SVG

<svg width="139" height="100" xmlns="http://www.w3.org/2000/svg">
    <!-- Note that I've Added Class Attribute 'logo-img' Here -->
    <g transform="translate(-22 -45)" fill="none" fill-rule="evenodd">
        <path
            d="M158.023 48.118a7.625 7.625 0 01-.266 10.78l-88.11 83.875a7.625 7.625 0 01-10.995-.5l-33.89-38.712a7.625 7.625 0 0111.475-10.045l28.653 32.73 82.353-78.394a7.625 7.625 0 0110.78.266z"
            fill="#00000" />
    </g>
</svg>

add your desired Class/ID to it (i've added 'logo-img'):

Edited Svg

<svg class="logo-img" width="139" height="100" xmlns="http://www.w3.org/2000/svg">
    <!-- Note that I've Added Class Attribute 'logo-img' Here -->
    ...
</svg>

Now apply Your Css Rules:

CSS

.logo-img path {
   fill: #000;
}

Pro

  • With this way you can animate on user's actions (hover, selected,...)

Con

  • Your HTML File would be a mess.

Heres a Stack Snippet

_x000D_
_x000D_
<style>
        body {
            display: flex;
            justify-content: center;
        }
        .logo-img path {
            transition: .5s all linear;
        }
        .logo-img path {
            fill: coral;
        }
        .logo-img:hover path{
            fill: darkblue;
        }
        
    </style>
_x000D_
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    
</head>

<body>
    <svg class="logo-img" width="139" height="100" xmlns="http://www.w3.org/2000/svg">
        <!-- Note that I've Added Class Attribute 'logo-img' Here -->
        <g transform="translate(-22 -45)" fill="none" fill-rule="evenodd">
            <path
                d="M158.023 48.118a7.625 7.625 0 01-.266 10.78l-88.11 83.875a7.625 7.625 0 01-10.995-.5l-33.89-38.712a7.625 7.625 0 0111.475-10.045l28.653 32.73 82.353-78.394a7.625 7.625 0 0110.78.266z"
                fill="#00000" />
        </g>
    </svg>
</body>

</html>
_x000D_
_x000D_
_x000D_

Make header and footer files to be included in multiple html pages

Must you use html file structure with JavaScript? Have you considered using PHP instead so that you can use simple PHP include object?

If you convert the file names of your .html pages to .php - then at the top of each of your .php pages you can use one line of code to include the content from your header.php

<?php include('header.php'); ?>

Do the same in the footer of each page to include the content from your footer.php file

<?php include('footer.php'); ?>

No JavaScript / Jquery or additional included files required.

NB You could also convert your .html files to .php files using the following in your .htaccess file

# re-write html to php
RewriteRule ^(.*)\.html$ $1.php [L]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]


# re-write no extension to .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

Extracting specific columns from a data frame

You can subset using a vector of column names. I strongly prefer this approach over those that treat column names as if they are object names (e.g. subset()), especially when programming in functions, packages, or applications.

# data for reproducible example
# (and to avoid confusion from trying to subset `stats::df`)
df <- setNames(data.frame(as.list(1:5)), LETTERS[1:5])
# subset
df[c("A","B","E")]

Note there's no comma (i.e. it's not df[,c("A","B","C")]). That's because df[,"A"] returns a vector, not a data frame. But df["A"] will always return a data frame.

str(df["A"])
## 'data.frame':    1 obs. of  1 variable:
## $ A: int 1
str(df[,"A"])  # vector
##  int 1

Thanks to David Dorchies for pointing out that df[,"A"] returns a vector instead of a data.frame, and to Antoine Fabri for suggesting a better alternative (above) to my original solution (below).

# subset (original solution--not recommended)
df[,c("A","B","E")]  # returns a data.frame
df[,"A"]             # returns a vector

what is numeric(18, 0) in sql server 2008 r2

The first value is the precision and the second is the scale, so 18,0 is essentially 18 digits with 0 digits after the decimal place. If you had 18,2 for example, you would have 18 digits, two of which would come after the decimal...

example of 18,2: 1234567890123456.12

There is no functional difference between numeric and decimal, other that the name and I think I recall that numeric came first, as in an earlier version.

And to answer, "can I add (-10) in that column?" - Yes, you can.

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

Running Python from Atom

Yes, you can do it by:

-- Install Atom

-- Install Python on your system. Atom requires the latest version of Python (currently 3.8.5). Note that Anaconda sometimes may not have this version, and depending on how you installed it, it may not have been added to the PATH. Install Python via https://www.python.org/ and make sure to check the option of "Add to PATH"

-- Install "scripts" on Atom via "Install packages"

-- Install any other autocomplete package like Kite on Atom if you want that feature.

-- Run it

I tried the normal way (I had Python installed via Anaconda) but Atom did not detect it & gave me an error when I tried to run Python. This is the way around it.

Android Studio - Auto complete and other features not working

'The file size (2561270 bytes) exceeds configured limit (2560000 bytes). Code insight features are not available.' 

Had this issue for days with none of these proposed solutions working before eventually getting this message in yellow under the tabs after adding a line of code. Removing the line of code eliminated the message but not the issue. There appears to be a code size window where you lose insight features but don't get this message, at least for me. Once you go over a certain point the message finally pops up. The suggested solution in a different thread for this issue was to edit 'Help/Edit Custom Properties' to increase the configured limit, but just opening this brought up a dialogue asking if I wanted to create an 'idea.properties' folder so I decided not to risk that approach over eventually cutting the file size.

Programmatically navigate using react router V4

I had a similar issue when migrating over to React-Router v4 so I'll try to explain my solution below.

Please do not consider this answer as the right way to solve the problem, I imagine there's a good chance something better will arise as React Router v4 becomes more mature and leaves beta (It may even already exist and I just didn't discover it).

For context, I had this problem because I occasionally use Redux-Saga to programmatically change the history object (say when a user successfully authenticates).

In the React Router docs, take a look at the <Router> component and you can see you have the ability to pass your own history object via a prop. This is the essence of the solution - we supply the history object to React-Router from a global module.

Steps:

  1. Install the history npm module - yarn add history or npm install history --save
  2. create a file called history.js in your App.js level folder (this was my preference)

    // src/history.js
    
    import createHistory from 'history/createBrowserHistory';
    export default createHistory();`
    
  3. Add this history object to your Router component like so

    // src/App.js
    
    import history from '../your/path/to/history.js;'
    <Router history={history}>
    // Route tags here
    </Router>
    
  4. Adjust the URL just like before by importing your global history object:

    import history from '../your/path/to/history.js;'
    history.push('new/path/here/');
    

Everything should stay synced up now, and you also have access to a way of setting the history object programmatically and not via a component/container.

Printing out a number in assembly language?

PRINT_SUM PROC NEAR
 CMP AL, 0
 JNE PRINT_AX
 PUSH AX
 MOV AL, '0'
 MOV AH, 0EH
 INT 10H
 POP AX
 RET 
    PRINT_AX:    
 PUSHA
 MOV AH, 0
 CMP AX, 0
 JE PN_DONE
 MOV DL, 10
 DIV DL    
 CALL PRINT_AX
 MOV AL, AH
 ADD AL, 30H
 MOV AH, 0EH
 INT 10H    
    PN_DONE:
 POPA  
 RET  
PRINT_SUM ENDP

Using CRON jobs to visit url?

you can use this for url with parameters:

lynx -dump "http://vps-managed.com/tasks.php?code=23456"

lynx is available on all systems by default.

Loading a properties file from Java package

Assuming your using the Properties class, via its load method, and I guess you are using the ClassLoader getResourceAsStream to get the input stream.

How are you passing in the name, it seems it should be in this form: /com/al/common/email/templates/foo.properties

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

An IDE is an integrated development environment - a suped-up text editor with additional support for developing (such as forms designers, resource editors, etc), compiling and debugging applications. e.g Eclipse, Visual Studio.

A Library is a chunk of code that you can call from your own code, to help you do things more quickly/easily. For example, a Bitmap Processing library will provide facilities for loading and manipulating bitmap images, saving you having to write all that code for yourself. Typically a library will only offer one area of functionality (processing images or operating on zip files)

An API (application programming interface) is a term meaning the functions/methods in a library that you can call to ask it to do things for you - the interface to the library.

An SDK (software development kit) is a library or group of libraries (often with extra tool applications, data files and sample code) that aid you in developing code that uses a particular system (e.g. extension code for using features of an operating system (Windows SDK), drawing 3D graphics via a particular system (DirectX SDK), writing add-ins to extend other applications (Office SDK), or writing code to make a device like an Arduino or a mobile phone do what you want). An SDK will still usually have a single focus.

A toolkit is like an SDK - it's a group of tools (and often code libraries) that you can use to make it easier to access a device or system... Though perhaps with more focus on providing tools and applications than on just code libraries.

A framework is a big library or group of libraries that provides many services (rather than perhaps only one focussed ability as most libraries/SDKs do). For example, .NET provides an application framework - it makes it easier to use most (if not all) of the disparate services you need (e.g. Windows, graphics, printing, communications, etc) to write a vast range of applications - so one "library" provides support for pretty much everything you need to do. Often a framework supplies a complete base on which you build your own code, rather than you building an application that consumes library code to do parts of its work.

There are of course many examples in the wild that won't exactly match these descriptions though.

Random character generator with a range of (A..Z, 0..9) and punctuation

See below link : http://www.asciitable.com/

public static char randomSeriesForThreeCharacter() {
    Random r = new Random();
    char random_3_Char = (char) (48 + r.nextInt(47));
    return random_3_Char;
}

Now you can generate a character at one time of calling.

Loaded nib but the 'view' outlet was not set

I had a similar problem with Xcode 9.3, and setting "Module" under the "File Owner's" attribute inspector to the project module fixed this for me.

CSS Positioning Elements Next to each other

If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:

float:left; display:inline; width: 49%;

on both of them.

#mainContent, #sideContent {float:left; display:inline; width: 49%;}

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

What is the curl error 52 "empty reply from server"?

It happens when you are trying to access secure Website like Https.

I hope you missed 's'

Try Changing URL to curl -sS -u "username:password" https://www.example.com/backup.php

How to kill an application with all its activities?

When the user wishes to exit all open activities, they should press a button which loads the first Activity that runs when your app starts, in my case "LoginActivity".

Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);

The above code clears all the activities except for LoginActivity. LoginActivity is the first activity that is brought up when the user runs the program. Then put this code inside the LoginActivity's onCreate, to signal when it should self destruct when the 'Exit' message is passed.

    if (getIntent().getBooleanExtra("EXIT", false)) {
         finish();
    }

The answer you get to this question from the Android platform is: "Don't make an exit button. Finish activities the user no longer wants, and the Activity manager will clean them up as it sees fit."

No connection could be made because the target machine actively refused it 127.0.0.1

Had the same problem, it turned out it was the WindowsFirewall blocking connections. Try to disable WindowsFirewall for a while to see if helps and if it is the problem open ports as needed.

Clip/Crop background-image with CSS

may be you can write like this:

#graphic { 
 background-image: url(image.jpg); 
 background-position: 0 -50px; 
 width: 200px; 
 height: 100px;
}

127 Return code from $?

A shell convention is that a successful executable should exit with the value 0. Anything else can be interpreted as a failure of some sort, on part of bash or the executable you that just ran. See also $PIPESTATUS and the EXIT STATUS section of the bash man page:

   For  the shell’s purposes, a command which exits with a zero exit status has succeeded.  An exit status
   of zero indicates success.  A non-zero exit status indicates failure.  When a command terminates  on  a
   fatal signal N, bash uses the value of 128+N as the exit status.
   If  a command is not found, the child process created to execute it returns a status of 127.  If a com-
   mand is found but is not executable, the return status is 126.

   If a command fails because of an error during expansion or redirection, the exit status is greater than
   zero.

   Shell  builtin  commands  return  a  status of 0 (true) if successful, and non-zero (false) if an error
   occurs while they execute.  All builtins return an exit status of 2 to indicate incorrect usage.

   Bash itself returns the exit status of the last command executed, unless  a  syntax  error  occurs,  in
   which case it exits with a non-zero value.  See also the exit builtin command below.

Controller not a function, got undefined, while defining controllers globally

I got this problem because I had wrapped a controller-definition file in a closure:

(function() {
   ...stuff...
});

But I had forgotten to actually invoke that closure to execute that definition code and actually tell Javascript my controller existed. I.e., the above needs to be:

(function() {
   ...stuff...
})();

Note the () at the end.

Long vs Integer, long vs int, what to use and when?

a) object Class "Long" versus primitive type "long". (At least in Java)

b) There are different (even unclear) memory-sizes of the primitive types:

Java - all clear: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

  • byte, char .. 1B .. 8b
  • short int .. 2B .. 16b
  • int .. .. .. .. 4B .. 32b
  • long int .. 8B .. 64b

C .. just mess: https://en.wikipedia.org/wiki/C_data_types

  • short .. .. 16b
  • int .. .. .. 16b ... wtf?!?!
  • long .. .. 32b
  • long long .. 64b .. mess! :-/

Convert String to Type in C#

You can only use just the name of the type (with its namespace, of course) if the type is in mscorlib or the calling assembly. Otherwise, you've got to include the assembly name as well:

Type type = Type.GetType("Namespace.MyClass, MyAssembly");

If the assembly is strongly named, you've got to include all that information too. See the documentation for Type.GetType(string) for more information.

Alternatively, if you have a reference to the assembly already (e.g. through a well-known type) you can use Assembly.GetType:

Assembly asm = typeof(SomeKnownType).Assembly;
Type type = asm.GetType(namespaceQualifiedTypeName);

Installing NumPy and SciPy on 64-bit Windows (with Pip)

Package version are very important.

I found some stable combination that works on my Windows10 64 bit machine:

pip install numpy-1.12.0+mkl-cp36-cp36m-win64.whl
pip install scipy-0.18.1-cp36-cp36m-win64.whl
pip install matplotlib-2.0.0-cp36-cp36m-win64.whl

Source.